问:
Vuex - update object in mutation
After the user clicks a button I want to replace the data in my vuex store with the data from my local object. But I am stuck at the mutation. Here is some code for more details.

This is the method that is called after the user clicks a button.
(this.tableview is a local object with the same values as the vuex object)

```<code>            updateVuexTableview() {
                // eslint-disable-next-line no-console
                console.log("Update Vuex Table view");
                this.updateTableview(this.tableview)
            }
</code>```

In this method my vuex action is called. Which looks like this:
(updTableview is the new data that I want to insert)

```<code>async updateTableview({commit}, updTableview) {
        const response = await axios.put(
            `http://localhost:3000/tableview`,
            updTableview
        );

        // eslint-disable-next-line no-console
        console.log(response.data);

        commit('updateTableviewMut', response.data);
    },
</code>```

This is the mutation that is called. That's where I am stuck. I have tried to pop the data and push it again, but nothing works so far.

```<code>    updateTableviewMut: (state, updTableview) => {
        state.tableview.push(updTableview)
    },
</code>```

This right here is my state:

```<code>const state = {
    tableview: {
        "thema_c": true,
        "status_c": true,
        "priority_c": true,
        "custom1_c": true,
        "custom2_c": true,
        "customFieldName1": "Custom1",
        "customFieldName2": "Custom2"
    },
};
</code>```

答:
You cannot update an object by .push you have to reassign object or set a specific field.
Just change your code like this:
If you want to add a key value pair you can do:

```<code>updateTableviewMut: (state, updTableview) => {
  state.tableview['keyname'] = updTableview
}
</code>```

Or if you want to reassign an object you can do:

```<code>updateTableviewMut: (state, updTableview) => {
  state.tableview = updTableview
}

</code>```

Title: Vuex - update object in mutation

Body:
After the user clicks a button I want to replace the data in my vuex store with the data from my local object. But I am stuck at the mutation. Here is some code for more details.

This is the method that is called after the user clicks a button.
(this.tableview is a local object with the same values as the vuex object)

            updateVuexTableview() {
                // eslint-disable-next-line no-console
                console.log("Update Vuex Table view");
                this.updateTableview(this.tableview)
            }

In this method my vuex action is called. Which looks like this:
(updTableview is the new data that I want to insert)

async updateTableview({commit}, updTableview) {
        const response = await axios.put(
            `http://localhost:3000/tableview`,
            updTableview
        );

        // eslint-disable-next-line no-console
        console.log(response.data);

        commit('updateTableviewMut', response.data);
    },

This is the mutation that is called. That's where I am stuck. I have tried to pop the data and push it again, but nothing works so far.

    updateTableviewMut: (state, updTableview) => {
        state.tableview.push(updTableview)
    },

This right here is my state:

const state = {
    tableview: {
        "thema_c": true,
        "status_c": true,
        "priority_c": true,
        "custom1_c": true,
        "custom2_c": true,
        "customFieldName1": "Custom1",
        "customFieldName2": "Custom2"
    },
};

Body:
You cannot update an object by .push you have to reassign object or set a specific field.
Just change your code like this:
If you want to add a key value pair you can do:

updateTableviewMut: (state, updTableview) => {
  state.tableview['keyname'] = updTableview
}

Or if you want to reassign an object you can do:

updateTableviewMut: (state, updTableview) => {
  state.tableview = updTableview
}


来源: stackexchange

问:
Set up a scheduled job?
I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically.

Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this.

Does anyone know how to set this up?

To clarify:  I know I can set up a cron job to do this, but I'm curious if there is some feature in Django that provides this functionality.   I'd like people to be able to deploy this app themselves without having to do much config (preferably zero).

I've considered triggering these actions "retroactively" by simply checking if a job should have been run since the last time a request was sent to the site, but I'm hoping for something a bit cleaner.

答:
after the part of code,I can write anything just like my views.py :)

```<code>#######################################
import os,sys
sys.path.append('/home/administrator/development/store')
os.environ['DJANGO_SETTINGS_MODULE']='store.settings'
from django.core.management impor setup_environ
from store import settings
setup_environ(settings)
#######################################
</code>```

from
http://www.cotellese.net/2007/09/27/running-external-scripts-against-django-models/

OwnerDisplayName: TM

ContentLicense: CC BY-SA 4.0

Title: Set up a scheduled job?

LastEditorDisplayName: TM

Body:
after the part of code,I can write anything just like my views.py :)

#######################################
import os,sys
sys.path.append('/home/administrator/development/store')
os.environ['DJANGO_SETTINGS_MODULE']='store.settings'
from django.core.management impor setup_environ
from store import settings
setup_environ(settings)
#######################################

from
http://www.cotellese.net/2007/09/27/running-external-scripts-against-django-models/

ContentLicense: CC BY-SA 3.0


问:
Disable "Upload" in Jupyter notebook
I am using Amazon EC2 AMI deep learning.
how can I revoke permission of uploading a file in jupyter notebook? Is there any way I can deny user from uploading any new files from their local machine? </p>

答:
This is an open issue on the jupyter github:
https://github.com/jupyter/jupyter/issues/293

A way to disable downloading is described here:
https://ujjwalbhardwaj.me/post/disable-download-button-on-the-sagemaker-jupyter-notebook

I haven't tested it myself, but I can image that overriding the files_handler_class with None in the latter example could also prevent uploads.

```<code>c.ContentsManager.files_handler_class = None
</code>```

Title: Disable "Upload" in Jupyter notebook

Body:
This is an open issue on the jupyter github:
https://github.com/jupyter/jupyter/issues/293

A way to disable downloading is described here:
https://ujjwalbhardwaj.me/post/disable-download-button-on-the-sagemaker-jupyter-notebook

I haven't tested it myself, but I can image that overriding the files_handler_class with None in the latter example could also prevent uploads.

c.ContentsManager.files_handler_class = None


问:
How to search and modify floating values that follow a string in a file using Perl
Lets say we have "abc {{1.1 2.2}}" occurring multiple times in a file and I want to modify it to "xyz {{2.2 4.4}}" which is basically:

Change abc to xyz.

And multiply the floating values by 2 that appear in the curly braces (always preceded by abc keyword).

```<code>abc {{1.1 2.2}} ----------> xyz {{2.2 4.4}}
</code>```

This modification must be done to all instances of the file.
Here's the code that I tried but was able to replace only abc to xyz and couldn't figure out how to do the operations by extracting those floating values.

```<code>#!/usr/bin/perl -w

use strict;

open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);

foreach(@lines) {
   $_ =~ s/abc/xyz/g;
}

open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);
</code>```

Any sort of help is highly appreciated.

答:
My Perl regex is rusty but something like this should help:

use Test::More tests => 6;

sub match_and_replace
{
    $_[0] =~ /abc \{\{([+-]?([0-9]*[.])?[0-9]+) ([+-]?([0-9]*[.])?[0-9]+)}}/;
    my $my1 = $1*2;
    my $my3 = $3*2;
    my $ret = $_[0];
    $ret =~ s/abc \{\{$1 $3}}/xyz \{\{$my1 $my3}}/g;
    return $ret;
}

is(match_and_replace('abc {{1.1 2.2}}'), 'xyz {{2.2 4.4}}', 'simple float');
is(match_and_replace('abc {{12.12 23.23}}'), 'xyz {{24.24 46.46}}', 'bigger float');
is(match_and_replace('abc {{1.99 99.1}}'), 'xyz {{3.98 198.2}}', 'another float');
is(match_and_replace('abc {{.5 .5}}'), 'xyz {{1 1}}', 'only fractional part');
is(match_and_replace('abc {{2 6}}'), 'xyz {{4 12}}', 'only integer part');
is(match_and_replace('abc'), 'abc', 'no match');
```

Body:
Lets say we have "abc {{1.1 2.2}}" occurring multiple times in a file and I want to modify it to "xyz {{2.2 4.4}}" which is basically:

Change abc to xyz.

And multiply the floating values by 2 that appear in the curly braces (always preceded by abc keyword).

abc {{1.1 2.2}} ----------> xyz {{2.2 4.4}}

This modification must be done to all instances of the file.
Here's the code that I tried but was able to replace only abc to xyz and couldn't figure out how to do the operations by extracting those floating values.

#!/usr/bin/perl -w

use strict;

open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);

foreach(@lines) {
   $_ =~ s/abc/xyz/g;
}

open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);

Any sort of help is highly appreciated.


问:
Download artifact contents from another pipeline build
I have two azure devops pipelines as follows:

the first one creates an artifact under the name 'AncientArtifact-1.2.0.$(Build.BuildId)'.

the second one is trying to use this artifact using the Download Build Artifacts task configured as follows:

This creates a folder named 'AncientArtifact-1.2.0.12345' (first pipeline most recent BuildId=12345) inside a $(CustomDestinationFolder) in the second pipeline build.

I want to rename the above folder to something like 'ancient' and move it to another directory within the second pipeline build to be included in the second pipeline artifact.

I have tried using the copy files task but the problem is I don't know the name of the downloaded artifact folder thus I can only specify its parent $(CustomDestinationFolder) as source folder and so my destination folder will look something like $(destinationFolder)\AncientArtifact-1.2.0.12345*.
Using the flattenFolders option will flatten everything and that is not what I want.

Some approaches come to mind:

Remove the $(Build.BuildId) from the artifact name. This way I know the exact name that the downloaded artifact will have. The issue is that I would like to keep it.

A custom script in the second pipeline that would list the folders inside the $(CustomDestinationFolder), get the name of the artifact folder rename it a hardcoded 'ancient' name. It feels quite hackish.

Is there a better way to handle this?

答:
Different with Eric, here I just follow your idea1 by keeping $(Build.buildId) specified in artifact name.

If you set the system.debug of pipeline2 as true, you will see that the task DownloadBuildArtifacts itself generate one environment variable based on different builds used: BuildNumber

Just make use of it, set reference name of DownloadBuildArtifacts task: ref.

Then, you can call this variable to get buildid value during next steps: $(ref.BuildNumber).

Meanwhile, you can use copy files task by keeping the artifact name contain the $(Build.BuildId) value in it.


问:
Why Hibernate inlines Integer parameter list passed to JPA Criteria Query?
I am building a query using JPA Criteria API. When I created two restriction predicates using javax.persistence.criteria.Path#in(Collection<?>) method the generated SQL query was a little bit different than I excpected.

The first predicate which was build over int attribute produced SQL with all elements of parameter collection inlined: in (10, 20, 30).

The second predicate which was build over String attribute produced parametrized SQL: in (?, ?, ?).

Let me show:

Entity:

```<code>@Entity
public class A {
    @Id
    private Integer id;
    private int intAttr;
    private String stringAttr;
    //getter/setters
}
</code>```

Query:

```<code>CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<A> q = cb.createQuery(A.class);
Root<A> root = q.from(A.class);
q.where(
    root.get("intAttr").in(Arrays.asList(10, 20, 30)),
    root.get("stringAttr").in(Arrays.asList("a", "b", "c"))
);
entityManager.createQuery(q).getResultList();
</code>```

Log:

```<code>select
    a0_.id as id1_0_,
    a0_.intAttr as intAttr2_0_,
    a0_.stringAttr as stringAt3_0_
from
    A a0_
where
    (
        a0_.intAttr in (
            10 , 20 , 30
        )
    )
    and (
        a0_.stringAttr in (
            ? , ? , ?
        )
    )
org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [a]
org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [2] as [VARCHAR] - [b]
org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [3] as [VARCHAR] - [c]
</code>```

My questions:

Why are elements of Integer list inlined directly to sql and elements of String list are handled as prepared statement parameters?

Is this feature Hibernate specific or is it guaranteed by JPA?

From DB perspective which of two should be preferred?

Is this int-yes string-no inlining somehow related to sql injection?

Is this somehow related to limitation of number of values in sql IN clause the RDMBS can process?

How to write a criteria query which will handle Integer parameter list the same way as String parameter list.

答:
In issue HHH-9576 a new parameter was added to fix this issue, applicable since version 5.2.12 (?)

```<code><property name="hibernate.criteria.literal_handling_mode" value="bind"/>
</code>```

If you use this parameter you don't need the verbose solution proposed by Pace anymore.

From hibernate documentation of literal_handling_mode:

This enum defines how literals are handled by JPA Criteria. By default (AUTO), Criteria queries uses bind parameters for any literal that is not a numeric value. However, to increase the likelihood of JDBC statement caching, you might want to use bind parameters for numeric values too. The BIND mode will use bind variables for any literal value. The INLINE mode will inline literal values as-is. To prevent SQL injection, never use INLINE with String variables. Always use constants with the INLINE mode.

Body:
I am building a query using JPA Criteria API. When I created two restriction predicates using javax.persistence.criteria.Path#in(Collection<?>) method the generated SQL query was a little bit different than I excpected.

The first predicate which was build over int attribute produced SQL with all elements of parameter collection inlined: in (10, 20, 30).

The second predicate which was build over String attribute produced parametrized SQL: in (?, ?, ?).

Let me show:

Entity:

@Entity
public class A {
    @Id
    private Integer id;
    private int intAttr;
    private String stringAttr;
    //getter/setters
}

Query:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery q = cb.createQuery(A.class);
Root root = q.from(A.class);
q.where(
    root.get("intAttr").in(Arrays.asList(10, 20, 30)),
    root.get("stringAttr").in(Arrays.asList("a", "b", "c"))
);
entityManager.createQuery(q).getResultList();

Log:

select
    a0_.id as id1_0_,
    a0_.intAttr as intAttr2_0_,
    a0_.stringAttr as stringAt3_0_
from
    A a0_
where
    (
        a0_.intAttr in (
            10 , 20 , 30
        )
    )
    and (
        a0_.stringAttr in (
            ? , ? , ?
        )
    )
org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [a]
org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [2] as [VARCHAR] - [b]
org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [3] as [VARCHAR] - [c]

My questions:

Why are elements of Integer list inlined directly to sql and elements of String list are handled as prepared statement parameters?

Is this feature Hibernate specific or is it guaranteed by JPA?

From DB perspective which of two should be preferred?

Is this int-yes string-no inlining somehow related to sql injection?

Is this somehow related to limitation of number of values in sql IN clause the RDMBS can process?

How to write a criteria query which will handle Integer parameter list the same way as String parameter list.

Body:
In issue HHH-9576 a new parameter was added to fix this issue, applicable since version 5.2.12 (?)

<property name="hibernate.criteria.literal_handling_mode" value="bind"/>

If you use this parameter you don't need the verbose solution proposed by Pace anymore.

From hibernate documentation of literal_handling_mode:

This enum defines how literals are handled by JPA Criteria. By default (AUTO), Criteria queries uses bind parameters for any literal that is not a numeric value. However, to increase the likelihood of JDBC statement caching, you might want to use bind parameters for numeric values too. The BIND mode will use bind variables for any literal value. The INLINE mode will inline literal values as-is. To prevent SQL injection, never use INLINE with String variables. Always use constants with the INLINE mode.


问:
spring-data-cassandra CassandraBatchTemplate is not public
I want to use CassandraBatchTemplate's withTimestamp to insert client side timestamp like USING TIMESTAMP clause in the CQL. here is my code:

```<code>  @Bean
  public DseSession dseSession(DseCluster dseCluster) {
    return dseCluster.connect(keyspace);
  }

  @Bean
  public CassandraOperations cassandraTemplate(DseSession session) {
    return new CassandraTemplate(session);
  }

  @Bean
  public CassandraBatchOperations cassdraBatchTemplate(CassandraOperations cassandraTemplate) {
    return new CassandraBatchTemplate(cassandraTemplate);
  }
</code>```

when compiled it complained cannot find CassandraBatchTemplate even though i can see it in spring-data-cassandra source code. one thing i noticed is that CassandraBatchTemplate is default implementation of interface CassandraBatchOperations, thus no 'public' is applied to CassandraBatchTemplate class:

```<code>class CassandraBatchTemplate implements CassandraBatchOperations {...}
</code>```

if the class is not public then I cannot create an instance of it by 'new'. how to work around? I'm using spring-data-cassandra 2.1.10.RELEASE and dse-java-driver-core 1.8.2

答:
CassandraBatchTemplate isn't public because it has a very limited lifecycle. It isn't intended to be used as @Bean because it is only valid for a single execution.

Instead, obtain CassandraBatchOperations through CassandraOperations.batchOps().

Body:
I want to use CassandraBatchTemplate's withTimestamp to insert client side timestamp like USING TIMESTAMP clause in the CQL. here is my code:

  @Bean
  public DseSession dseSession(DseCluster dseCluster) {
    return dseCluster.connect(keyspace);
  }

  @Bean
  public CassandraOperations cassandraTemplate(DseSession session) {
    return new CassandraTemplate(session);
  }

  @Bean
  public CassandraBatchOperations cassdraBatchTemplate(CassandraOperations cassandraTemplate) {
    return new CassandraBatchTemplate(cassandraTemplate);
  }

when compiled it complained cannot find CassandraBatchTemplate even though i can see it in spring-data-cassandra source code. one thing i noticed is that CassandraBatchTemplate is default implementation of interface CassandraBatchOperations, thus no 'public' is applied to CassandraBatchTemplate class:

class CassandraBatchTemplate implements CassandraBatchOperations {...}

if the class is not public then I cannot create an instance of it by 'new'. how to work around? I'm using spring-data-cassandra 2.1.10.RELEASE and dse-java-driver-core 1.8.2


问:
Problems with Ember, PostCSS, SASS and @apply
I'm trying to use TailwindCSS in my ember app and I ended up using this add-on to do this. But unfortunately some other add-ons require to include their 'scss' files to app styles. So I tried to add 'postcss-sass' to make it work. But it doesn't want to work with "@apply" command. Is it possible to use postcss and sass and @apply command at the moment?

My ember-cli-build.js:

```<code>postcssOptions: {
      compile: {
        extension: 'scss',
        enabled: true,
        parser: require('postcss-scss'),
        plugins: [
          {
            module: require('@csstools/postcss-sass'),
            options: {
              includePaths: ['node_modules']
            }
          },
          require('tailwindcss')('./app/tailwind/config.js'),
          ...isProduction ? [purgeCSS] : []
        ]
      }
    }
</code>```

And I'm getting an error: UnhandledPromiseRejectionWarning: Error: Invalid mapping: {"generated":{"line":53,"column":-1},"source":"../../out-338-broccoli_merge_trees_full_application/app/styles/app.scss","original":{"line":52,"column":25},"name":null}

This is precisely where @apply appeared the first time.

答: It turned out the problem was with a missing semicolon in "app.scss". It worked fine when it was a plain css, and stopped working when I converted it to SASS.</p>

Body:
I'm trying to use TailwindCSS in my ember app and I ended up using this add-on to do this. But unfortunately some other add-ons require to include their 'scss' files to app styles. So I tried to add 'postcss-sass' to make it work. But it doesn't want to work with "@apply" command. Is it possible to use postcss and sass and @apply command at the moment?

My ember-cli-build.js:

postcssOptions: {
      compile: {
        extension: 'scss',
        enabled: true,
        parser: require('postcss-scss'),
        plugins: [
          {
            module: require('@csstools/postcss-sass'),
            options: {
              includePaths: ['node_modules']
            }
          },
          require('tailwindcss')('./app/tailwind/config.js'),
          ...isProduction ? [purgeCSS] : []
        ]
      }
    }

And I'm getting an error: UnhandledPromiseRejectionWarning: Error: Invalid mapping: {"generated":{"line":53,"column":-1},"source":"../../out-338-broccoli_merge_trees_full_application/app/styles/app.scss","original":{"line":52,"column":25},"name":null}

This is precisely where @apply appeared the first time.


问:
Download excel file already existing in Shiny
I'm trying to donwload an excel file already existing in my shiny app.

I've tried following code in server.R

```<code>   output$downloadbutton <- downloadHandler(

     filename <- function() {
       paste("result_balance", "xlsx", sep=".")
     },
     content <- function(file) {
       #temp <- file.path(tempdir(), "report.Rmd")
       file.copy(file.path(getwd(),'www','result.xlsx'), file,overwrite = TRUE)
     },
     contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
   )
</code>```

but when user click on Download button it appears a download pop up like this:

and it will download a folder with xml/html files in it.
Weird is that the proposed name is downloadbutton like my id shiny element.

I'm already aware of this R Shiny: Download existing file.

R version 3.6.2 on Ubuntu 18.04

答:
filename and content are arguments of the function downloadHandler, thus you have to use = and not <-:

```<code> output$downloadbutton <- downloadHandler(

     filename = function() {
       paste("result_balance", "xlsx", sep=".")
     },
     content = function(file) {
       #temp <- file.path(tempdir(), "report.Rmd")
       file.copy(file.path(getwd(),'www','result.xlsx'), file,overwrite = TRUE)
     },
     contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
   )
</code>```

Body:
I'm trying to donwload an excel file already existing in my shiny app.

I've tried following code in server.R

   output$downloadbutton <- downloadHandler(

     filename <- function() {
       paste("result_balance", "xlsx", sep=".")
     },
     content <- function(file) {
       #temp <- file.path(tempdir(), "report.Rmd")
       file.copy(file.path(getwd(),'www','result.xlsx'), file,overwrite = TRUE)
     },
     contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
   )

but when user click on Download button it appears a download pop up like this:

and it will download a folder with xml/html files in it.
Weird is that the proposed name is downloadbutton like my id shiny element.

I'm already aware of this R Shiny: Download existing file.

R version 3.6.2 on Ubuntu 18.04

Body:
filename and content are arguments of the function downloadHandler, thus you have to use = and not <-:

 output$downloadbutton <- downloadHandler(

     filename = function() {
       paste("result_balance", "xlsx", sep=".")
     },
     content = function(file) {
       #temp <- file.path(tempdir(), "report.Rmd")
       file.copy(file.path(getwd(),'www','result.xlsx'), file,overwrite = TRUE)
     },
     contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
   )


问:
How to share the same ViewModel between Activity and Service when ViewModelProviders.of() is deprecated?
In new androidx.lifecycle:lifecycle-extensions:2.2.0 library, ViewModelProviders.of() is deprecated. It suggested that we should

```<code> * @deprecated Use the 'by viewModels()' Kotlin property delegate or
 * {@link ViewModelProvider#ViewModelProvider(ViewModelStoreOwner)},
 * passing in the activity.
</code>```

However, I want to share the same ViewModel instance between an activity and a service, I cannot use 'by viewModels()' delegation. Could anyone point out what is the correct way of doing this?

Thanks a lot

答:
Just replace it, with

In Activity:

Kotlin: ViewModelProvider(this).get(CustomViewModel::class.java)

Java: ViewModelProvider(this).get(CustomViewModel.class)

In Service:

create an instance of viewModel with keyword new inside service class

these work for me :)

Body:
In new androidx.lifecycle:lifecycle-extensions:2.2.0 library, ViewModelProviders.of() is deprecated. It suggested that we should

 * @deprecated Use the 'by viewModels()' Kotlin property delegate or
 * {@link ViewModelProvider#ViewModelProvider(ViewModelStoreOwner)},
 * passing in the activity.

However, I want to share the same ViewModel instance between an activity and a service, I cannot use 'by viewModels()' delegation. Could anyone point out what is the correct way of doing this?

Thanks a lot


问:
Filling web form fields but web page unable to detect text
I'm filling a web form using VBA, and I am able to fill text in the inputbox, but the webpage still is unable to detect the text and shows an error:
"Error: Required Field - Please provide an answer"

```<code>Set objIE = CreateObject("InternetExplorer.Application")
objIE.Visible = True

URL = "https://npc.collegeboard.org/app/dartmouth/start"

objIE.Navigate URL

objIE.Document.getElementById("student.firstName").Focus
objIE.Document.getElementById("student.firstName").Value = "Tom"
</code>```

Looks like theres some AngularJS running in the background, and it can't detect text fed in my VBA. Any help would be highly appreciated.

答:
First of all after objIE.Navigate URL you should wait until the website is fully loaded and the IE is ready. This is done with the following:

```<code>objIE.Navigate URL 'this needs some time but VBA will continue excecuting the next statement qickly

Const READYSTATE_COMPLETE As Integer = 4
Do While objIE.Busy Or objIE.ReadyState <> READYSTATE_COMPLETE
    DoEvents
Loop

'now IE is ready and the page is loaded.
</code>```

But it might be that some JavaScript is not ready yet and this is not recognized by objIE.Busy Or objIE.ReadyState. So you can do a workaround:

```<code>Dim Obj As Object
Do While Obj Is Nothing
    On Error Resume Next
    Set Obj = objIE.Document.getElementById("student.firstName")
    On Error GoTo 0
Loop

'now `student.firstName` is accessible, and probably all the other fields are too.
</code>```

This will try to access the field student.firstName if it is not there it will error. We suppress the error message using On Error Resume Next and jump back to TryAgain until it was found.

Note that this has one disadvantage: If there is a problem loading this site it will get stuck in this loop. So I recommend to get a timed cancel criterium like if this takes more than a minute cancel it and throw a error message.

Something like the following should work:

```<code>Option Explicit

Sub test()
    Dim objIE As Object
    Set objIE = CreateObject("InternetExplorer.Application")
    objIE.Visible = True

    Dim URL As String
    URL = "https://npc.collegeboard.org/app/dartmouth/start"

    objIE.Navigate URL

    Const READYSTATE_COMPLETE As Integer = 4
    Do While objIE.Busy Or objIE.ReadyState <> READYSTATE_COMPLETE
        DoEvents
    Loop

    Dim Obj As Object
    Do While Obj Is Nothing
        On Error Resume Next
        Set Obj = objIE.Document.getElementById("student.firstName")
        On Error GoTo 0
    Loop

    objIE.Document.getElementById("student.firstName").Focus
    objIE.Document.getElementById("student.firstName").Value = "Tom"
End Sub
</code>```

Body:
I'm filling a web form using VBA, and I am able to fill text in the inputbox, but the webpage still is unable to detect the text and shows an error:
"Error: Required Field - Please provide an answer"

Set objIE = CreateObject("InternetExplorer.Application")
objIE.Visible = True

URL = "https://npc.collegeboard.org/app/dartmouth/start"

objIE.Navigate URL

objIE.Document.getElementById("student.firstName").Focus
objIE.Document.getElementById("student.firstName").Value = "Tom"

Looks like theres some AngularJS running in the background, and it can't detect text fed in my VBA. Any help would be highly appreciated.

Body:
First of all after objIE.Navigate URL you should wait until the website is fully loaded and the IE is ready. This is done with the following:

objIE.Navigate URL 'this needs some time but VBA will continue excecuting the next statement qickly

Const READYSTATE_COMPLETE As Integer = 4
Do While objIE.Busy Or objIE.ReadyState <> READYSTATE_COMPLETE
    DoEvents
Loop

'now IE is ready and the page is loaded.

But it might be that some JavaScript is not ready yet and this is not recognized by objIE.Busy Or objIE.ReadyState. So you can do a workaround:

Dim Obj As Object
Do While Obj Is Nothing
    On Error Resume Next
    Set Obj = objIE.Document.getElementById("student.firstName")
    On Error GoTo 0
Loop

'now `student.firstName` is accessible, and probably all the other fields are too.

This will try to access the field student.firstName if it is not there it will error. We suppress the error message using On Error Resume Next and jump back to TryAgain until it was found.

Note that this has one disadvantage: If there is a problem loading this site it will get stuck in this loop. So I recommend to get a timed cancel criterium like if this takes more than a minute cancel it and throw a error message.

Something like the following should work:

Option Explicit

Sub test()
    Dim objIE As Object
    Set objIE = CreateObject("InternetExplorer.Application")
    objIE.Visible = True

    Dim URL As String
    URL = "https://npc.collegeboard.org/app/dartmouth/start"

    objIE.Navigate URL

    Const READYSTATE_COMPLETE As Integer = 4
    Do While objIE.Busy Or objIE.ReadyState <> READYSTATE_COMPLETE
        DoEvents
    Loop

    Dim Obj As Object
    Do While Obj Is Nothing
        On Error Resume Next
        Set Obj = objIE.Document.getElementById("student.firstName")
        On Error GoTo 0
    Loop

    objIE.Document.getElementById("student.firstName").Focus
    objIE.Document.getElementById("student.firstName").Value = "Tom"
End Sub


问:
Select the IDs using group by condition
I have a dataset where I need to find the diseased patients in consecutive rows.

I'll share my sample dataset with a clear explanation.

```<code>ID Normal Des1 Des2 Des3 Des4
12 0      1    0    0    0
12 1      0    1    0    0
12 1      0    1    0    0
12 1      0    1    0    0
14 0      1    0    1    0
18 1      0    0    0    0
18 1      0    0    0    0
18 1      0    0    0    0
11 0      1    0    0    0
11 0      1    0    0    0
11 0      1    0    0    0
22 1      0    0    0    0
</code>```

Here I specified the Diseased list of the dataset. I required the IDs for those who are in the same Disease in all the period.
Assume that I need an output for Patients who never fall in any Diseased criteria(IDs 18, 22) I stored it as a new set(Undiseased), Later I need to get the same model for Des1 patients (IDs 11). I tried the below code to fetch the data. but It returns partial output.

```<code>select ID from tablename where
(normal = '1' and Des1 = '0' and Des2 = '0' and Des3 = '0' and Des4 = '0')
group by ID
</code>```

答:
You can try the below query using COUNT (Transact-SQL)
 function.

```<code>Create table MySampleTable (Id int, Des1 int, Des2 int, Des3 int)
insert into MySampleTable Values
(12, 0, 1, 0),
(12, 1, 0, 1),
(12, 1, 0, 1),
(18, 1, 0, 0),
(18, 1, 0, 0),
(11, 0, 1, 0),
(11, 0, 1, 0)

; with cte as (Select Id
     , Count(distinct Des1) as TotDes1
     , Count(distinct Des2) as TotDes2
     , Count(distinct Des3) as TotDes3
from MySampleTable
group by Id
)
Select Id from cte where TotDes1 = 1
and TotDes2 = 1 and TotDes3 = 1
</code>```

It looks like as shown below with the output.

Here is the live db<>fiddle demo.

You can also use the having clause as shown in the query below.

```<code>Select Id
     /*
     , Count(distinct Des1) as TotDes1
     , Count(distinct Des2) as TotDes2
     , Count(distinct Des3) as TotDes3
     */
from MySampleTable
group by Id
having Count(distinct Des1) = 1 and Count(distinct Des2) = 1
and Count(distinct Des3) = 1
</code>```

Title: Select the IDs using group by condition

Body:
I have a dataset where I need to find the diseased patients in consecutive rows.

I'll share my sample dataset with a clear explanation.

ID Normal Des1 Des2 Des3 Des4
12 0      1    0    0    0
12 1      0    1    0    0
12 1      0    1    0    0
12 1      0    1    0    0
14 0      1    0    1    0
18 1      0    0    0    0
18 1      0    0    0    0
18 1      0    0    0    0
11 0      1    0    0    0
11 0      1    0    0    0
11 0      1    0    0    0
22 1      0    0    0    0

Here I specified the Diseased list of the dataset. I required the IDs for those who are in the same Disease in all the period.
Assume that I need an output for Patients who never fall in any Diseased criteria(IDs 18, 22) I stored it as a new set(Undiseased), Later I need to get the same model for Des1 patients (IDs 11). I tried the below code to fetch the data. but It returns partial output.

select ID from tablename where
(normal = '1' and Des1 = '0' and Des2 = '0' and Des3 = '0' and Des4 = '0')
group by ID

Body:
You can try the below query using COUNT (Transact-SQL)
 function.

Create table MySampleTable (Id int, Des1 int, Des2 int, Des3 int)
insert into MySampleTable Values
(12, 0, 1, 0),
(12, 1, 0, 1),
(12, 1, 0, 1),
(18, 1, 0, 0),
(18, 1, 0, 0),
(11, 0, 1, 0),
(11, 0, 1, 0)

; with cte as (Select Id
     , Count(distinct Des1) as TotDes1
     , Count(distinct Des2) as TotDes2
     , Count(distinct Des3) as TotDes3
from MySampleTable
group by Id
)
Select Id from cte where TotDes1 = 1
and TotDes2 = 1 and TotDes3 = 1

It looks like as shown below with the output.

Here is the live db<>fiddle demo.

You can also use the having clause as shown in the query below.

Select Id
     /*
     , Count(distinct Des1) as TotDes1
     , Count(distinct Des2) as TotDes2
     , Count(distinct Des3) as TotDes3
     */
from MySampleTable
group by Id
having Count(distinct Des1) = 1 and Count(distinct Des2) = 1
and Count(distinct Des3) = 1


问:
how to text align center for the text with space and line break
I have the following example below:

.wrapper {
  text-align: center;
  border: 1px solid red;
  background-color: white;
  color: black;
  width: 240px;
  height: 200px;
  font-size: 36px;
  line-height: 43px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea class="wrapper" autosize>THE GREAT BANGKOK SALE</textarea></code>```

https://jsfiddle.net/ngoctuan001/cgLvh62o/2/

As you can see, I want to text-align the text in the textarea tag. Because the text area got a fixed width, it will try to break to next line when there is a space. However, when that happen, that row is slightly not center in human eyes due to the space.

As you can see in the screen shot above, the red line in the right hand side is always slightly longer than the red line in the left hand side, this is because the computer treats the space (highlighted) as 1 more character. But in human eyes, this is not considered as center aligned

Is there anyway to fix this ?
Thanks

答:
put your text in p tag and you can try</p>

```<code>.wrapper
{
display: flex;
    align-items: center;
    justify-content: center;

}
</code>```

Body:
I have the following example below:

.wrapper {
  text-align: center;
  border: 1px solid red;
  background-color: white;
  color: black;
  width: 240px;
  height: 200px;
  font-size: 36px;
  line-height: 43px;
}

<textarea class="wrapper" autosize>THE GREAT BANGKOK SALE</textarea>

https://jsfiddle.net/ngoctuan001/cgLvh62o/2/

As you can see, I want to text-align the text in the textarea tag. Because the text area got a fixed width, it will try to break to next line when there is a space. However, when that happen, that row is slightly not center in human eyes due to the space.

As you can see in the screen shot above, the red line in the right hand side is always slightly longer than the red line in the left hand side, this is because the computer treats the space (highlighted) as 1 more character. But in human eyes, this is not considered as center aligned

Is there anyway to fix this ?
Thanks

Body:
put your text in p tag and you can try

.wrapper
{
display: flex;
    align-items: center;
    justify-content: center;

}


问:
How to find out where the default influxDB data storage location on Ubuntu is?
I am running influxDB version: 1.7.8 and since my Ubuntu machine (18.04.3 LTS) is running low of storage (I have 80GB), I want to:

Locate where does InfluxDB physically store the data (the big files)

How to change location to another place.

From this question here I understand that there are two locations:

var\lib\influxdb\wal

var\lib\influxdb\data

When I check the first I see 4.0K file size... Which tells me it's not the right place.

```<code>my_server:~$ sudo ls -l /var/lib/influxdb/wal/ -sh
total 20K
4.0K drwx------ 3 influxdb influxdb 4.0K Jul  9  2019 _internal
4.0K drwx------ 3 influxdb influxdb 4.0K Jul 10  2019 db1
4.0K drwx------ 3 influxdb influxdb 4.0K Nov 30 12:32 db2
4.0K drwx------ 3 influxdb influxdb 4.0K Nov 30 21:50 db3
4.0K drwx------ 3 influxdb influxdb 4.0K Dec 12 00:18 db4
</code>```

When I check the second, I see the same

```<code>my_server:~$ sudo ls -l /var/lib/influxdb/data/ -sh
total 20K
4.0K drwx------ 4 influxdb influxdb 4.0K Jul  9  2019 _internal
4.0K drwx------ 4 influxdb influxdb 4.0K Jul 10  2019 db1
4.0K drwx------ 4 influxdb influxdb 4.0K Nov 30 12:32 db2
4.0K drwx------ 4 influxdb influxdb 4.0K Nov 30 21:50 db3
4.0K drwx------ 4 influxdb influxdb 4.0K Dec 12 00:18 db4
</code>```

At the same time I see that this file: /var/log/syslog.1 takes a crazy amount of storage (13.7GB) with DB related information.

I could not find any information about this on the InfluxDB documentation, which I think is weird.

Can anyone provide either either a link to where I can read up about this and figure it out
or a solution to how I can approach to addressing my primary issues: finding out where the physical information is stored?

Thanks!

答:
Those are directories..directories on Linux always show as 4KB

Those locations are correct though

Try du -h -d1 /var/lib/influxdb for am accurate count

Body:
I am running influxDB version: 1.7.8 and since my Ubuntu machine (18.04.3 LTS) is running low of storage (I have 80GB), I want to:

Locate where does InfluxDB physically store the data (the big files)

How to change location to another place.

From this question here I understand that there are two locations:

var\lib\influxdb\wal

var\lib\influxdb\data

When I check the first I see 4.0K file size... Which tells me it's not the right place.

my_server:~$ sudo ls -l /var/lib/influxdb/wal/ -sh
total 20K
4.0K drwx------ 3 influxdb influxdb 4.0K Jul  9  2019 _internal
4.0K drwx------ 3 influxdb influxdb 4.0K Jul 10  2019 db1
4.0K drwx------ 3 influxdb influxdb 4.0K Nov 30 12:32 db2
4.0K drwx------ 3 influxdb influxdb 4.0K Nov 30 21:50 db3
4.0K drwx------ 3 influxdb influxdb 4.0K Dec 12 00:18 db4

When I check the second, I see the same

my_server:~$ sudo ls -l /var/lib/influxdb/data/ -sh
total 20K
4.0K drwx------ 4 influxdb influxdb 4.0K Jul  9  2019 _internal
4.0K drwx------ 4 influxdb influxdb 4.0K Jul 10  2019 db1
4.0K drwx------ 4 influxdb influxdb 4.0K Nov 30 12:32 db2
4.0K drwx------ 4 influxdb influxdb 4.0K Nov 30 21:50 db3
4.0K drwx------ 4 influxdb influxdb 4.0K Dec 12 00:18 db4

At the same time I see that this file: /var/log/syslog.1 takes a crazy amount of storage (13.7GB) with DB related information.

I could not find any information about this on the InfluxDB documentation, which I think is weird.

Can anyone provide either either a link to where I can read up about this and figure it out
or a solution to how I can approach to addressing my primary issues: finding out where the physical information is stored?

Thanks!


问:
Angular Material Datepicker with Range Selection
I'm using angular 8 and I wanted implement a datepicker with daterage highlighted:
enter image description here
I was looking for some package like this one:  https://www.npmjs.com/package/saturn-datepicker
Unfortunately it has been deprecated and currently I cannot find others like that.
Do you know something for my purpose? Thank you.  </p>

答:
IMPORTANT UPDATE, My good!! google is plenty full of controls like mine! (remember: Google is my friend, google is my friend...)

I'm making a datePicker range in this stackblitz, i'll try to explain after

Update I improve the stackblitz and a brief explanation

There are a point important with the mat-date-picker that it's not possible create a day-template. So it's necesary use Renderer2 to add listener, add classes or remove classes. I need use document.querySelectorAll as it's show in this another SO

The idea is, with the cells selected create an array of object

```<code>{
   date: //will be a getTime of the date,
   element: //will be the nativeElement x,
   change: //a boolean to indicate this cell has an aditional class
   x.listen: //the listener added to allow us remove the listener
}
</code>```

And a function who help us to add/remove class acording two variables: this._dateTo and another variable that will be this._dateFrom or another one (early we discovered why)

```<code>  redrawCells(timeTo: number) {
    timeTo = timeTo || this._dateTo;
    if (timeTo<this._dateFrom)
      timeTo=this._dateFrom
    this.cells.forEach(x => {
      const change = x.date >= this._dateFrom && x.date <= timeTo;
      if (change || x.change) {
        x.change = change;
        const addInside = x.change ? "addClass" : "removeClass";
        const addFrom = x.date == this._dateFrom? "addClass":
                        x.date == timeTo && this._dateFrom==timeTo? "addClass":
                        "removeClass";
        const addTo = x.date == timeTo? "addClass":
                      x.date == this._dateFrom && this._dateFrom==timeTo? "addClass":
                        "removeClass";

        this.renderer[addInside](x.element, "inside");
        this.renderer[addFrom](x.element, "from");
        this.renderer[addTo](x.element, "to");
      }
    });
  }
</code>```

A new function setCell will be who manage the td to add/remove listener of mouse over. It's necesary enclosed in a setTimeout because we call this function before the calendar is drawed

```<code>  setCells() {
    setTimeout(() => {
      if (this.cells) {
        this.cells.forEach(x => {
          x.listen();  //<---remove the listener
        });
      }
      this.dateOver = null;
      //get the elements
      let elements = document.querySelectorAll(".calendar");
      if (!elements || elements.length == 0) return;
      const cells = elements[0].querySelectorAll(".mat-calendar-body-cell");
      this.cells = [];
      //with each element we fill our array "this.cells"
      cells.forEach((x, index) => {
        const date = new Date(x.getAttribute("aria-label"));
        const time=new Date(date.getFullYear() +"-" +(date.getMonth() + 1) +
              "-" +date.getDate()).getTime()

        this.cells.push({
          date: time,
          element: x,
          change:time>=this._dateFrom && time<=this._dateTo
        });
      });
      this.cells.forEach(x => {
        if (!x.listen) {
          //we add a listener "mouseover"
          x.listen = this.renderer.listen(x.element, "mouseover", () => {
            if (!this._dateTo && this.dateOver != x.date) {
              this.dateOver = x.date;
              this.redrawCells(this.dateOver); //who call to redrawCells
            }
          });
        }
      });
    });
  }
</code>```

Well, the rest of function necesary to parse and format a date and open a mat-calendar using a mat-menu is from this another SO. In this last SO, the calendar not close, so, we can use to force two clicks to get a dateFrom and a dateTo

```<code>  select(date: any) {
    date = new Date(
      date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate()
    );
    if (
      !this.from.value ||
      (this.from.value && this.to.value) ||
      this._dateFrom > date.getTime()
    ) {
      this.dateFrom = date;
      this.dateTo = null;
      this.redrawCells(date.getTime());
    } else {
      this.dateTo = date;
      this.trigger.closeMenu();
    }
  }
</code>```

I like create a mat custom component. This allow us use the component in a mat-form-field, some like

```<code><mat-form-field class="full-width" >
  <mat-label>Select dates</mat-label>
  <date-picker-range [formControl]="control" placeholder="DD/MM/YYYY"  ></date-picker-range>
  <mat-error>required</mat-error>
</mat-form-field>
</code>```

And allow e.g. us use [disabled] to disabled the formControl, and the label move like another mat-input. For this we need add some functions, see (I promise it's the last) this last recent SO

NOTE: The control is "AS IS" without any warranty and it's allowed: critics it, improve, modify, use or put it as bad example

Body:
IMPORTANT UPDATE, My good!! google is plenty full of controls like mine! (remember: Google is my friend, google is my friend...)

I'm making a datePicker range in this stackblitz, i'll try to explain after

Update I improve the stackblitz and a brief explanation

There are a point important with the mat-date-picker that it's not possible create a day-template. So it's necesary use Renderer2 to add listener, add classes or remove classes. I need use document.querySelectorAll as it's show in this another SO

The idea is, with the cells selected create an array of object

{
   date: //will be a getTime of the date,
   element: //will be the nativeElement x,
   change: //a boolean to indicate this cell has an aditional class
   x.listen: //the listener added to allow us remove the listener
}

And a function who help us to add/remove class acording two variables: this._dateTo and another variable that will be this._dateFrom or another one (early we discovered why)

  redrawCells(timeTo: number) {
    timeTo = timeTo || this._dateTo;
    if (timeTo<this._dateFrom)
      timeTo=this._dateFrom
    this.cells.forEach(x => {
      const change = x.date >= this._dateFrom && x.date <= timeTo;
      if (change || x.change) {
        x.change = change;
        const addInside = x.change ? "addClass" : "removeClass";
        const addFrom = x.date == this._dateFrom? "addClass":
                        x.date == timeTo && this._dateFrom==timeTo? "addClass":
                        "removeClass";
        const addTo = x.date == timeTo? "addClass":
                      x.date == this._dateFrom && this._dateFrom==timeTo? "addClass":
                        "removeClass";

        this.renderer[addInside](x.element, "inside");
        this.renderer[addFrom](x.element, "from");
        this.renderer[addTo](x.element, "to");
      }
    });
  }

A new function setCell will be who manage the td to add/remove listener of mouse over. It's necesary enclosed in a setTimeout because we call this function before the calendar is drawed

  setCells() {
    setTimeout(() => {
      if (this.cells) {
        this.cells.forEach(x => {
          x.listen();  //<---remove the listener
        });
      }
      this.dateOver = null;
      //get the elements
      let elements = document.querySelectorAll(".calendar");
      if (!elements || elements.length == 0) return;
      const cells = elements[0].querySelectorAll(".mat-calendar-body-cell");
      this.cells = [];
      //with each element we fill our array "this.cells"
      cells.forEach((x, index) => {
        const date = new Date(x.getAttribute("aria-label"));
        const time=new Date(date.getFullYear() +"-" +(date.getMonth() + 1) +
              "-" +date.getDate()).getTime()

        this.cells.push({
          date: time,
          element: x,
          change:time>=this._dateFrom && time<=this._dateTo
        });
      });
      this.cells.forEach(x => {
        if (!x.listen) {
          //we add a listener "mouseover"
          x.listen = this.renderer.listen(x.element, "mouseover", () => {
            if (!this._dateTo && this.dateOver != x.date) {
              this.dateOver = x.date;
              this.redrawCells(this.dateOver); //who call to redrawCells
            }
          });
        }
      });
    });
  }

Well, the rest of function necesary to parse and format a date and open a mat-calendar using a mat-menu is from this another SO. In this last SO, the calendar not close, so, we can use to force two clicks to get a dateFrom and a dateTo

  select(date: any) {
    date = new Date(
      date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate()
    );
    if (
      !this.from.value ||
      (this.from.value && this.to.value) ||
      this._dateFrom > date.getTime()
    ) {
      this.dateFrom = date;
      this.dateTo = null;
      this.redrawCells(date.getTime());
    } else {
      this.dateTo = date;
      this.trigger.closeMenu();
    }
  }

I like create a mat custom component. This allow us use the component in a mat-form-field, some like

<mat-form-field class="full-width" >
  <mat-label>Select dates</mat-label>
  <date-picker-range [formControl]="control" placeholder="DD/MM/YYYY"  ></date-picker-range>
  <mat-error>required</mat-error>
</mat-form-field>

And allow e.g. us use [disabled] to disabled the formControl, and the label move like another mat-input. For this we need add some functions, see (I promise it's the last) this last recent SO

NOTE: The control is "AS IS" without any warranty and it's allowed: critics it, improve, modify, use or put it as bad example


问:
react.js ant design range filter with start and end dates error
in my react.js ant.design project I am trying to implement table range filtering based on 2 date pickers: for start date and end date. I inserted them into filter drop down, but when I hit the search button, I get an error sayng that values.some is not a function.

Example you may see HERE

The goal is to send to backend for searching an array of 2 dates: start date and end date. I suppose it is sending a moment.js object there which is should be converted to string somehow, but I dont know where to do that. Any ideas how to fix it would be welcome

答:
Change the way on how you pass the values to setSelectedKeys function, the setSelectedKeys function accepts an array as the value.

So in order for this to work. Change your code into this.

```<code>onChange={e => setSelectedKeys([e.format("DD.MM.YYYY")])}
</code>```

Also you must handle the on clear event of the datepicker to avoid passing null value to setSelectedKeys function.

```<code>onChange={e => setSelectedKeys(e !== null ? [e.format("DD.MM.YYYY")] : [])}
</code>```

Body:
Change the way on how you pass the values to setSelectedKeys function, the setSelectedKeys function accepts an array as the value.

So in order for this to work. Change your code into this.

onChange={e => setSelectedKeys([e.format("DD.MM.YYYY")])}

Also you must handle the on clear event of the datepicker to avoid passing null value to setSelectedKeys function.

onChange={e => setSelectedKeys(e !== null ? [e.format("DD.MM.YYYY")] : [])}


问:
How to delete reversed value on Oracle Database by using Query?
Lets say i have some data on Oracle database like what i mentioned above .

TABLE

```<code>       COLUMN1 | COLUMN2 | Quantity

        100    |  2000   |     1
       2000    |  100    |     5
       3000    |  100    |     2
</code>```

As you can see column1 and column2 is reversed data . What is the efficient way to clean this data from oracleDb . I am not concerned about which one might delete . My main purpose is if table includes reverse data  one of them should be deleted . It is enough for me .

答:
Let me call your table T.

```<code>select *
from T T1 join T T2
     on T1.column1 = T2.column2
     and T1.column2 = T2.column1;
</code>```

Gives you the pairs.
Each pair occurs twice, because of the symmetry.

In order to delete them, you can do

```<code>delete from T
where rowid in (
    select T1.rowid
    from T T1 join T T2
         on T1.column1 = T2.column2
         and T1.column2 = T2.column1
    where T1.rowid < T2.rowid
);
</code>```

Note: I didn't test this. I leave that up to you.

Body:
Lets say i have some data on Oracle database like what i mentioned above .

TABLE

       COLUMN1 | COLUMN2 | Quantity

        100    |  2000   |     1
       2000    |  100    |     5
       3000    |  100    |     2

As you can see column1 and column2 is reversed data . What is the efficient way to clean this data from oracleDb . I am not concerned about which one might delete . My main purpose is if table includes reverse data  one of them should be deleted . It is enough for me .

Body:
Let me call your table T.

select *
from T T1 join T T2
     on T1.column1 = T2.column2
     and T1.column2 = T2.column1;

Gives you the pairs.
Each pair occurs twice, because of the symmetry.

In order to delete them, you can do

delete from T
where rowid in (
    select T1.rowid
    from T T1 join T T2
         on T1.column1 = T2.column2
         and T1.column2 = T2.column1
    where T1.rowid < T2.rowid
);

Note: I didn't test this. I leave that up to you.


问:
remove duplicate array from array list using filter?
I use this code

```<code>labels.map((label, key) => {
  const xAxis = (parseInt(label, 10)).toFixed(0);
  const yAxis = parseInt(this.props.dataSet.datasets[0].data[key], 10);
  const arrayAxis = [xAxis, yAxis];
  data.push(arrayAxis);
  return arrayAxis;
});
</code>```

then i get the data list

```<code>["1", 1]
["2", 1]  // duplicate
["2", 1]  // duplicate
["3", 1]
["4", 1]
["4", 1]
["5", 4]
["6", 4]
["7", 4]
["8", 4]
["9", 4]
.....
....
...
</code>```

How I can remove duplicate array from the array list using filter?

Body:
I use this code

labels.map((label, key) => {
  const xAxis = (parseInt(label, 10)).toFixed(0);
  const yAxis = parseInt(this.props.dataSet.datasets[0].data[key], 10);
  const arrayAxis = [xAxis, yAxis];
  data.push(arrayAxis);
  return arrayAxis;
});

then i get the data list

["1", 1]
["2", 1]  // duplicate
["2", 1]  // duplicate
["3", 1]
["4", 1]
["4", 1]
["5", 4]
["6", 4]
["7", 4]
["8", 4]
["9", 4]
.....
....
...

How I can remove duplicate array from the array list using filter?

Body:
let res = [...new Set([1,3,45, 1, 3])]

output is = [1,3,45]


问:
How to require a field if a particular checkbox is checked in laravel?
I am new to Laravel, I have three checkboxes: WhatsApp, Email and SMS

What I want to accomplish in my validation CustomerRequest, is to require the Email field if the Checkbox for email is checked:

Below is a sample of my rules:

```<code>public function rules()
    {
        return [
            'choix' => 'required',
            'tel' => 'required|max:25',
            'contract' => 'required|numeric|max:9',
            'nom' => 'required|max:255',
            'email' => 'required|max:50',
            'language' => 'required|max:2',
            'g-recaptcha-response' => 'required|captcha',
            'conditionAccepted' => 'accepted',
        ];
    }
</code>```

Below is my checkbox field:

```<code> <div class="form-group row">
                    <div class="col-md-12 " style="text-align : left; margin-left:20px;" ><label class="checkbox-inline check"> <input type="checkbox" class="checkbox" name="choix[]" value="WHA">
                            <span style="margin-top:10px; margin-left:20px; position: absolute;">WhatsApp</span></label></div>
                    <div class="col-md-12 " style="text-align : left; margin-left:20px;" ><label class="checkbox-inline check"> <input type="checkbox" class="checkbox" name="choix[]" value="SMS">
                            <span style="margin-top:10px; margin-left:20px; position: absolute;">SMS</span></label></div>
                    <div class="col-md-12 " style="text-align : left; margin-left:20px;" ><label class="checkbox-inline check"> <input type="checkbox" class="checkbox" name="choix[]" value="MAIL">
                            <span style="margin-top:10px; margin-left:20px; position: absolute;">Email</span></label></div>

                </div>
</code>```

Appreciate guidance

答:
I was able to solve the issue with the following code:</p>

```<code>'choix.*' => 'in:WHA,SMS,MAIL',
'tel' => 'required|max:25',
'contract' => 'required|digits:9|exists:accounts,sic_code',
'nom' => 'required|max:255',
'email' => 'required_if:choix.MAIL,==,MAIL|nullable|email|max:50',
'language' => 'required|max:2',
'g-recaptcha-response' => 'required|captcha',
'conditionAccepted' => 'accepted',
</code>```

Body:
I am new to Laravel, I have three checkboxes: WhatsApp, Email and SMS

What I want to accomplish in my validation CustomerRequest, is to require the Email field if the Checkbox for email is checked:

Below is a sample of my rules:

public function rules()
    {
        return [
            'choix' => 'required',
            'tel' => 'required|max:25',
            'contract' => 'required|numeric|max:9',
            'nom' => 'required|max:255',
            'email' => 'required|max:50',
            'language' => 'required|max:2',
            'g-recaptcha-response' => 'required|captcha',
            'conditionAccepted' => 'accepted',
        ];
    }

Below is my checkbox field:

 <input type="checkbox" class="checkbox" name="choix[]" value="WHA">
                            WhatsApp

 <input type="checkbox" class="checkbox" name="choix[]" value="SMS">
                            SMS

 <input type="checkbox" class="checkbox" name="choix[]" value="MAIL">
                            Email

Appreciate guidance

Body:
I was able to solve the issue with the following code:

'choix.*' => 'in:WHA,SMS,MAIL',
'tel' => 'required|max:25',
'contract' => 'required|digits:9|exists:accounts,sic_code',
'nom' => 'required|max:255',
'email' => 'required_if:choix.MAIL,==,MAIL|nullable|email|max:50',
'language' => 'required|max:2',
'g-recaptcha-response' => 'required|captcha',
'conditionAccepted' => 'accepted',


问:
Updating Session ID to Test Name in Browserstack
I am using Ruby/Capybara, and hooked up my test to browserstack but I see session ID in browserstack instead of the test name.  This is how I set it up:

```<code>Capybara.register_driver :browserstack do |app|
Capybara::Selenium::Driver.new(app,
                               browser: :remote,
                               url: 'some/URI',
                               desired_capabilities: browserstack_capabilities)
</code>```

How do I see the test name?

答: You may try adding the "name" : "Some-name" capability in your capability set and that should work. For more details on capabilities, you may refer this link: https://www.browserstack.com/automate/capabilities</p>

Body:
I am using Ruby/Capybara, and hooked up my test to browserstack but I see session ID in browserstack instead of the test name.  This is how I set it up:

Capybara.register_driver :browserstack do |app|
Capybara::Selenium::Driver.new(app,
                               browser: :remote,
                               url: 'some/URI',
                               desired_capabilities: browserstack_capabilities)

How do I see the test name?


问:
Preserve decimals when writing CSVs
It seems the when using the writer to write CSV file, the 0s in decimals are automatically left out. For example

```<code>out.update({movieID:"%.1f" % (round(sum(rating)/float(len(rating)),1))})
for key in sorted(out.keys()):
        writer1.writerow({'movieID': int(key), 'avg_rating': out[key]})
</code>```

I have specified one decimal in writing CSV, my intended output

```<code>3.0
3.3
</code>```

Actual output in CSV

```<code>3
3.3
</code>```

Anyways to preserve this value? I also tried quoting=Non numeric

答:
Trying this:

```<code>import csv

with open('test.csv', mode='w') as csv_file:
    fieldnames = ['#', 'Salary']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'#': '32', 'Salary': '100.40'})
    writer.writerow({'#': '33', 'Salary': '100.4400'})
    writer.writerow({'#': '34', 'Salary': '101.40'})
    writer.writerow({'#': '35', 'Salary': '105.430'})
</code>```

The following is received, when the file is opened with Notepad:

```<code>#,Salary
32,100.40
33,100.4400
34,101.40
35,105.430
</code>```

If you open with Excel, then a possible solution is to import the column with the numbers explicitly as a text.

Data > Get External Data > From Text

Click "Next", and make sure that the column with the numbers is selected. The radio button should be as "Text":

At the end, the csv table is imported to Excel as text:

Note, that the text in Excel is automatically aligned to the left, while the numbers are to the right. Still, the formulas work on the Text, as Excel is "wise" enough to parse them to numbers correctly.

Title: Preserve decimals when writing CSVs

Body:
It seems the when using the writer to write CSV file, the 0s in decimals are automatically left out. For example

out.update({movieID:"%.1f" % (round(sum(rating)/float(len(rating)),1))})
for key in sorted(out.keys()):
        writer1.writerow({'movieID': int(key), 'avg_rating': out[key]})

I have specified one decimal in writing CSV, my intended output

3.0
3.3

Actual output in CSV

3
3.3

Anyways to preserve this value? I also tried quoting=Non numeric

Body:
Trying this:

import csv

with open('test.csv', mode='w') as csv_file:
    fieldnames = ['#', 'Salary']
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'#': '32', 'Salary': '100.40'})
    writer.writerow({'#': '33', 'Salary': '100.4400'})
    writer.writerow({'#': '34', 'Salary': '101.40'})
    writer.writerow({'#': '35', 'Salary': '105.430'})

The following is received, when the file is opened with Notepad:

#,Salary
32,100.40
33,100.4400
34,101.40
35,105.430

If you open with Excel, then a possible solution is to import the column with the numbers explicitly as a text.

Data > Get External Data > From Text

Click "Next", and make sure that the column with the numbers is selected. The radio button should be as "Text":

At the end, the csv table is imported to Excel as text:

Note, that the text in Excel is automatically aligned to the left, while the numbers are to the right. Still, the formulas work on the Text, as Excel is "wise" enough to parse them to numbers correctly.


问:
Change Apache directory to show Wordpress homepage
I have Wordpress installed using an AWS EC2 instance. The public IP is as here. I used LetsEncrypt to get SSL, that worked fine. But after that, my homepage now shows the 'Apache2 Ubuntu Default Page'. It should be showing me the Wordpress homepage. I still have ssh access to the EC2 (Bitnami Wordpress), so my data is supposedly still there.

I've been doing some research at it seems that I need to change something with Apache so it direct to the Wordpress directory/page.

Any help in the matter would be most appreciated :)

答:
Bitnami Engineer here,

It seems you installed the Apache2 system's service in the machine and it got started at boot time. The Bitnami apps don't use the system's services. That's why the Bitnami's Apache service can't be started because other service is already running in the 80 port. In order to stop and disable it, please run these commands

```<code>sudo service apache2 stop
sudo service apache2 disable
sudo /opt/bitnami/ctlscript.sh start apache
</code>```

Happy to help!

Body:
Bitnami Engineer here,

It seems you installed the Apache2 system's service in the machine and it got started at boot time. The Bitnami apps don't use the system's services. That's why the Bitnami's Apache service can't be started because other service is already running in the 80 port. In order to stop and disable it, please run these commands

sudo service apache2 stop
sudo service apache2 disable
sudo /opt/bitnami/ctlscript.sh start apache

Happy to help!


问:
How do I print to the console instead of an iPython output cell?
I want to print my output to the console (the one showing the log information or, better yet, a separate console) rather than an output cell in the iPython web notebook.

This is because I frequently have very long output I like to scroll through, and Chrome lags and breaks on large output, whereas iTerm2 does not.

答:
Update of the answer from valhallasw:
You should use the following, otherwise it returns TypeError: a bytes-like object is required, not 'str'.

```<code>import os
os.write(1, b"text\n")
</code>```

Otherwise, you can also do as Oliver Evans said:

```<code>import os
os.write(1, "text\n".encode())
</code>```

Body:
Update of the answer from valhallasw:
You should use the following, otherwise it returns TypeError: a bytes-like object is required, not 'str'.

import os
os.write(1, b"text\n")

Otherwise, you can also do as Oliver Evans said:

import os
os.write(1, "text\n".encode())


问:
Flutter - Font Awesome Icon overflow with Text
I'm using FontAwesomeIcon Plugin in my application.

Some Icons from FontAwesomeIcon plugin are overlap with Text widget like below Image.

I can solve this problem by adding some width between Text and Icon, but that is not good. so how to solve this problem.

I need like this Image.

here i'm not adding any width between icon and text.

Code:

```<code>Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Icon(
                      Icons.trip_origin,
                      color: Colors.white,
                    ),
                    Text(
                      'TP-23',
                      style: TextStyle(color: Colors.white),
                    )
                  ],
                ),
                Row(
                  children: <Widget>[
                    Icon(
                      FontAwesomeIcons.idCard,
                      color: Colors.white,
                    ),
                    Text(
                      'TP-23',
                      style: TextStyle(color: Colors.white),
                    )
                  ],
                )
              ],
            ),
</code>```

答:
Why don't you just use the Padding widget (https://api.flutter.dev/flutter/widgets/Padding-class.html) like this

ADD PADDING TO THE LEFT AND RIGHT TO THE ICON WIDGET

Row(
  children: <Widget>[
    Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.0)
      child: Icon(
        Icons.trip_origin,
        color: Colors.white,
      ),
    ),
    Text(
      'TP-23',
      style: TextStyle(color: Colors.white),
    )
  ]
)
```

<p>ADD PADDING ONLY TO THE RIGHT TO THE ICON WIDGET</p>

<pre class="lang-dart prettyprint-override"><code>Row(
  children: <Widget>[
    Padding(
      padding: EdgeInsets.only(right: 16.0)
      child: Icon(
        Icons.trip_origin,
        color: Colors.white,
      ),
    ),
    Text(
      'TP-23',
      style: TextStyle(color: Colors.white),
    )
  ]
)
</code>```

Body:
I'm using FontAwesomeIcon Plugin in my application.

Some Icons from FontAwesomeIcon plugin are overlap with Text widget like below Image.

I can solve this problem by adding some width between Text and Icon, but that is not good. so how to solve this problem.

I need like this Image.

here i'm not adding any width between icon and text.

Code:

Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Icon(
                      Icons.trip_origin,
                      color: Colors.white,
                    ),
                    Text(
                      'TP-23',
                      style: TextStyle(color: Colors.white),
                    )
                  ],
                ),
                Row(
                  children: <Widget>[
                    Icon(
                      FontAwesomeIcons.idCard,
                      color: Colors.white,
                    ),
                    Text(
                      'TP-23',
                      style: TextStyle(color: Colors.white),
                    )
                  ],
                )
              ],
            ),

Body:
Why don't you just use the Padding widget (https://api.flutter.dev/flutter/widgets/Padding-class.html) like this

ADD PADDING TO THE LEFT AND RIGHT TO THE ICON WIDGET

Row(
  children: <Widget>[
    Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.0)
      child: Icon(
        Icons.trip_origin,
        color: Colors.white,
      ),
    ),
    Text(
      'TP-23',
      style: TextStyle(color: Colors.white),
    )
  ]
)

ADD PADDING ONLY TO THE RIGHT TO THE ICON WIDGET

Row(
  children: <Widget>[
    Padding(
      padding: EdgeInsets.only(right: 16.0)
      child: Icon(
        Icons.trip_origin,
        color: Colors.white,
      ),
    ),
    Text(
      'TP-23',
      style: TextStyle(color: Colors.white),
    )
  ]
)


问:
Show All Empty Categories in Woocommerce Shop Page except Uncategorized
Woocommerce generally displays only the categories with products on the Shop page.
I would like to display all the categories(except Uncategorized) in the Shop Page even if it's empty.

The below displays all the categories including Uncategorized. Is there a way to exclude Uncategorized from that?

```<code>add_filter( 'woocommerce_product_subcategories_hide_empty', 'show_empty_categories', 10, 1 );
function show_empty_categories ( $show_empty ) {
   $show_empty  =  true;
    return $show_empty;
}
</code>```

答:
Change the args in the following way

https://github.com/woocommerce/woocommerce/blob/master/includes/wc-template-functions.php#L2479

function my_product_subcategories_arg( $args ) {
    $uncategorized = get_option( 'default_product_cat' );
    $args['exclude'] = $uncategorized;
    $args['hide_empty'] = 0;
    return $args;
}
add_filter( 'woocommerce_product_subcategories_args', 'my_product_subcategories_arg', 10, 1 );
```

Body:
Woocommerce generally displays only the categories with products on the Shop page.
I would like to display all the categories(except Uncategorized) in the Shop Page even if it's empty.

The below displays all the categories including Uncategorized. Is there a way to exclude Uncategorized from that?

add_filter( 'woocommerce_product_subcategories_hide_empty', 'show_empty_categories', 10, 1 );
function show_empty_categories ( $show_empty ) {
   $show_empty  =  true;
    return $show_empty;
}


问:
Click function on checkbox for toggeling table elements
I have been trying to use this JS for hiding some html table th and td elements.

```<code>$(document).ready(function(){
    $('th.proces').hide();
    $('td.proces').hide();
    $('#hide_proces').click(function() {
        if($(this).attr('checked'))
        {
            $('th.proces').show();
            $('td.proces').show();
        }
        else
        {
            $('th.proces').hide();
            $('td.proces').hide();
        }
    });
});
</code>```

When the page is loaded the items are hidden, so that is working.

Now I have this checkbox, and when checked the th and td elements should be made visible again.

```<code><input id="hide_proces" type="checkbox"/>
<th class="proces">Proces</th>
<td class="proces">some content</td>
</code>```

When the checkbox is checked the elements are still not visible, also no errors in the console. Any suggestions?

答:
$('#hide_proces').change(function() {
  let $e = $(".proces");
  $(this).is(':checked') ?
    $e.removeClass("hidden") : $e.addClass("hidden");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  display: none !important;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Title of the document</title>

  <input id="hide_proces" type="checkbox" />

      Proces

      some content

```

Body:
I have been trying to use this JS for hiding some html table th and td elements.

$(document).ready(function(){
    $('th.proces').hide();
    $('td.proces').hide();
    $('#hide_proces').click(function() {
        if($(this).attr('checked'))
        {
            $('th.proces').show();
            $('td.proces').show();
        }
        else
        {
            $('th.proces').hide();
            $('td.proces').hide();
        }
    });
});

When the page is loaded the items are hidden, so that is working.

Now I have this checkbox, and when checked the th and td elements should be made visible again.

<input id="hide_proces" type="checkbox"/>
Proces
some content

When the checkbox is checked the elements are still not visible, also no errors in the console. Any suggestions?

Body:
$('#hide_proces').change(function() {
  let $e = $(".proces");
  $(this).is(':checked') ?
    $e.removeClass("hidden") : $e.addClass("hidden");
});

.hidden {
  display: none !important;
}

<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <meta charset="UTF-8">
  <title>Title of the document</title>
</head>

<body>
  <input id="hide_proces" type="checkbox" />
  <table>
    <tr>
      <th class="proces hidden">Proces</th>
    </tr>
    <tr>
      <td class="proces hidden">some content</td>
    </tr>
</body>

</html>


问:
How to fix the Snackbar height and position?
On Android Support Library 24.1.1, the Snackbar was working fine:

Then starting on Android Support Library 24.2.0 onwards, the Snackbar started to behave like this:

On the library revision history, there is the following statement:

Behavior changes: Snackbar now draws behind the navigation bar if the status bar is translucent.

But the thing is that my app is full screen and it doesn't have the navigation bar or the status bar. How can I fix it?

答:
It's 2020 and also I don't know if it's related but I got my snackbar having some padding at the bottom when using android 10 gesture navigation. None of the above works for my case. I finally got it fixed with a super simple line:

```<code>val snackbar = Snackbar.make(view, message, duration)
snackbar.isGestureInsetBottomIgnored = true // here
snackbar.show()
</code>```

Hope it helps.

Body:
It's 2020 and also I don't know if it's related but I got my snackbar having some padding at the bottom when using android 10 gesture navigation. None of the above works for my case. I finally got it fixed with a super simple line:

val snackbar = Snackbar.make(view, message, duration)
snackbar.isGestureInsetBottomIgnored = true // here
snackbar.show()

Hope it helps.


问:
Access function protocol in generic class
I want to access function in protocol, but XCode complaint

Instance member 'createColumns' cannot be used on type 'T'; did you
  mean to use a value of this type instead?

What I have done:

Create protocol:

```<code>protocol StorageModelDelegate {
   func createColumns(for tableBuilder: TableBuilder)
}
</code>```

Create class generic that receive StorageModelDelegate:

```<code>class SQLiteStorage<T: StorageModelDelegate> {
     func createTable(tableName: TableKey) -> Bool {
           let table = Table(tableName.rawValue)

           let query = table.create(ifNotExists: true) { (builder: TableBuilder) in
                T.createColumns(for: builder) // -> this is the error comes up.
           }
     }
}
</code>```

Create class that implement SQLiteStorage:

```<code>final class InfoStorageModel {
    private let sqlite: SQLiteStorage = SQLiteStorage<Info>()
}
</code>```

so, how to fix the error in SQLiteStorage class?

答:
You want to call static method instead of instance method.

In order to fix, you should add instance parameter:

First of all, use weak var delegate in order to prevent retain cycles.

```<code>protocol StorageModelDelegate: class {
   func createColumns(for tableBuilder: TableBuilder)
}

final class SQLiteStorage<T: StorageModelDelegate> {
weak var delegate: T?
     func createTable(tableName: TableKey) -> Bool {
           let table = Table(tableName.rawValue)

           let query = table.create(ifNotExists: true) { (builder: TableBuilder) in
                delegate?.createColumns(for: builder)
           }
     }
}
</code>```

Or use static protocol methods:

```<code>protocol StorageModelDelegate {
   static func createColumns(for tableBuilder: TableBuilder)
}

final class SQLiteStorage<T: StorageModelDelegate> {
weak var delegate: T?
     func createTable(tableName: TableKey) -> Bool {
           let table = Table(tableName.rawValue)

           let query = table.create(ifNotExists: true) { (builder: TableBuilder) in
                T.createColumns(for: builder)
           }
     }
}
</code>```

Body:
I want to access function in protocol, but XCode complaint

Instance member 'createColumns' cannot be used on type 'T'; did you
  mean to use a value of this type instead?

What I have done:

Create protocol:

protocol StorageModelDelegate {
   func createColumns(for tableBuilder: TableBuilder)
}

Create class generic that receive StorageModelDelegate:

class SQLiteStorage<T: StorageModelDelegate> {
     func createTable(tableName: TableKey) -> Bool {
           let table = Table(tableName.rawValue)

           let query = table.create(ifNotExists: true) { (builder: TableBuilder) in
                T.createColumns(for: builder) // -> this is the error comes up.
           }
     }
}

Create class that implement SQLiteStorage:

final class InfoStorageModel {
    private let sqlite: SQLiteStorage = SQLiteStorage<Info>()
}

so, how to fix the error in SQLiteStorage class?

Body:
You want to call static method instead of instance method.

In order to fix, you should add instance parameter:

First of all, use weak var delegate in order to prevent retain cycles.

protocol StorageModelDelegate: class {
   func createColumns(for tableBuilder: TableBuilder)
}

final class SQLiteStorage<T: StorageModelDelegate> {
weak var delegate: T?
     func createTable(tableName: TableKey) -> Bool {
           let table = Table(tableName.rawValue)

           let query = table.create(ifNotExists: true) { (builder: TableBuilder) in
                delegate?.createColumns(for: builder)
           }
     }
}

Or use static protocol methods:

protocol StorageModelDelegate {
   static func createColumns(for tableBuilder: TableBuilder)
}

final class SQLiteStorage<T: StorageModelDelegate> {
weak var delegate: T?
     func createTable(tableName: TableKey) -> Bool {
           let table = Table(tableName.rawValue)

           let query = table.create(ifNotExists: true) { (builder: TableBuilder) in
                T.createColumns(for: builder)
           }
     }
}


问:
html2canvas stop scroll to top of the page
I am using html2canvas for screenshot and append the image. Those things working fine, but After doing that always scroll to top of the page. I need to scroll pacific div according to div id or class. Here is the code that I using:

```<code>html2canvas($('#preview_front'), {
    onrendered: function (canvas) {
        document.getElementById("image_reply").appendChild(canvas);
        $('#img_front').val(canvas.toDataURL("image/png"));
        var canvas = $('canvas');
        canvas.addClass('front_canvas');
    }
});
</code>```

Try with Following code:

```<code>var scrollPos;
document.querySelector("screenshotButton").addEventListener("click", function () {
    scrollPos = document.body.scrollTop;
    html2canvas(document.body, {
        onrendered: function (canvas) {
            document.body.appendChild(canvas);
            window.scrollTo(0, scrollPos);
        }
    });
});
</code>```

That is not working for me.

答: everytime when you click the button you set the scrollPos to 0 in your code. As you set scrollPos to scrollTop of body which is always 0. Instead document.body.scrollTop this use scrollTop of particular pacific div according to div ID of class.</p>

Body:
I am using html2canvas for screenshot and append the image. Those things working fine, but After doing that always scroll to top of the page. I need to scroll pacific div according to div id or class. Here is the code that I using:

html2canvas($('#preview_front'), {
    onrendered: function (canvas) {
        document.getElementById("image_reply").appendChild(canvas);
        $('#img_front').val(canvas.toDataURL("image/png"));
        var canvas = $('canvas');
        canvas.addClass('front_canvas');
    }
});

Try with Following code:

var scrollPos;
document.querySelector("screenshotButton").addEventListener("click", function () {
    scrollPos = document.body.scrollTop;
    html2canvas(document.body, {
        onrendered: function (canvas) {
            document.body.appendChild(canvas);
            window.scrollTo(0, scrollPos);
        }
    });
});

That is not working for me.


问:
Apply CSS style/class to div
I have some div elements

The structure is

```<code><div id="comment">
  <div id="m1">...</div>
  <div id="m2">...</div>
</div>
</code>```

I want to apply some CSS or Class to the even/odd inner div of comments (or to the m1/m2 div)

So i coded this, but it did not worked :(

```<code>$("div>div:even").addClass("evn");
</code>```

What i'm missing ?

答:
:even and :odd are 0-indexed, and may not produce results you're looking for. The first element is number 0, and that's even, so it gets selected by :even, rather than the second one.

For 1-indexing, you're missing the :nth-child() pseudo-class:

```<code>$("div > div:nth-child(even)").addClass("evn");
</code>```

Make sure that you spelled the class name correctly too, I don't know if your CSS defines an .evn class...

Title: Apply CSS style/class to div

Body:
I have some div elements

The structure is

...

...

I want to apply some CSS or Class to the even/odd inner div of comments (or to the m1/m2 div)

So i coded this, but it did not worked :(

$("div>div:even").addClass("evn");

What i'm missing ?

Body:
:even and :odd are 0-indexed, and may not produce results you're looking for. The first element is number 0, and that's even, so it gets selected by :even, rather than the second one.

For 1-indexing, you're missing the :nth-child() pseudo-class:

$("div > div:nth-child(even)").addClass("evn");

Make sure that you spelled the class name correctly too, I don't know if your CSS defines an .evn class...


问:
The return types for the following stored procedures could not be detected
While drag-drop a stored procedure in dbml file I get this error:

Unknown Return Type

  The return types for the following stored procedures could not be detected. Set the return type for each stored procedure in the Properties window.

How can I resolve this error?

答:
I had this error too and finally I found out that I have changed a table field name and in procedure it did not change it yet, and so it showed an error when adding to dbml.

Now you can check this on your procedure and your table that fields are the same.

I hope this experience is useful.


问:
How can I sort my records by average rating?
I have a table of venues which I'm displaying on the venues index page as partials. I also have a table of reviews where one venue can have many reviews and each review has a rating 1-5.

I'm trying to get the venues to display on the index page with the ones with the highest average rating at the top and descending.

The controller code looks like this:

Venues controller

```<code>def index
    if
      @venues = Venue.with_type(params[:venuetypes]).with_area(params[:areas]).joins(:reviews).order("reviews.rating DESC")
    else
      @venues = Venue.all
    end
  end
</code>```

This gives this kind of a result:

If venue 1 has a 5 star review it
shows the venue partial at the top of
the list.

If venue 2 has a 5 star review and
a 1 star review it shows two
partials, one at the top and one

at the bottom of the list.

If venue 3 has a 5 star review, a 3 star review and
a 1 star review it shows three
partials, one at the top, one in the middle and one
at the bottom of the list.

I just want one partial showing per venue but positioned in the list by the average rating, I feel theres a .average or something missing somewhere how can I acheive this?

Thanks for any help its much appreciated!

edit

Venue model

```<code>class Venue < ActiveRecord::Base
  attr_accessible :name, :addressline1, :addressline2, :addressline3, :addressline4, :postcode, :phonenumber, :about, :icontoppx, :iconleftpx, :area_id, :venuetype_id, :lat, :long, :venuephotos_attributes
  belongs_to :area
  belongs_to :venuetype
  has_many :reviews
  has_many :venuephotos

  accepts_nested_attributes_for :venuephotos, :allow_destroy => true

  scope :with_type, lambda { |types|
    types.present? ? where(:venuetype_id => types) : scoped }

  scope :with_area, lambda { |areas|
    areas.present? ? where(:area_id => areas) : scoped }

  def to_param
    "#{id}-#{name.gsub(/\W/, '-').downcase}"
  end

  def add_rating(rating_opts)
    @venue.add_rating(:rating => rating, :reviewer => params[:rating][:reviewer])
    self.reviews.create(rating_opts)
    self.update_rating!
  end

  def update_rating!
    s = self.reviews.sum(:rating)
    c = self.reviews.count
    self.update_attribute(:average_rating, s.to_f / c.to_f)
    self.save(:validate => false)
  end
end
</code>```

Development log for adding a review

```<code>Started POST "/venues/44-rating-test-5/reviews" for 127.0.0.1 at 2011-05-18 09:24:24 +0100
  Processing by ReviewsController#create as JS
  Parameters: {"utf8"=>"âœ“", "authenticity_token"=>"GZWd67b5ocJOjwKI6z9nJInBXxvQahHrjUtUpdm9oJE=", "review"=>{"rating"=>"5", "title"=>"5 star review"}, "venue_id"=>"44-rating-test-5"}
  [1m[36mVenue Load (1.0ms)[0m  [1mSELECT `venues`.* FROM `venues` WHERE (`venues`.`id` = 44) LIMIT 1[0m
  [1m[35mUser Load (0.0ms)[0m  SELECT `users`.* FROM `users` WHERE (`users`.`id` = 3) LIMIT 1
  [1m[36mSQL (0.0ms)[0m  [1mBEGIN[0m
  [1m[35mSQL (2.0ms)[0m  describe `reviews`
  [1m[36mAREL (0.0ms)[0m  [1mINSERT INTO `reviews` (`title`, `created_at`, `updated_at`, `venue_id`, `user_id`, `rating`) VALUES ('5 star review', '2011-05-18 08:24:24', '2011-05-18 08:24:24', NULL, 3, 5)[0m
  [1m[35mSQL (27.0ms)[0m  COMMIT
  [1m[36mSQL (0.0ms)[0m  [1mBEGIN[0m
  [1m[35mAREL (0.0ms)[0m  UPDATE `reviews` SET `venue_id` = 44, `updated_at` = '2011-05-18 08:24:24' WHERE (`reviews`.`id` = 90)
  [1m[36mSQL (23.0ms)[0m  [1mCOMMIT[0m
  [1m[35mSQL (1.0ms)[0m  SELECT COUNT(*) FROM `reviews` WHERE (`reviews`.venue_id = 44)
  [1m[36mUser Load (0.0ms)[0m  [1mSELECT `users`.* FROM `users` WHERE (`users`.`id` = 3) LIMIT 1[0m
Rendered reviews/_review.html.erb (9.0ms)
Rendered reviews/create.js.erb (22.0ms)
Completed 200 OK in 220ms (Views: 56.0ms | ActiveRecord: 54.0ms)
</code>```

edit
create review method (reviews controller)

```<code>def create
    @review = current_user.reviews.create!(params[:review])
    @review.venue = @venue
    if @review.save
      flash[:notice] = 'Thank you for reviewing this venue!'
      respond_to do |format|
        format.html { redirect_to venue_path(@venue) }
        format.js
      end
    else
      render :action => :new
    end
  end
</code>```

答:
To add to NoICE's answer, by hooking into the :after_add and :after_remove association callbacks, you don't have to remember to call a special add_rating method.

```<code>class Venue < ActiveRecord::Base
  has_many :reviews, :after_add => :update_average_rating, :after_remove => :update_average_rating

  def update_average_rating(review=nil)
    s = self.reviews.sum(:rating)
    c = self.reviews.count
    self.update_attribute(:average_rating, c == 0 ? 0.0 : s / c.to_f)
  end

end
</code>```

Also, you'll want to check count for 0 to prevent division by zero.

When you create the review, you must append with << or concat it to the venue object's reviews association so that the callback gets triggered. For example, this will associate the review to the venue, create the review (INSERT into the db), and trigger the callback:

```<code>@venue = Venue.find(params[:venue_id])
@venue.reviews << Review.new(params[:review])
</code>```

This will create the review but won't trigger the callback, even if the venue_id is the params:

```<code>Review.create(params[:review])
</code>```

If you really want to get your action to trigger the callback, you can change your code to:

```<code>def create
  @review = Review.new(params[:review].merge({ :user => current_user, :venue => @venue })
  if @review.valid? and @venue.reviews << @review
  ...
</code>```

To fix it expediently, though, you could just add @review.venue.update_average_rating just before the line w/ flash[:notice].

Body:
I have a table of venues which I'm displaying on the venues index page as partials. I also have a table of reviews where one venue can have many reviews and each review has a rating 1-5.

I'm trying to get the venues to display on the index page with the ones with the highest average rating at the top and descending.

The controller code looks like this:

Venues controller

def index
    if
      @venues = Venue.with_type(params[:venuetypes]).with_area(params[:areas]).joins(:reviews).order("reviews.rating DESC")
    else
      @venues = Venue.all
    end
  end

This gives this kind of a result:

If venue 1 has a 5 star review it
shows the venue partial at the top of
the list.

If venue 2 has a 5 star review and
a 1 star review it shows two
partials, one at the top and one

at the bottom of the list.

If venue 3 has a 5 star review, a 3 star review and
a 1 star review it shows three
partials, one at the top, one in the middle and one
at the bottom of the list.

I just want one partial showing per venue but positioned in the list by the average rating, I feel theres a .average or something missing somewhere how can I acheive this?

Thanks for any help its much appreciated!

edit

Venue model

class Venue < ActiveRecord::Base
  attr_accessible :name, :addressline1, :addressline2, :addressline3, :addressline4, :postcode, :phonenumber, :about, :icontoppx, :iconleftpx, :area_id, :venuetype_id, :lat, :long, :venuephotos_attributes
  belongs_to :area
  belongs_to :venuetype
  has_many :reviews
  has_many :venuephotos

  accepts_nested_attributes_for :venuephotos, :allow_destroy => true

  scope :with_type, lambda { |types|
    types.present? ? where(:venuetype_id => types) : scoped }

  scope :with_area, lambda { |areas|
    areas.present? ? where(:area_id => areas) : scoped }

  def to_param
    "#{id}-#{name.gsub(/\W/, '-').downcase}"
  end

  def add_rating(rating_opts)
    @venue.add_rating(:rating => rating, :reviewer => params[:rating][:reviewer])
    self.reviews.create(rating_opts)
    self.update_rating!
  end

  def update_rating!
    s = self.reviews.sum(:rating)
    c = self.reviews.count
    self.update_attribute(:average_rating, s.to_f / c.to_f)
    self.save(:validate => false)
  end
end

Development log for adding a review

Started POST "/venues/44-rating-test-5/reviews" for 127.0.0.1 at 2011-05-18 09:24:24 +0100
  Processing by ReviewsController#create as JS
  Parameters: {"utf8"=>"âœ“", "authenticity_token"=>"GZWd67b5ocJOjwKI6z9nJInBXxvQahHrjUtUpdm9oJE=", "review"=>{"rating"=>"5", "title"=>"5 star review"}, "venue_id"=>"44-rating-test-5"}
  [1m[36mVenue Load (1.0ms)[0m  [1mSELECT `venues`.* FROM `venues` WHERE (`venues`.`id` = 44) LIMIT 1[0m
  [1m[35mUser Load (0.0ms)[0m  SELECT `users`.* FROM `users` WHERE (`users`.`id` = 3) LIMIT 1
  [1m[36mSQL (0.0ms)[0m  [1mBEGIN[0m
  [1m[35mSQL (2.0ms)[0m  describe `reviews`
  [1m[36mAREL (0.0ms)[0m  [1mINSERT INTO `reviews` (`title`, `created_at`, `updated_at`, `venue_id`, `user_id`, `rating`) VALUES ('5 star review', '2011-05-18 08:24:24', '2011-05-18 08:24:24', NULL, 3, 5)[0m
  [1m[35mSQL (27.0ms)[0m  COMMIT
  [1m[36mSQL (0.0ms)[0m  [1mBEGIN[0m
  [1m[35mAREL (0.0ms)[0m  UPDATE `reviews` SET `venue_id` = 44, `updated_at` = '2011-05-18 08:24:24' WHERE (`reviews`.`id` = 90)
  [1m[36mSQL (23.0ms)[0m  [1mCOMMIT[0m
  [1m[35mSQL (1.0ms)[0m  SELECT COUNT(*) FROM `reviews` WHERE (`reviews`.venue_id = 44)
  [1m[36mUser Load (0.0ms)[0m  [1mSELECT `users`.* FROM `users` WHERE (`users`.`id` = 3) LIMIT 1[0m
Rendered reviews/_review.html.erb (9.0ms)
Rendered reviews/create.js.erb (22.0ms)
Completed 200 OK in 220ms (Views: 56.0ms | ActiveRecord: 54.0ms)

edit
create review method (reviews controller)

def create
    @review = current_user.reviews.create!(params[:review])
    @review.venue = @venue
    if @review.save
      flash[:notice] = 'Thank you for reviewing this venue!'
      respond_to do |format|
        format.html { redirect_to venue_path(@venue) }
        format.js
      end
    else
      render :action => :new
    end
  end

Body:
To add to NoICE's answer, by hooking into the :after_add and :after_remove association callbacks, you don't have to remember to call a special add_rating method.

class Venue < ActiveRecord::Base
  has_many :reviews, :after_add => :update_average_rating, :after_remove => :update_average_rating

  def update_average_rating(review=nil)
    s = self.reviews.sum(:rating)
    c = self.reviews.count
    self.update_attribute(:average_rating, c == 0 ? 0.0 : s / c.to_f)
  end

end

Also, you'll want to check count for 0 to prevent division by zero.

When you create the review, you must append with << or concat it to the venue object's reviews association so that the callback gets triggered. For example, this will associate the review to the venue, create the review (INSERT into the db), and trigger the callback:

@venue = Venue.find(params[:venue_id])
@venue.reviews << Review.new(params[:review])

This will create the review but won't trigger the callback, even if the venue_id is the params:

Review.create(params[:review])

If you really want to get your action to trigger the callback, you can change your code to:

def create
  @review = Review.new(params[:review].merge({ :user => current_user, :venue => @venue })
  if @review.valid? and @venue.reviews << @review
  ...

To fix it expediently, though, you could just add @review.venue.update_average_rating just before the line w/ flash[:notice].


问:
Jmeter cyclic running tests
I want to run cyclical tests in jmeter. I want them to run every day and than run for 10 minutes (every day for 10 minutes). How to do it?</p>

答:
There are many ways to answer your (a bit too broad) question.
Here are some insights that could help:

to launch a JMeter test that last 10 minutes, you have to configure a job in JMeter with such a duration. Then you have to lear how to launch it via command line instead of via the graphical interface (see this answer for example)

to launch your JMeter test every day, you can use a Continuous Integration tool like Jenkins. In this tool, you will be able to create some jobs with a specific schedule (every day in your case) and a specific task (launch my JMeter test via command line)

Title: Jmeter cyclic running tests