问:
could any one help me to rectify Error with bigcommerce CLI
I am new to bigcommerce. I have followed Stencil CLI comments to work with local copy of theme.
while using STENCIL BUNDLE comment i am getting following error. can any one help me to rectify it.

stencil bundle

Validating theme...

/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/lib/stencil-bundle.js:290

```<code>        throw err;
        ^
</code>```

Error: Your theme's schema.json has errors:

schema[5].settings[1].options[0].value should NOT be shorter than 1 characters
    at validateJsonSchema

(/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/lib/bundle-validator.js:134:16)
    at BundleValidator.validateThemeSchema (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/lib/bundle-validator.js:78:23)
    at /home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:3880:24
    at replenish (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1011:17)
    at /home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1016:9
    at eachOfLimit (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1041:24)
    at /home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1046:16
    at _parallel (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:3879:5)
    at Object.series (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:4735:5)
    at BundleValidator.validateTheme (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/lib/bundle-validator.js:55:11)
    at Bundle.validateTheme (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/lib/stencil-bundle.js:288:20)
    at /home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:3880:24
    at replenish (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1011:17)
    at /home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1016:9
    at eachOfLimit (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1041:24)
    at /home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1046:16

答:
This looks similar to errors when the schema.json or schemaTranslations.json file have been removed or modified, are you using the base Cornerstone theme? Could you add any relevant schema code in your post? If the schema.json should be the same as the base Cornerstone theme, I'd verify this against the GitHub repo here.

Since Stencil CLI 2.0, part of the bundle process now validates a schemaTranlsations.json file which has been included since Cornerstone 4.5.1.

Body:
I am new to bigcommerce. I have followed Stencil CLI comments to work with local copy of theme.
while using STENCIL BUNDLE comment i am getting following error. can any one help me to rectify it.

stencil bundle

Validating theme...

/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/lib/stencil-bundle.js:290

        throw err;
        ^

Error: Your theme's schema.json has errors:

schema[5].settings[1].options[0].value should NOT be shorter than 1 characters
    at validateJsonSchema

(/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/lib/bundle-validator.js:134:16)
    at BundleValidator.validateThemeSchema (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/lib/bundle-validator.js:78:23)
    at /home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:3880:24
    at replenish (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1011:17)
    at /home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1016:9
    at eachOfLimit (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1041:24)
    at /home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1046:16
    at _parallel (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:3879:5)
    at Object.series (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:4735:5)
    at BundleValidator.validateTheme (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/lib/bundle-validator.js:55:11)
    at Bundle.validateTheme (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/lib/stencil-bundle.js:288:20)
    at /home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:3880:24
    at replenish (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1011:17)
    at /home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1016:9
    at eachOfLimit (/home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1041:24)
    at /home/innoppl/.nvm/versions/node/v10.16.3/lib/node_modules/@bigcommerce/stencil-cli/node_modules/async/dist/async.js:1046:16


来源: stackexchange

问:
SciPy programming on CUDA cores
Has somebody managed to apply SciPy functions on CUDA kernels? As far as I see from the literature, there is no explicit support of SciPy for GPU computing.

I would like to speed-up code with some SciPy.optimize functions by applying it on CUDA kernels. If somebody knows of any other library for nonlinear optimization that can be applied on CUDA GPUs, would very much appreciate sharing it here.

答: Have run into similar problems and I am now using tensorflow_probability's optimize capabilities.  The biggest problem is that tensorflow ops often cannot be directly implemented from numpy functions, so there is a pretty steep learning curve.  But it is very fast once your code is written.</p>

ContentLicense: CC BY-SA 4.0

Title: SciPy programming on CUDA cores


问:
How to generate allure report after running selenium test jar in docker environment
I'm trying to execute an allure report after running a selenium executable jar in a docker container. I've been trying to get this working for 4 days, can someone advise if I'm missing something or using the wrong approach?

What I've done and tried so far:

Built the selenium test executable jar (fatjar) using a dockerfile.

Installed allure using the dockerfile while building the test jar file.

Added AllureJunit4 after reading this Allure - generate allure-results with jar which generates the correct directory when running in local but doesn't generate the directory in docker.

Inspected image and running container using docker exec -it to look for allure-results dir.

Used docker cp to try and copy out folders that I think might have allure reports.

The Entrypoint in my docker file is ENTRYPOINT ["java", "-jar", "automation-tests.jar"]. So when I do docker build --tag <tagname> . and docker run <tagname> the jar file runs and executes with no errors.

Below is a sample of my dockerfile

```<code>RUN wget https://chromedriver.storage.googleapis.com/80.0.3987.106/chromedriver_linux64.zip
RUN unzip chromedriver_linux64.zip
RUN mv chromedriver /usr/bin/chromedriver
RUN chown root:root /usr/bin/chromedriver
RUN chmod +x /usr/bin/chromedriver

RUN wget https://github.com/allure-framework/allure-core/releases/download/allure-core-1.4.24.RC2/allure-commandline.zip && \
     unzip allure-commandline.zip && bin/allure && rm allure-commandline.zip

FROM gradle:6.1.1-jdk8 AS sdk
WORKDIR /auto

WORKDIR /auto/build
RUN gradle clean fatJar -x test

FROM runtime AS final
COPY --from=sdk path/to/jar/automation-stuff*.jar ./auto-testing.jar

ENTRYPOINT ["java", "-jar", "auto-testing.jar"]
</code>```

None of these have produced any results so if anyone can help me then I'd truly appreciate it.
So just to clarify this is only a problem generating the allure report.

答:
You can use the Allure Docker Service container. Once your tests generate the allure results you can send them using the Allure API and see your updated report.
https://github.com/fescobar/allure-docker-service#send-results-through-api</p>

Body:
I'm trying to execute an allure report after running a selenium executable jar in a docker container. I've been trying to get this working for 4 days, can someone advise if I'm missing something or using the wrong approach?

What I've done and tried so far:

Built the selenium test executable jar (fatjar) using a dockerfile.

Installed allure using the dockerfile while building the test jar file.

Added AllureJunit4 after reading this Allure - generate allure-results with jar which generates the correct directory when running in local but doesn't generate the directory in docker.

Inspected image and running container using docker exec -it to look for allure-results dir.

Used docker cp to try and copy out folders that I think might have allure reports.

The Entrypoint in my docker file is ENTRYPOINT ["java", "-jar", "automation-tests.jar"]. So when I do docker build --tag <tagname> . and docker run <tagname> the jar file runs and executes with no errors.

Below is a sample of my dockerfile

RUN wget https://chromedriver.storage.googleapis.com/80.0.3987.106/chromedriver_linux64.zip
RUN unzip chromedriver_linux64.zip
RUN mv chromedriver /usr/bin/chromedriver
RUN chown root:root /usr/bin/chromedriver
RUN chmod +x /usr/bin/chromedriver

RUN wget https://github.com/allure-framework/allure-core/releases/download/allure-core-1.4.24.RC2/allure-commandline.zip && \
     unzip allure-commandline.zip && bin/allure && rm allure-commandline.zip

FROM gradle:6.1.1-jdk8 AS sdk
WORKDIR /auto

WORKDIR /auto/build
RUN gradle clean fatJar -x test

FROM runtime AS final
COPY --from=sdk path/to/jar/automation-stuff*.jar ./auto-testing.jar

ENTRYPOINT ["java", "-jar", "auto-testing.jar"]

None of these have produced any results so if anyone can help me then I'd truly appreciate it.
So just to clarify this is only a problem generating the allure report.


问:
How to generate Perlin Noise on an iPhone
I want to create an animated perlin noise on the iPhone, so I can ultimately do something like this: http://dl.dropbox.com/u/1977230/example.png

I've looked and looked, but can't find anything similar or a way to actually display a Perlin Noise.

I've been told to look at OpenGL ES, but even searching for an example of Perlin noise or a lava/plasma effect doesn't result in anything.

I'd really appreciate some help on this one.

Thanks guys,
Andre

答: Now there is another Perlin noise function for GLSL shader that doesn't require lookup textures: https://github.com/ashima/webgl-noise/tree/master/src. This should work on iPhones.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
java -version showing different version than in path
I have jdk12 and jdk8 on my computer installed. Usually jdk12 is set in the path.
To run some java programs I had set path to jdk8. Now after changing the path back to /jdk-12.0.1/bin, running java -version on cmd still returns

```<code>java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)
</code>```

答:
If you have multiple Java installed, create the JAVA_HOME variable and give the JAVA path which you want to use. Use only this JAVA_HOME variable in the PATH variable.

If you wish to change the default Java, change only the JAVA_HOME variable pointing to the required JAVA.

This way, only one JAVA (which is required) will be present in PATH. Remove all other JAVA references in the PATH variable.

Also, whenever you change the JAVA_HOME value, open a new terminal (command prompt) to verify this change.

Note: If the path contains spaces, use the shortened path name. For example, C:\Progra~1\Java\jdk1.8.0_65

Body:
I have jdk12 and jdk8 on my computer installed. Usually jdk12 is set in the path.
To run some java programs I had set path to jdk8. Now after changing the path back to /jdk-12.0.1/bin, running java -version on cmd still returns

java version "1.8.0_251"
Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)


问:
Exception: IL2CPP.exe did not run properly! Unity 3D build issue
My unity version 2019.3.12f1
I have problem with build my Android game. When I want use IL2CPP, I can't build my game. In console is this errors:

```<code>Exception: C:\Program Files\Unity\Editor\Data\il2cpp/build/deploy/net471/il2cpp.exe did not run properly!

Exception: C:\Program Files\Unity\Editor\Data\il2cpp/build/deploy/net471/il2cpp.exe did not run properly!
UnityEditorInternal.Runner.RunProgram (UnityEditor.Utils.Program p, System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser) (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEditorInternal.Runner.RunManagedProgram (System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, System.Action`1[T] setupStartInfo) (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEditorInternal.IL2CPPBuilder.RunIl2CppWithArguments (System.Collections.Generic.List`1[T] arguments, System.Action`1[T] setupStartInfo, System.String workingDirectory) (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEditorInternal.IL2CPPBuilder.ConvertPlayerDlltoCpp (UnityEditor.Il2Cpp.Il2CppBuildPipelineData data, System.String outputDirectory, System.String workingDirectory, System.Boolean platformSupportsManagedDebugging) (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEditorInternal.IL2CPPBuilder.Run () (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEditorInternal.IL2CPPUtils.RunIl2Cpp (System.String tempFolder, System.String stagingAreaData, UnityEditorInternal.IIl2CppPlatformProvider platformProvider, System.Action`1[T] modifyOutputBeforeCompile, UnityEditor.RuntimeClassRegistry runtimeClassRegistry) (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEditor.Android.PostProcessor.Tasks.RunIl2Cpp.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <3167064085404657b0d6c498207da025>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <3167064085404657b0d6c498207da025>:0)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (UnityEditor.BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <3167064085404657b0d6c498207da025>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <3167064085404657b0d6c498207da025>:0)
UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)
</code>```

How can I fix it?

When I use Mono, building is working.
When I use ILC2PP, building is not working.

答: The problem is this Unity Assets Name has you in pic the name of folder is.." VacuumShaders" I removed these Assets my Project build Success in IL2CPP

Body:
My unity version 2019.3.12f1
I have problem with build my Android game. When I want use IL2CPP, I can't build my game. In console is this errors:

Exception: C:\Program Files\Unity\Editor\Data\il2cpp/build/deploy/net471/il2cpp.exe did not run properly!

Exception: C:\Program Files\Unity\Editor\Data\il2cpp/build/deploy/net471/il2cpp.exe did not run properly!
UnityEditorInternal.Runner.RunProgram (UnityEditor.Utils.Program p, System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser) (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEditorInternal.Runner.RunManagedProgram (System.String exe, System.String args, System.String workingDirectory, UnityEditor.Scripting.Compilers.CompilerOutputParserBase parser, System.Action`1[T] setupStartInfo) (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEditorInternal.IL2CPPBuilder.RunIl2CppWithArguments (System.Collections.Generic.List`1[T] arguments, System.Action`1[T] setupStartInfo, System.String workingDirectory) (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEditorInternal.IL2CPPBuilder.ConvertPlayerDlltoCpp (UnityEditor.Il2Cpp.Il2CppBuildPipelineData data, System.String outputDirectory, System.String workingDirectory, System.Boolean platformSupportsManagedDebugging) (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEditorInternal.IL2CPPBuilder.Run () (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEditorInternal.IL2CPPUtils.RunIl2Cpp (System.String tempFolder, System.String stagingAreaData, UnityEditorInternal.IIl2CppPlatformProvider platformProvider, System.Action`1[T] modifyOutputBeforeCompile, UnityEditor.RuntimeClassRegistry runtimeClassRegistry) (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEditor.Android.PostProcessor.Tasks.RunIl2Cpp.Execute (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <3167064085404657b0d6c498207da025>:0)
UnityEditor.Android.PostProcessor.PostProcessRunner.RunAllTasks (UnityEditor.Android.PostProcessor.PostProcessorContext context) (at <3167064085404657b0d6c498207da025>:0)
UnityEditor.Android.PostProcessAndroidPlayer.PostProcess (UnityEditor.BuildTarget target, System.String stagingAreaData, System.String stagingArea, System.String playerPackage, System.String installPath, System.String companyName, System.String productName, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <3167064085404657b0d6c498207da025>:0)
UnityEditor.Android.AndroidBuildPostprocessor.PostProcess (UnityEditor.Modules.BuildPostProcessArgs args, UnityEditor.BuildProperties& outProperties) (at <3167064085404657b0d6c498207da025>:0)
UnityEditor.PostprocessBuildPlayer.Postprocess (UnityEditor.BuildTargetGroup targetGroup, UnityEditor.BuildTarget target, System.String installPath, System.String companyName, System.String productName, System.Int32 width, System.Int32 height, UnityEditor.BuildOptions options, UnityEditor.RuntimeClassRegistry usedClassRegistry, UnityEditor.Build.Reporting.BuildReport report) (at <ffcf2f9855fe46038192299154f37a45>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr)

How can I fix it?

When I use Mono, building is working.
When I use ILC2PP, building is not working.


问:
Contenteditable paragraphs in html
I am creating a contenteditable paragraph in html. I have a button which on clicking will make the text bold. The first time it is clicked the text should change to bold,and the next time it is clicked ,the text should be normal(not bolder).This is similar to the Stack overflow question editor.html code:

```<code>    <button type="button" id="bold" onclick="bold()">B</button>
    <div id="content">
       <p id="hey" contenteditable="true">Hi how are you</p>
    </div>
</code>```

JS:

```<code>        let boldClick=0;
        let p=document.getElementById('hey');
        function bold(){
           if(boldClick%2==0){

             p.innerHTML=p.innerHTML+' <span contenteditable="true">'+' boldtext'+'</span>';
           }
           else{
              let pNew=document.createElement('p');
              pNew.setAttribute("contenteditable","true");
              document.getElementById('content').appendChild(pNew);
           }
           boldClick++;
        }
</code>```

CSS:

```<code>        #bold{
            font-weight: bold;
        }
        span{
            font-weight: bold;
            background-color: grey;
        }
        p{
            display: inline;
        }
</code>```

I can make the text bolder by clicking the button.Bolder texts must be inside the span element and non-bolder texts must be outside span but inside
  p element.How do I solve it?

答:
approach 1:

```<code>    let boldClick=0;
    let p=document.getElementById('hey');
    p.innerHTML=p.innerHTML+' <span contenteditable="true" id="bold">'+' boldtext'+'</span>';
     const boldTag = document.getElementById('bold');
    function bold(){
       if(boldClick%2==0){
      boldTag.style.fontWeight="";
       }
       else{
         boldTag.style.fontWeigh="bold";
       }
       boldClick++;
    }
</code>```

approach 2:

```<code>    let boldClick=0;
    let p=document.getElementById('hey');
    p.innerHTML=p.innerHTML+' <span contenteditable="true" id="bold">'+' boldtext'+'</span>';
     const boldTag = document.getElementById('bold');
    function bold(){
       if(boldClick%2==0){
      boldTag.id="";
       }
       else{
         boldTag.id="bold";
       }
       boldClick++;
    }
</code>```

these approaches are not optimized , but hope you get the concept .

Title: Contenteditable paragraphs in html

Body:
I am creating a contenteditable paragraph in html. I have a button which on clicking will make the text bold. The first time it is clicked the text should change to bold,and the next time it is clicked ,the text should be normal(not bolder).This is similar to the Stack overflow question editor.html code:

    <button type="button" id="bold" onclick="bold()">B</button>

Hi how are you

JS:

        let boldClick=0;
        let p=document.getElementById('hey');
        function bold(){
           if(boldClick%2==0){

             p.innerHTML=p.innerHTML+' '+' boldtext'+'';
           }
           else{
              let pNew=document.createElement('p');
              pNew.setAttribute("contenteditable","true");
              document.getElementById('content').appendChild(pNew);
           }
           boldClick++;
        }

CSS:

        #bold{
            font-weight: bold;
        }
        span{
            font-weight: bold;
            background-color: grey;
        }
        p{
            display: inline;
        }

I can make the text bolder by clicking the button.Bolder texts must be inside the span element and non-bolder texts must be outside span but inside
  p element.How do I solve it?

Body:
approach 1:

    let boldClick=0;
    let p=document.getElementById('hey');
    p.innerHTML=p.innerHTML+' <span contenteditable="true" id="bold">'+' boldtext'+'</span>';
     const boldTag = document.getElementById('bold');
    function bold(){
       if(boldClick%2==0){
      boldTag.style.fontWeight="";
       }
       else{
         boldTag.style.fontWeigh="bold";
       }
       boldClick++;
    }

approach 2:

    let boldClick=0;
    let p=document.getElementById('hey');
    p.innerHTML=p.innerHTML+' <span contenteditable="true" id="bold">'+' boldtext'+'</span>';
     const boldTag = document.getElementById('bold');
    function bold(){
       if(boldClick%2==0){
      boldTag.id="";
       }
       else{
         boldTag.id="bold";
       }
       boldClick++;
    }

these approaches are not optimized , but hope you get the concept .


问:
How to collect elements of a collection basing on a result of some method?
Suppose we have a list of values sorted according to some ordering. We also have a map of elements mapped to these values. We want to obtain a collection of elements from the map in the same order as their keys are in the list. A straightforward method to do this is:

```<code>val order = Seq("a", "b", "c")
val map = Map("a" -> "aaa", "c" -> "ccc")

val elems = order.map(map.get(_)).filter(_.isDefined).map(_.get)
</code>```

However the program needs to iterate over the collection three times. Is it possible to implement this functionality more efficiently? In particular, is it possible to do this with collect method?

答:
Well, a standard Scala map is also a PartialFunction, so you can use "collect".</p>

```<code>val elems = order.collect(map)
</code>```

Body:
Suppose we have a list of values sorted according to some ordering. We also have a map of elements mapped to these values. We want to obtain a collection of elements from the map in the same order as their keys are in the list. A straightforward method to do this is:

val order = Seq("a", "b", "c")
val map = Map("a" -> "aaa", "c" -> "ccc")

val elems = order.map(map.get(_)).filter(_.isDefined).map(_.get)

However the program needs to iterate over the collection three times. Is it possible to implement this functionality more efficiently? In particular, is it possible to do this with collect method?

Body:
Well, a standard Scala map is also a PartialFunction, so you can use "collect".

val elems = order.collect(map)


问:
Extract value from all objects with similar names to a table in R
I have a bunch of R objects, all of their names starting with abund_envir_reduc . I need to extract their value in $statistic to a data frame, with the first column being the name of the object and the second its corresponding statistic value.

Object examples ($statistic class is "numeric"):

```<code>abund_envir_reduc_4$statistic
[1] 0.0071
abund_envir_reduc_2_6_7$statistic
[1] 0.214
abund_envir_reduc_2_2$statistic
[1] 0.056
abund_envir_reduc_7_8_6_2_5$statistic
[1] 0.522
abund_envir_reduc_1_2_3$statistic
[1] 0.2031
</code>```

Desired output:

```<code>ID                            STATISTIC
abund_envir_reduc_4           0.0071
abund_envir_reduc_2_6_7       0.214
abund_envir_reduc_2_2         0.056
abund_envir_reduc_7_8_6_2_5   0.522
abund_envir_reduc_1_2_3       0.2031
</code>```

答:
A raw base R option:

```<code>objs <- mget(ls(pattern = "abund_envir_reduc_.+"))
stack(unlist(objs))

  values                                   ind
1 0.2031     abund_envir_reduc_1_2_3.statistic
2 0.0560       abund_envir_reduc_2_2.statistic
3 0.2140     abund_envir_reduc_2_6_7.statistic
4 0.0071         abund_envir_reduc_4.statistic
5 0.5220 abund_envir_reduc_7_8_6_2_5.statistic
</code>```

Data (please provide it next time)

```<code>abund_envir_reduc_1_2_3     <- list(statistic = 0.2031)
abund_envir_reduc_2_2       <- list(statistic = 0.056)
abund_envir_reduc_2_6_7     <- list(statistic = 0.214)
abund_envir_reduc_4         <- list(statistic = 0.0071)
abund_envir_reduc_7_8_6_2_5 <- list(statistic = 0.522)
</code>```

Body:
I have a bunch of R objects, all of their names starting with abund_envir_reduc . I need to extract their value in $statistic to a data frame, with the first column being the name of the object and the second its corresponding statistic value.

Object examples ($statistic class is "numeric"):

abund_envir_reduc_4$statistic
[1] 0.0071
abund_envir_reduc_2_6_7$statistic
[1] 0.214
abund_envir_reduc_2_2$statistic
[1] 0.056
abund_envir_reduc_7_8_6_2_5$statistic
[1] 0.522
abund_envir_reduc_1_2_3$statistic
[1] 0.2031

Desired output:

ID                            STATISTIC
abund_envir_reduc_4           0.0071
abund_envir_reduc_2_6_7       0.214
abund_envir_reduc_2_2         0.056
abund_envir_reduc_7_8_6_2_5   0.522
abund_envir_reduc_1_2_3       0.2031

Body:
A raw base R option:

objs <- mget(ls(pattern = "abund_envir_reduc_.+"))
stack(unlist(objs))

  values                                   ind
1 0.2031     abund_envir_reduc_1_2_3.statistic
2 0.0560       abund_envir_reduc_2_2.statistic
3 0.2140     abund_envir_reduc_2_6_7.statistic
4 0.0071         abund_envir_reduc_4.statistic
5 0.5220 abund_envir_reduc_7_8_6_2_5.statistic

Data (please provide it next time)

abund_envir_reduc_1_2_3     <- list(statistic = 0.2031)
abund_envir_reduc_2_2       <- list(statistic = 0.056)
abund_envir_reduc_2_6_7     <- list(statistic = 0.214)
abund_envir_reduc_4         <- list(statistic = 0.0071)
abund_envir_reduc_7_8_6_2_5 <- list(statistic = 0.522)


问:
MongoDb Node js Real Time notifications with change streams
In my web application i have followers and notifications. The problem is how to get to the list of users and report changes of some document like changed price, or user created one more property etc.. So i can use change streams to watch for changes inside collection.

```<code>Property.watch().
on('change', async data => {
  let prop = await Property.findById(data.documentKey._id);
  let user = await Follow.findOne({userId: prop.user._id});

  // After that find all followers then
  user.followers.forEach(foll => {
    await Notification.create({
      ...
    })
  })
});

</code>```

This code looks crazy to me, I mean even with some validations etc.. this is again overkill.

Maybe better approach is some logic inside controller, but how i can first return response to user after he successfully created or updated document and then run some function where i can find all users on followers list and create notifications for them ?

What you guys think ? There is not much examples and solutions for notification system, is there any resource that can be helpful

答:
So basically i ended up with code like this. Inside update and create controller i'm creating user activity and then i'm watching that model. </p>

```<code>Activity.watch().on('change', async (data) => {
  const { fullDocument } = data;
  const followers = await Follow.findOne({ user: fullDocument.user});
  if(!followers) return;

  let doc = [];

  followers.followers.forEach(follower => {
    let obj = {};

    obj.senderId = fullDocument.user;
    obj.receiverId = follower;
    obj.message = fullDocument.activityMessage;

    doc.push(obj);
  })

  try {
    await Notification.insertMany(doc);
  } catch(err) {
    console.log(err);
  }
})
</code>```

Body:
In my web application i have followers and notifications. The problem is how to get to the list of users and report changes of some document like changed price, or user created one more property etc.. So i can use change streams to watch for changes inside collection.

Property.watch().
on('change', async data => {
  let prop = await Property.findById(data.documentKey._id);
  let user = await Follow.findOne({userId: prop.user._id});

  // After that find all followers then
  user.followers.forEach(foll => {
    await Notification.create({
      ...
    })
  })
});

This code looks crazy to me, I mean even with some validations etc.. this is again overkill.

Maybe better approach is some logic inside controller, but how i can first return response to user after he successfully created or updated document and then run some function where i can find all users on followers list and create notifications for them ?

What you guys think ? There is not much examples and solutions for notification system, is there any resource that can be helpful

Body:
So basically i ended up with code like this. Inside update and create controller i'm creating user activity and then i'm watching that model.

Activity.watch().on('change', async (data) => {
  const { fullDocument } = data;
  const followers = await Follow.findOne({ user: fullDocument.user});
  if(!followers) return;

  let doc = [];

  followers.followers.forEach(follower => {
    let obj = {};

    obj.senderId = fullDocument.user;
    obj.receiverId = follower;
    obj.message = fullDocument.activityMessage;

    doc.push(obj);
  })

  try {
    await Notification.insertMany(doc);
  } catch(err) {
    console.log(err);
  }
})


问:
How to generate allure report that carries the history information.
I have a bash script to run the selenium test case in docker. And last step of this script is to generate the allure report of the test results, such as:

```<code> export ALLURE_IMAGE=beeete2/docker-allure2
 export PROJECT_DIR=selenium-suites
 export ALLURE_REPORT_DIR=allure-report
 export ALLURE_CONFIG_DIR=allure-config
 docker run --rm  \
           -v $(pwd)/$ALLURE_REPORT_DIR:/$ALLURE_REPORT_DIR \
           -v $(pwd)/$PROJECT_DIR/$ALLURE_RESULTS_DIR:/$ALLURE_RESULTS_DIR \
           -v $(pwd)/$PROJECT_DIR/$ALLURE_CONFIG_DIR:/$ALLURE_CONFIG_DIR \
           $ALLURE_IMAGE allure generate /$ALLURE_RESULTS_DIR -o /$ALLURE_REPORT_DIR --clean
</code>```

If the report was 1st time created, this allure-report dir will be created and the whole directory structure would be as:

```<code>├── allure-report
│   ├── app.js
│   ├── data
│   ├── export
│   ├── favicon.ico
│   ├── history
│   ├── index.html
│   ├── plugins
│   ├── styles.css
│   └── widgets
├── selenium-suites
│   ├── allure-config
│   ├── ...
</code>```

I want to know how do I keep the previous history, if I was to run the script for the 2nd, or 3rd time, and the latest allure report is created ?

I've googled and have found that I should have history part saved in a separate allure-results dir, before the next execution starts, such as:

```<code>if [[ -e ./allure-report/history ]]; then
    if [[ -e ./allure-results/history ]]; then
        rm -rf ./allure-results/history
    fi
    mv ./allure-report/history ./allure-results/history
fi
</code>```

By this, It will try to save the latest allure-report/history part into allure-results/history, but I am not sure when the next execution is done, and is about to create a new report under allure-report, how does it know there is history saved under allure-results/... ?

答:
You can navigate through your history executions using this docker container:
https://github.com/fescobar/allure-docker-service#keep-history-and-trends</p>

Body:
I have a bash script to run the selenium test case in docker. And last step of this script is to generate the allure report of the test results, such as:

 export ALLURE_IMAGE=beeete2/docker-allure2
 export PROJECT_DIR=selenium-suites
 export ALLURE_REPORT_DIR=allure-report
 export ALLURE_CONFIG_DIR=allure-config
 docker run --rm  \
           -v $(pwd)/$ALLURE_REPORT_DIR:/$ALLURE_REPORT_DIR \
           -v $(pwd)/$PROJECT_DIR/$ALLURE_RESULTS_DIR:/$ALLURE_RESULTS_DIR \
           -v $(pwd)/$PROJECT_DIR/$ALLURE_CONFIG_DIR:/$ALLURE_CONFIG_DIR \
           $ALLURE_IMAGE allure generate /$ALLURE_RESULTS_DIR -o /$ALLURE_REPORT_DIR --clean

If the report was 1st time created, this allure-report dir will be created and the whole directory structure would be as:

├── allure-report
│   ├── app.js
│   ├── data
│   ├── export
│   ├── favicon.ico
│   ├── history
│   ├── index.html
│   ├── plugins
│   ├── styles.css
│   └── widgets
├── selenium-suites
│   ├── allure-config
│   ├── ...

I want to know how do I keep the previous history, if I was to run the script for the 2nd, or 3rd time, and the latest allure report is created ?

I've googled and have found that I should have history part saved in a separate allure-results dir, before the next execution starts, such as:

if [[ -e ./allure-report/history ]]; then
    if [[ -e ./allure-results/history ]]; then
        rm -rf ./allure-results/history
    fi
    mv ./allure-report/history ./allure-results/history
fi

By this, It will try to save the latest allure-report/history part into allure-results/history, but I am not sure when the next execution is done, and is about to create a new report under allure-report, how does it know there is history saved under allure-results/... ?


问:
How to use R function properly
I have a dataframe named data and columns comfort, condition and few others.
I do one and the same manipulations with 5 columns and decided to write the following function:

```<code>replacing_na_999<-function(df, variable){
  #variable<-as.name(variable)
  levels <- levels(df$variable)
  levels[length(levels) + 1] <- "999"
  df$variable <- factor(df$variable, levels = levels)
  df$variable[is.na(df$variable)] <- "999"
}

</code>```

When I try:

```<code>replacing_na_999(data, comfort)
</code>```

it returns an error:

```<code> Error in `$<-.data.frame`(`*tmp*`, variable, value = integer(0)) :
  replacement has 0 rows, data has 44070
</code>```

Can someone help me please with syntaxis?

Title: How to use R function properly

Body:
I have a dataframe named data and columns comfort, condition and few others.
I do one and the same manipulations with 5 columns and decided to write the following function:

replacing_na_999<-function(df, variable){
  #variable<-as.name(variable)
  levels <- levels(df$variable)
  levels[length(levels) + 1] <- "999"
  df$variable <- factor(df$variable, levels = levels)
  df$variable[is.na(df$variable)] <- "999"
}

When I try:

replacing_na_999(data, comfort)

it returns an error:

 Error in `$<-.data.frame`(`*tmp*`, variable, value = integer(0)) :
  replacement has 0 rows, data has 44070

Can someone help me please with syntaxis?

Body:
this works on my computer

m<-structure(list(district = structure(c(6L, 21L, 20L, 19L, 5L, 8L),
                                           .Label = c("I", "II", "III", "IV", "IX", "V", "VI", "VII", "VIII", "X", "XI", "XII", "XIII", "XIV", "XIX", "XV", "XVI", "XVII", "XVIII", "XX", "XXI", "XXII", "XXIII"),
                                           class = "factor"),
                      ln_price = c(5.52146091786225, 4.9416424226093, 4.74493212836325, 5.01063529409626, 4.55387689160054, 5.07517381523383)),
                 row.names = c(NA, 6L), class = "data.frame")
    m[4,1]<-NA
    m

    m<-sapply(m,function(x) {
      if(is.factor(x))
        factor(x,levels=c(levels(x),999))
      else x
    }
    )

    m[is.na(m)]<-999
    m


问:
How to solve the select overlap bug in IE6?
When using IE, you cannot put an absolutely positioned div over a select input element. That's because the select element is considered an ActiveX object and is on top of every HTML element in the page.

I already saw people hiding selects when opening a popup div, that leads to pretty bad user experience having controls disappearing.

FogBugz actually had a pretty smart solution (before v6) of turning every select into text boxes when a popup was displayed. This solved the bug and tricked the user eye but the behavior was not perfect.

Another solution is in FogBugz 6 where they no more use the select element and recoded it everywhere.

Last solution I currently use is messing up the IE rendering engine and force it to render the absolutely positioned
 as an ActiveX element too, ensuring it can live over a select element. This is achieved by placing an invisible  inside the
 and styling it with:

#MyDiv iframe
{
    position: absolute;
    z-index: -1;
    filter: mask();
    border: 0;
    margin: 0;
    padding: 0;
    top: 0;
    left: 0;
    width: 9999px;
    height: 9999px;
    overflow: hidden;
}
```

Does anyone have an even better solution than this one?

EDIT: The purpose of this question is as much informative as it is a real question. I find the  trick to be a good solution, but I am still looking for improvement like removing this ugly useless tag that degrades accessibility.

答: When hiding the select elements hide them by setting the "visibility: hidden" instead of display: none otherwise the browser will re-flow the document.</p>

Body:
When using IE, you cannot put an absolutely positioned div over a select input element. That's because the select element is considered an ActiveX object and is on top of every HTML element in the page.

I already saw people hiding selects when opening a popup div, that leads to pretty bad user experience having controls disappearing.

FogBugz actually had a pretty smart solution (before v6) of turning every select into text boxes when a popup was displayed. This solved the bug and tricked the user eye but the behavior was not perfect.

Another solution is in FogBugz 6 where they no more use the select element and recoded it everywhere.

Last solution I currently use is messing up the IE rendering engine and force it to render the absolutely positioned
 as an ActiveX element too, ensuring it can live over a select element. This is achieved by placing an invisible  inside the
 and styling it with:

#MyDiv iframe
{
    position: absolute;
    z-index: -1;
    filter: mask();
    border: 0;
    margin: 0;
    padding: 0;
    top: 0;
    left: 0;
    width: 9999px;
    height: 9999px;
    overflow: hidden;
}

Does anyone have an even better solution than this one?

EDIT: The purpose of this question is as much informative as it is a real question. I find the  trick to be a good solution, but I am still looking for improvement like removing this ugly useless tag that degrades accessibility.

LastEditorDisplayName: Ross


问:
Python: How to label this dataset
Hi I have df like this:

```<code>df = pd.DataFrame({'CaseNo':[1,1,1,1,2,2,3,3,3,4,4],
                   'Category':['A','A','IOU','A','B','B','IOU','IOU','IOU','C','IOU']})
</code>```

I'd like to label CaseNo col based on this condition:

For each CaseNo, if there is an occurrence of value 'IOU' in Category column with any values (except 'IOU') preceding it - label 'YES', else label 'NO'.

How can I do this in Python? Expected outcome:

答:
Let us try transform with first and any

```<code>g=df.Category.eq('IOU').groupby(df['CaseNo'])
m=g.transform('any') & ~g.transform('first')
df['New']=m.map({True:'Yes',False:'No'})
df
Out[24]:
    CaseNo Category  New
0        1        A  Yes
1        1        A  Yes
2        1      IOU  Yes
3        1        A  Yes
4        2        B   No
5        2        B   No
6        3      IOU   No
7        3      IOU   No
8        3      IOU   No
9        4        C  Yes
10       4      IOU  Yes
</code>```

Title: Python: How to label this dataset

Body:
Hi I have df like this:

df = pd.DataFrame({'CaseNo':[1,1,1,1,2,2,3,3,3,4,4],
                   'Category':['A','A','IOU','A','B','B','IOU','IOU','IOU','C','IOU']})

I'd like to label CaseNo col based on this condition:

For each CaseNo, if there is an occurrence of value 'IOU' in Category column with any values (except 'IOU') preceding it - label 'YES', else label 'NO'.

How can I do this in Python? Expected outcome:

Body:
Let us try transform with first and any

g=df.Category.eq('IOU').groupby(df['CaseNo'])
m=g.transform('any') & ~g.transform('first')
df['New']=m.map({True:'Yes',False:'No'})
df
Out[24]:
    CaseNo Category  New
0        1        A  Yes
1        1        A  Yes
2        1      IOU  Yes
3        1        A  Yes
4        2        B   No
5        2        B   No
6        3      IOU   No
7        3      IOU   No
8        3      IOU   No
9        4        C  Yes
10       4      IOU  Yes


问:
java google drive api V3 MultiPart & Resumable Upload
I need help in writing multipart & resumable upload of large files (>5MB) so far I have only been able to start an multiupload upload but I don't know how to resume it either when the user pauses it or during network failures.

By "Resuming" I mean I don't know how to

1) get the total bytes already uploaded to the drive

2) how to use that value in the Content-Range Header

3) how to even pause this upload by user interaction[executeAsInputStream() Maybe?]

This is what I have done so far. I need the code to resume from where it stopped  uploading even if I were to forcefully stop the application and restart it

```<code>   Drive service = GDrive.getService(); //Drive Specific Initialization Copied From QuickStart But with DriveScopes.FILES

   File fileMetadata = new File();
   fileMetadata.setName("Video.mp4"); //Video File
   fileMetadata.setMimeType("application/vnd.google-apps.video");

   java.io.File filePath = new java.io.File("E:\\large-file-60MB.mp4");//Large File Of 60 Mega Bytes
   FileContent mediaContent = new FileContent("video/mp4",filePath);

   Drive.Files.Create create=service.files().create(fileMetadata,mediaContent);

   MediaHttpUploader uploader=create.getMediaHttpUploader();
   uploader.setDirectUploadEnabled(false);                       //Use Resumable MultiPart Upload Protocol
   uploader.setChunkSize(2*MediaHttpUploader.MINIMUM_CHUNK_SIZE); //Chunks Of Bytes To Upload With Each Request

  // HttpHeaders headers=new HttpHeaders();
  // headers.put("Content-Range",?);          //This is not actual code which I used here but after reading the drive docs they talk about this header and I am not sure how or when to use it
  // uploader.setInitiationHeaders(headers);

   uploader.setProgressListener((uploading)->
   {
    switch (uploading.getUploadState())
    {
      case INITIATION_STARTED:System.out.println("Initiation has started!");
      break;
      case INITIATION_COMPLETE:System.out.println("Initiation is complete!");
      break;
      case MEDIA_IN_PROGRESS:
      System.out.println("Progress="+uploading.getProgress());
      System.out.println("Bytes="+uploading.getNumBytesUploaded());
      break;
      case MEDIA_COMPLETE:System.out.println("Upload is complete!");
    }
   });

   create.execute();
</code>```

答:
While answering multiple questions in one answer isn't normally appropriate for Stack Overflow, it seems that these are all closely linked and so will give an overview of resumable uploads and in doing so attempt to address your three points:

How does one get total bytes already uploaded to Drive

How to use the value in the Content-Range Header

How to pause a resumable upload

From Google's documentation on Direct and Resumable Media Uploads on ther Java API Client Library documentation:

Implementation details

The main classes of interest are MediaHttpUploader and MediaHttpProgressListener.

If methods in the service-specific generated libraries contain the mediaUpload parameter in the Discovery document, then a convenience method is created for these methods that takes an InputStreamContent as a parameter.

For example, the insert method of the Drive API supports mediaUpload, and you can use the following code to upload a file:

class CustomProgressListener implements MediaHttpUploaderProgressListener {
  public void progressChanged(MediaHttpUploader uploader) throws IOException {
    switch (uploader.getUploadState()) {
      case INITIATION_STARTED:
        System.out.println("Initiation has started!");
        break;
      case INITIATION_COMPLETE:
        System.out.println("Initiation is complete!");
        break;
      case MEDIA_IN_PROGRESS:
        System.out.println(uploader.getProgress());
        break;
      case MEDIA_COMPLETE:
        System.out.println("Upload is complete!");
    }
  }
}

File mediaFile = new File("/tmp/driveFile.jpg");
InputStreamContent mediaContent =
    new InputStreamContent("image/jpeg",
        new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());

Drive.Files.Insert request = drive.files().insert(fileMetadata, mediaContent);
request.getMediaHttpUploader().setProgressListener(new CustomProgressListener());
request.execute();
```
<p>These classes however abstract away things like the location URI which is returned when creating the resumable upload, so if you want to be able to do this then you will need to follow the resumable upload initiation steps as documented here. This is all manually done however rather than directly using the Google Drive API Client Library.</p>
<p>To answer the first point, how you store how many bytes have been uploaded is up to you. Rather than thinking <em>"how much is already on Drive"</em>, think <em>"how much have I already uploaded?"</em>.</p>
<p>You can store this as a vairable locally if you so desire, as it will be a multiple of your chunk size (<code>2 * MediaHttpUploader.MINIMUM_CHUNK_SIZE</code> in your case) and should be easy to track.</p>
<p>The thing is, this isn't actually needed. You can just use a wildcard to indicate that the current position of your file is unknown, as per the documentation (emphasis my own):</p>
<blockquote>
<p>If an upload request is terminated before a response, or if you receive a 503 Service Unavailable response, then you need to resume the interrupted upload.</p>
<p>To request the upload status, create an empty <code>PUT</code> request to the resumable session URI.</p>
<p><em><strong>Add a <code>Content-Range</code> header to indicate that the current position in the file is unknown. For example, set the <code>Content-Range</code> to <code>*/2000000</code> if your total file length is 2,000,000 bytes.</strong></em> If you don't know the full size of the file, set the <code>Content-Range</code> to <code>*/*</code>.</p>
</blockquote>
<p>If you do want to keep track of the bytes, you can specify it in your <code>Content-Range</code> header as</p>
```Content-Range: bytes_so_far/total_bytes
```
<h3>Steps:</h3>
<p>To initialise the resumable upload, you need to make a <code>POST</code> request to the <code>/upload</code> endpoint of the Drive API. You do not need to use the Drive API client library for this (and actually if you want to get the resumable session URI, you can't as the client library doesn't give you this).</p>
<p>Assuming you have your credential definition from:</p>
```GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(...);
```
<p>Then make the <code>POST</code> request containing the file metadata:</p>
```URL requestUrl = new URL("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");

String requestBody = "{\"name\": \"fileName\"}";

HttpURLConnection request = (HttpURLConnection) requestUrl.openConnection();

request.setRequestMethod("POST");
request.setDoInput(true);
request.setDoOutput(true);
request.setRequestProperty("Authorization", "Bearer " + credential.getToken());
request.setRequestProperty("X-Upload-Content-Type", "file/mimetype");
request.setRequestProperty("X-Upload-Content-Length", number_of_bytes_of_your_file);
request.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
request.setRequestProperty("Content-Length", String.format(Locale.ENGLISH, "%d", requestBody.getBytes().length));

OutputStream outputStream = request.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.close();

request.connect();
```
<p>The session URI - where to call to resume in case you need to - is returned in the headers of the response from the API. After connecting you can get this URI from the response:</p>
```if (request.getResponseCode() == HttpURLConnection.HTTP_OK) {
    URL sessionUri = new URL(request.getHeaderField("location"));
}
```
<p>Now you have the Session URI - with this you can upload chunks of file to Drive as you please. You now need to use this URI as the upload point for successive uploads.</p>
<p>Remember though: <strong>A resumable session URI expires after one week.</strong></p>
<h3>How to Pause a Resumable Upload:</h3>
<p>This in reality is down to how you wish to implement this. You could break out a loop for example or have a giant <code>PAUSE THIS UPLOAD</code> button in a GUI which toggles whether the next section of the upload continues or not.</p>
<p>The thing to remember is when uploading the file contents, the request made has to be done with <code>HTTP PUT</code> rather than <code>POST</code>. Following on from the previous section:</p>
<pre class="lang-java prettyprint-override"><code>// set these variables:
long beginningOfChunk = 0;
long chunkSize = 2 * MediaHttpUploader.MINIMUM_CHUNK_SIZE;
int chunksUploaded = 0;

// Here starts the upload chunk code:
HttpURLConnection request = (HttpURLConnection) sessionUri.openConnection();

request.setRequestMethod("PUT");
request.setDoOutput(true);
// change your timeout as you desire here:
request.setConnectTimeout(30000);
request.setRequestProperty("Content-Type", "file/mimetype");

long bytesUploadedSoFar = chunksUploaded * chunkSize;

if (beginningOfChunk + chunkSize > number_of_bytes_of_your_file) {
    chunkSize = (int) number_of_bytes_of_your_file - beginningOfChunk;
}

request.setRequestProperty("Content-Length", String.format(Locale.ENGLISH, "%d", chunkSize));
request.setRequestProperty("Content-Range", "bytes " + beginningOfChunk + "-" + (beginningOfChunk + chunkSize - 1) + "/" + number_of_bytes_of_your_file);

byte[] buffer = new byte[(int) chunksize];
FileInputStream fileInputStream = new FileInputStream(yourFile);
fileInputStream.getChannel().position(beginningOfChunk);
fileInputStream.close();

OutputStream outputStream = request.getOutputStream();
outputStream.write(buffer);
outputStream.close();
request.connect();

chunksUploaded += 1;

// End of upload chunk section
</code>```

You can then call the upload chunk code on repeat; in a loop, as a function; how you like. As it is a distinct code block, you can call it as you like and therefore implement some way of pausing the upload (through breaks, sleeps, waits, etc).

Just remember: you will need to save the session URI in order to resume.

Update:

It seems that using the Drive V3 API directly to make resumable uploads isn't something yet possible. The Java Client Library documentation alludes to this when discussing when to use Drive: create vs the non service-specific libraries:

...the insert method of the Drive API supports mediaUpload, and you can use the following code to upload a file:

```<code></code>```

code block

```<code>You can also use the resumable media upload feature without the service-specific generated libraries.
</code>```

Feature Request:

You can however let Google know that this is a feature that is important for the Drive API directly rather than the requirement to use the non-service specific library. Google's Issue Tracker is a place for developers to report issues and make feature requests for their development services. The page to file a Feature Request for the Drive API is here.

Note of discrepancy: what was called Drive.Files.Insert in Drive API V2 was changed to Drive.Files.Create in Drive API V3.

References:

Java Quickstart | Google Drive API | Google Developers

Drive.Files.Create (Drive API v3 (Rev. 197) 1.25.0)

Create and populate folders | Google Drive API | Google Developers

Upload file data | Google Drive API | Google Developers

Files: create | Google Drive API | Google Developers

Direct and Resumable Media Uploads | API Client Library for Java

Related Questions:

Google Drive api Java - is my large multipart upload complete?

Setting uploadType in Google Drive Java API

Resumable upload in Drive Rest API V3

Google Drive API - Drive.Files class has no insert () method

Body:
I need help in writing multipart & resumable upload of large files (>5MB) so far I have only been able to start an multiupload upload but I don't know how to resume it either when the user pauses it or during network failures.

By "Resuming" I mean I don't know how to

1) get the total bytes already uploaded to the drive

2) how to use that value in the Content-Range Header

3) how to even pause this upload by user interaction[executeAsInputStream() Maybe?]

This is what I have done so far. I need the code to resume from where it stopped  uploading even if I were to forcefully stop the application and restart it

   Drive service = GDrive.getService(); //Drive Specific Initialization Copied From QuickStart But with DriveScopes.FILES

   File fileMetadata = new File();
   fileMetadata.setName("Video.mp4"); //Video File
   fileMetadata.setMimeType("application/vnd.google-apps.video");

   java.io.File filePath = new java.io.File("E:\\large-file-60MB.mp4");//Large File Of 60 Mega Bytes
   FileContent mediaContent = new FileContent("video/mp4",filePath);

   Drive.Files.Create create=service.files().create(fileMetadata,mediaContent);

   MediaHttpUploader uploader=create.getMediaHttpUploader();
   uploader.setDirectUploadEnabled(false);                       //Use Resumable MultiPart Upload Protocol
   uploader.setChunkSize(2*MediaHttpUploader.MINIMUM_CHUNK_SIZE); //Chunks Of Bytes To Upload With Each Request

  // HttpHeaders headers=new HttpHeaders();
  // headers.put("Content-Range",?);          //This is not actual code which I used here but after reading the drive docs they talk about this header and I am not sure how or when to use it
  // uploader.setInitiationHeaders(headers);

   uploader.setProgressListener((uploading)->
   {
    switch (uploading.getUploadState())
    {
      case INITIATION_STARTED:System.out.println("Initiation has started!");
      break;
      case INITIATION_COMPLETE:System.out.println("Initiation is complete!");
      break;
      case MEDIA_IN_PROGRESS:
      System.out.println("Progress="+uploading.getProgress());
      System.out.println("Bytes="+uploading.getNumBytesUploaded());
      break;
      case MEDIA_COMPLETE:System.out.println("Upload is complete!");
    }
   });

   create.execute();

Body:
While answering multiple questions in one answer isn't normally appropriate for Stack Overflow, it seems that these are all closely linked and so will give an overview of resumable uploads and in doing so attempt to address your three points:

How does one get total bytes already uploaded to Drive

How to use the value in the Content-Range Header

How to pause a resumable upload

From Google's documentation on Direct and Resumable Media Uploads on ther Java API Client Library documentation:

Implementation details

The main classes of interest are MediaHttpUploader and MediaHttpProgressListener.

If methods in the service-specific generated libraries contain the mediaUpload parameter in the Discovery document, then a convenience method is created for these methods that takes an InputStreamContent as a parameter.

For example, the insert method of the Drive API supports mediaUpload, and you can use the following code to upload a file:

class CustomProgressListener implements MediaHttpUploaderProgressListener {
  public void progressChanged(MediaHttpUploader uploader) throws IOException {
    switch (uploader.getUploadState()) {
      case INITIATION_STARTED:
        System.out.println("Initiation has started!");
        break;
      case INITIATION_COMPLETE:
        System.out.println("Initiation is complete!");
        break;
      case MEDIA_IN_PROGRESS:
        System.out.println(uploader.getProgress());
        break;
      case MEDIA_COMPLETE:
        System.out.println("Upload is complete!");
    }
  }
}

File mediaFile = new File("/tmp/driveFile.jpg");
InputStreamContent mediaContent =
    new InputStreamContent("image/jpeg",
        new BufferedInputStream(new FileInputStream(mediaFile)));
mediaContent.setLength(mediaFile.length());

Drive.Files.Insert request = drive.files().insert(fileMetadata, mediaContent);
request.getMediaHttpUploader().setProgressListener(new CustomProgressListener());
request.execute();

These classes however abstract away things like the location URI which is returned when creating the resumable upload, so if you want to be able to do this then you will need to follow the resumable upload initiation steps as documented here. This is all manually done however rather than directly using the Google Drive API Client Library.

To answer the first point, how you store how many bytes have been uploaded is up to you. Rather than thinking "how much is already on Drive", think "how much have I already uploaded?".

You can store this as a vairable locally if you so desire, as it will be a multiple of your chunk size (2 * MediaHttpUploader.MINIMUM_CHUNK_SIZE in your case) and should be easy to track.

The thing is, this isn't actually needed. You can just use a wildcard to indicate that the current position of your file is unknown, as per the documentation (emphasis my own):

If an upload request is terminated before a response, or if you receive a 503 Service Unavailable response, then you need to resume the interrupted upload.

To request the upload status, create an empty PUT request to the resumable session URI.

Add a Content-Range header to indicate that the current position in the file is unknown. For example, set the Content-Range to */2000000 if your total file length is 2,000,000 bytes. If you don't know the full size of the file, set the Content-Range to */*.

If you do want to keep track of the bytes, you can specify it in your Content-Range header as

Content-Range: bytes_so_far/total_bytes

Steps:

To initialise the resumable upload, you need to make a POST request to the /upload endpoint of the Drive API. You do not need to use the Drive API client library for this (and actually if you want to get the resumable session URI, you can't as the client library doesn't give you this).

Assuming you have your credential definition from:

GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(...);

Then make the POST request containing the file metadata:

URL requestUrl = new URL("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable");

String requestBody = "{\"name\": \"fileName\"}";

HttpURLConnection request = (HttpURLConnection) requestUrl.openConnection();

request.setRequestMethod("POST");
request.setDoInput(true);
request.setDoOutput(true);
request.setRequestProperty("Authorization", "Bearer " + credential.getToken());
request.setRequestProperty("X-Upload-Content-Type", "file/mimetype");
request.setRequestProperty("X-Upload-Content-Length", number_of_bytes_of_your_file);
request.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
request.setRequestProperty("Content-Length", String.format(Locale.ENGLISH, "%d", requestBody.getBytes().length));

OutputStream outputStream = request.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.close();

request.connect();

The session URI - where to call to resume in case you need to - is returned in the headers of the response from the API. After connecting you can get this URI from the response:

if (request.getResponseCode() == HttpURLConnection.HTTP_OK) {
    URL sessionUri = new URL(request.getHeaderField("location"));
}

Now you have the Session URI - with this you can upload chunks of file to Drive as you please. You now need to use this URI as the upload point for successive uploads.

Remember though: A resumable session URI expires after one week.

How to Pause a Resumable Upload:

This in reality is down to how you wish to implement this. You could break out a loop for example or have a giant PAUSE THIS UPLOAD button in a GUI which toggles whether the next section of the upload continues or not.

The thing to remember is when uploading the file contents, the request made has to be done with HTTP PUT rather than POST. Following on from the previous section:

// set these variables:
long beginningOfChunk = 0;
long chunkSize = 2 * MediaHttpUploader.MINIMUM_CHUNK_SIZE;
int chunksUploaded = 0;

// Here starts the upload chunk code:
HttpURLConnection request = (HttpURLConnection) sessionUri.openConnection();

request.setRequestMethod("PUT");
request.setDoOutput(true);
// change your timeout as you desire here:
request.setConnectTimeout(30000);
request.setRequestProperty("Content-Type", "file/mimetype");

long bytesUploadedSoFar = chunksUploaded * chunkSize;

if (beginningOfChunk + chunkSize > number_of_bytes_of_your_file) {
    chunkSize = (int) number_of_bytes_of_your_file - beginningOfChunk;
}

request.setRequestProperty("Content-Length", String.format(Locale.ENGLISH, "%d", chunkSize));
request.setRequestProperty("Content-Range", "bytes " + beginningOfChunk + "-" + (beginningOfChunk + chunkSize - 1) + "/" + number_of_bytes_of_your_file);

byte[] buffer = new byte[(int) chunksize];
FileInputStream fileInputStream = new FileInputStream(yourFile);
fileInputStream.getChannel().position(beginningOfChunk);
fileInputStream.close();

OutputStream outputStream = request.getOutputStream();
outputStream.write(buffer);
outputStream.close();
request.connect();

chunksUploaded += 1;

// End of upload chunk section

You can then call the upload chunk code on repeat; in a loop, as a function; how you like. As it is a distinct code block, you can call it as you like and therefore implement some way of pausing the upload (through breaks, sleeps, waits, etc).

Just remember: you will need to save the session URI in order to resume.

Update:

It seems that using the Drive V3 API directly to make resumable uploads isn't something yet possible. The Java Client Library documentation alludes to this when discussing when to use Drive: create vs the non service-specific libraries:

...the insert method of the Drive API supports mediaUpload, and you can use the following code to upload a file:

code block

You can also use the resumable media upload feature without the service-specific generated libraries.

Feature Request:

You can however let Google know that this is a feature that is important for the Drive API directly rather than the requirement to use the non-service specific library. Google's Issue Tracker is a place for developers to report issues and make feature requests for their development services. The page to file a Feature Request for the Drive API is here.

Note of discrepancy: what was called Drive.Files.Insert in Drive API V2 was changed to Drive.Files.Create in Drive API V3.

References:

Java Quickstart | Google Drive API | Google Developers

Drive.Files.Create (Drive API v3 (Rev. 197) 1.25.0)

Create and populate folders | Google Drive API | Google Developers

Upload file data | Google Drive API | Google Developers

Files: create | Google Drive API | Google Developers

Direct and Resumable Media Uploads | API Client Library for Java

Related Questions:

Google Drive api Java - is my large multipart upload complete?

Setting uploadType in Google Drive Java API

Resumable upload in Drive Rest API V3

Google Drive API - Drive.Files class has no insert () method


问:
Changing the time and date in Xcode simulator
How to change the time in the iPhone simulator ? I want the other apps on my phone to see a different time than the current one. </p>

答:
Old question, modern answer:

With Xcode 11, Apple shipped new features for the simctl tool, which allows you to have a bit more control over what the simulators look like by overriding status bar values.

Finding the correct device

The command xcrun simctl list lists the currently installed simulators and gives their status:

```<code>% xcrun simctl list
== Device Types ==
<list of device types>

== Runtimes ==
<list of runtimes>

== Devices ==
-- iOS 13.5 --
    iPhone 11 (A2A694CF-8DA3-4371-AD2D-A2592A5C770C) (Shutdown)
    iPhone 11 Pro (F36583E8-6833-4526-8622-CE24022BE876) (Booted)
    iPhone 11 Pro Max (82029941-193B-423E-BE89-DD3E1C0B12E6) (Shutdown)
</code>```

The output of this command is very long so NSHipster was nice enough to provide a command that prints the UDID of the currently booted device in their simctl article:

```<code>$ xcrun simctl list devices | \
    grep "(Booted)"         | \
    grep -E -o -i "([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})"
9FED67A2-3D0A-4C9C-88AC-28A9CCA44C60
</code>```

Grab the appropriate device UDID and pass that into the following command to change the simulator's current time:

```<code>% xcrun simctl status_bar F36583E8-6833-4526-8622-CE24022BE876 override --time "9:41"
%
</code>```

Running xcrun simctl help status_bar will show a full range of options:

```<code>$ xcrun simctl help status_bar
Set or clear status bar overrides
Usage: simctl status_bar <device> [list | clear | override <override arguments>]

Supported Operations:
    list
    List existing overrides.

    clear
    Clear all existing status bar overrides.

    override <override arguments>
    Set status bar override values, according to these flags.
    You may specify any combination of these flags (at least one is required):

    --time <string>
         Set the date or time to a fixed value.
         If the string is a valid ISO date string it will also set the date on relevant devices.
    --dataNetwork <dataNetworkType>
         If specified must be one of 'wifi', '3g', '4g', 'lte', 'lte-a', or 'lte+'.
    --wifiMode <mode>
         If specified must be one of 'searching', 'failed', or 'active'.
    --wifiBars <int>
         If specified must be 0-3.
    --cellularMode <mode>
         If specified must be one of 'notSupported', 'searching', 'failed', or 'active'.
    --cellularBars <int>
         If specified must be 0-4.
    --operatorName <string>
         Set the cellular operator/carrier name. Use '' for the empty string.
    --batteryState <state>
         If specified must be one of 'charging', 'charged', or 'discharging'.
    --batteryLevel <int>
         If specified must be 0-100.
</code>```

Body:
Old question, modern answer:

With Xcode 11, Apple shipped new features for the simctl tool, which allows you to have a bit more control over what the simulators look like by overriding status bar values.

Finding the correct device

The command xcrun simctl list lists the currently installed simulators and gives their status:

% xcrun simctl list
== Device Types ==
<list of device types>

== Runtimes ==
<list of runtimes>

== Devices ==
-- iOS 13.5 --
    iPhone 11 (A2A694CF-8DA3-4371-AD2D-A2592A5C770C) (Shutdown)
    iPhone 11 Pro (F36583E8-6833-4526-8622-CE24022BE876) (Booted)
    iPhone 11 Pro Max (82029941-193B-423E-BE89-DD3E1C0B12E6) (Shutdown)

The output of this command is very long so NSHipster was nice enough to provide a command that prints the UDID of the currently booted device in their simctl article:

$ xcrun simctl list devices | \
    grep "(Booted)"         | \
    grep -E -o -i "([0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12})"
9FED67A2-3D0A-4C9C-88AC-28A9CCA44C60

Grab the appropriate device UDID and pass that into the following command to change the simulator's current time:

% xcrun simctl status_bar F36583E8-6833-4526-8622-CE24022BE876 override --time "9:41"
%

Running xcrun simctl help status_bar will show a full range of options:

$ xcrun simctl help status_bar
Set or clear status bar overrides
Usage: simctl status_bar <device> [list | clear | override <override arguments>]

Supported Operations:
    list
    List existing overrides.

    clear
    Clear all existing status bar overrides.

    override <override arguments>
    Set status bar override values, according to these flags.
    You may specify any combination of these flags (at least one is required):

    --time <string>
         Set the date or time to a fixed value.
         If the string is a valid ISO date string it will also set the date on relevant devices.
    --dataNetwork <dataNetworkType>
         If specified must be one of 'wifi', '3g', '4g', 'lte', 'lte-a', or 'lte+'.
    --wifiMode <mode>
         If specified must be one of 'searching', 'failed', or 'active'.
    --wifiBars <int>
         If specified must be 0-3.
    --cellularMode <mode>
         If specified must be one of 'notSupported', 'searching', 'failed', or 'active'.
    --cellularBars <int>
         If specified must be 0-4.
    --operatorName <string>
         Set the cellular operator/carrier name. Use '' for the empty string.
    --batteryState <state>
         If specified must be one of 'charging', 'charged', or 'discharging'.
    --batteryLevel <int>
         If specified must be 0-100.


问:
Unable to resolve module 'react-native-vector-icons/AntDesign''
I am facing following issue when import this:

import Icon from 'react-native-vector-icons/AntDesign';

Error:

error: bundling failed: Error: Unable to resolve module react-native-vector-icons/AntDesign from /Desktop/development/cbcvp-rn/cbcvp/node_modules/react-native-elements/src/helpers/getIconType.js: Module react-native-vector-icons/AntDesign does not exist in the Haste module map

This might be related to https://github.com/facebook/react-native/issues/4968
To resolve try the following:
  1. Clear watchman watches: watchman watch-del-all.
  2. Delete the node_modules folder: rm -rf node_modules && npm install.
  3. Reset Metro Bundler cache: rm -rf /tmp/metro-bundler-cache-* or npm start -- --reset-cache.  4. Remove haste cache: rm -rf /tmp/haste-map-react-native-packager-*.
    at ModuleResolver.resolveDependency (/Users/amit/Desktop/development/cbcvp-rn/cbcvp/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:161:1460)
    at ResolutionRequest.resolveDependency (/Users/amit/Desktop/development/cbcvp-rn/cbcvp/node_modules/metro/src/node-haste/DependencyGraph/ResolutionRequest.js:91:16)
    at DependencyGraph.resolveDependency (/Users/amit/Desktop/development/cbcvp-rn/cbcvp/node_modules/metro/src/node-haste/DependencyGraph.js:272:4579)
    at dependencies.map.relativePath (/Users/amit/Desktop/development/cbcvp-rn/cbcvp/node_modules/metro/src/DeltaBundler/traverseDependencies.js:376:19)
    at Array.map ()
    at resolveDependencies (/Users/amit/Desktop/development/cbcvp-rn/cbcvp/node_modules/metro/src/DeltaBundler/traverseDependencies.js:374:16)
    at /Users/amit/Desktop/development/cbcvp-rn/cbcvp/node_modules/metro/src/DeltaBundler/traverseDependencies.js:212:33
    at Generator.next ()
    at step (/Users/amit/Desktop/development/cbcvp-rn/cbcvp/node_modules/metro/src/DeltaBundler/traverseDependencies.js:297:313)
    at /Users/amit/Desktop/development/cbcvp-rn/cbcvp/node_modules/metro/src/DeltaBundler/traverseDependencies.js:297:473
 BUNDLE  [ios, dev] ./index.js ▓▓▓▓▓▓░░░░░░░░░░ 38.0% (719/1166), failed.

how to fix this error anyone help me...

Thanks

答:
Run the below commands

```<code>npm i react-native-vector-icons
npx react-native link react-native-vector-icons
</code>```

Hope it helps.

Body:
Run the below commands

npm i react-native-vector-icons
npx react-native link react-native-vector-icons

Hope it helps.


问:
how to get a date from a date input using javascript
hello so i have a javascript function that takes two dates from two date inputs, compares them and returns a boolean value except it doesn't work

function checkdate() {

 var datefrom = new Date();
 var dateto = new Date();

 datefrom = getElementById("date_from").innerHTML;
 dateto = getElementById("date_to").innerHTML;

 if (datefrom > dateto) {
  alert("Dateto must be bigger than datefrom  ");

  return false;
 } else return true;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form onsubmit="return checkdate()" class="forms-sample" method="post"
   action="addstage.php">
   <div class="form-group row">
      <label for="exampleInputUsername2" class="col-sm-3 col-form-label">Date
      Début</label>
      <div class="col-sm-9">
         <input type="date" class="form-control"
            id="date_from" placeholder="Debut" name="datedebut"  required="required">
      </div>
   </div>
   <div class="form-group row">
      <label for="exampleInputEmail2" class="col-sm-3 col-form-label">Date
      Fin</label>
      <div class="col-sm-9">
         <input type="date" class="form-control"
            id="date_to" placeholder="Fin" name="datefin" required="required">
      </div>
   </div>
   <div class="form-check form-check-flat form-check-primary"></div>
   <button type="submit" class="btn btn-primary mr-2" value="addStage"
      name="action">Add</button>
</form></code>```

答:
You can't use getElementById as a static method. You have to call it on document:

```<code>datefrom= document.getElementById("date_from").innerHTML;
dateto= document.getElementById("date_to").innerHTML;
</code>```

Body:
hello so i have a javascript function that takes two dates from two date inputs, compares them and returns a boolean value except it doesn't work

function checkdate() {

 var datefrom = new Date();
 var dateto = new Date();

 datefrom = getElementById("date_from").innerHTML;
 dateto = getElementById("date_to").innerHTML;

 if (datefrom > dateto) {
  alert("Dateto must be bigger than datefrom  ");

  return false;
 } else return true;

}

<form onsubmit="return checkdate()" class="forms-sample" method="post"
   action="addstage.php">

      Date
      Début

         <input type="date" class="form-control"
            id="date_from" placeholder="Debut" name="datedebut"  required="required">

      Date
      Fin

         <input type="date" class="form-control"
            id="date_to" placeholder="Fin" name="datefin" required="required">

   <button type="submit" class="btn btn-primary mr-2" value="addStage"
      name="action">Add</button>
</form>

Body:
You can't use getElementById as a static method. You have to call it on document:

datefrom= document.getElementById("date_from").innerHTML;
dateto= document.getElementById("date_to").innerHTML;


问:
convert a irregular time series of a data table with factors into a regular time series in R
I am trying to convert a irregular time series of a data table into a regular time series. My data looks like this

```<code>library(data.table)
dtRes <- data.table(time  = c(0.1, 0.8, 1, 2.3, 2.4, 4.8, 4.9),
                    abst  = c(1, 1, 1, 0, 0, 3, 3),
                    farbe = as.factor(c("keine", "keine", "keine", "keine", "keine", "rot", "blau")),
                    gier  = c(2.5, 2.5, 2.5, 0, 0, 3, 3),
                    goff  = as.factor(c("haus", "maus", "toll", "maus", NA, "maus", "maus")),
                    huft  = as.factor(c(NA, NA, NA, "wolle", "wolle", "holz", "holz")),
                    mode  = c(4, 4, 4, 2.5, NA, 3, 3))
</code>```

How is it possible to aggregate the observations in chunks by taking a chunk size of like 1 second? (with a variable number of rows - even 0 if there are no rows within a 1 second period) The result should be the mean for the numeric columns (NAs omitted) and for the factors a whole duplicated row if there is more than 1 unique value. If this is not possible for factors or doesn't make sense to you, it is also fine to just take the first value of the specific second in the factor column. This way it would be real regular time series without any duplicated times. If there is no value for an interval (like in the example for the 2nd second), the result is NA.

In the end the result can look like this (depends on duplicated rows or not):

with duplicates:

```<code>wiDups <- data.table(time  = c(1, 1, 2, 3, 4, 5, 5),
                     abst  = c(1, 1, NA, 1, NA, 5, 5),
                     farbe = as.factor(c("keine", "keine", NA, "keine", NA, "rot", "blau")),
                     gier  = c(2.5, 2.5, NA, 0, NA, 4.5, 4.5),
                     goff  = as.factor(c("haus", "maus", NA, "maus", NA, "maus", "maus")),
                     huft  = as.factor(c(NA, NA, NA, "wolle", NA, "holz", "holz")),
                     mode  = c(5, 5, NA, 2.5, NA, 4, 4))
</code>```

and without duplicates:

```<code>noDups <- data.table(time  = c(1, 2, 3, 4, 5),
                     abst  = c(1, NA, 1, NA, 5),
                     farbe = as.factor(c("keine", NA, "keine", NA, "rot")),
                     gier  = c(2.5, NA, 0, NA, 4.5),
                     goff  = as.factor(c("haus", NA, "maus", NA, "maus")),
                     huft  = as.factor(c(NA, NA, "wolle", NA, "holz")),
                     mode  = c(5, NA, 2.5, NA, 4))
</code>```

Is it better to convert it into a time series object?

答:
Here's a data.table answer:

Rounding up time to the nearest second:

```<code>> dtRes[,
+       lapply(.SD, function(z) {return(ifelse(is.factor(z), levels(z)[unique(z)[1]], mean(z, na.rm = T)))} ),
+       by = .(time = round(time, digits = 0))]
   time abst farbe gier goff  huft mode
1:    0    1 keine  2.5 haus  <NA>  4.0
2:    1    1 keine  2.5 maus  <NA>  4.0
3:    2    0 keine  0.0 maus wolle  2.5
4:    5    3   rot  3.0 maus  holz  3.0
</code>```

Using the ceiling function:

```<code>> dtRes[,
+       lapply(.SD, function(z) {return(ifelse(is.factor(z), levels(z)[unique(z)[1]], mean(z, na.rm = T)))} ),
+       by = .(time = ceiling(time))]
   time abst farbe gier goff  huft mode
1:    1    1 keine  2.5 haus  <NA>  4.0
2:    3    0 keine  0.0 maus wolle  2.5
3:    5    3   rot  3.0 maus  holz  3.0
</code>```

You can adjust the logic for returning the level based on what you want. Here I'm returning the level corresponding to the first non-unique value.

You may switch to using as.numeric in the ifelse statement - with similar results. I realized the data type for factor columns changes to character - if you need factor then you can set this specifically in a separate statement or use chaining.

```<code>dtRes[, lapply(.SD, ....), by = .(....)][, lapply(.SD, as.factor(...)), .SDcols = .( columns you want as factors), ]
</code>```

Body:
I am trying to convert a irregular time series of a data table into a regular time series. My data looks like this

library(data.table)
dtRes <- data.table(time  = c(0.1, 0.8, 1, 2.3, 2.4, 4.8, 4.9),
                    abst  = c(1, 1, 1, 0, 0, 3, 3),
                    farbe = as.factor(c("keine", "keine", "keine", "keine", "keine", "rot", "blau")),
                    gier  = c(2.5, 2.5, 2.5, 0, 0, 3, 3),
                    goff  = as.factor(c("haus", "maus", "toll", "maus", NA, "maus", "maus")),
                    huft  = as.factor(c(NA, NA, NA, "wolle", "wolle", "holz", "holz")),
                    mode  = c(4, 4, 4, 2.5, NA, 3, 3))

How is it possible to aggregate the observations in chunks by taking a chunk size of like 1 second? (with a variable number of rows - even 0 if there are no rows within a 1 second period) The result should be the mean for the numeric columns (NAs omitted) and for the factors a whole duplicated row if there is more than 1 unique value. If this is not possible for factors or doesn't make sense to you, it is also fine to just take the first value of the specific second in the factor column. This way it would be real regular time series without any duplicated times. If there is no value for an interval (like in the example for the 2nd second), the result is NA.

In the end the result can look like this (depends on duplicated rows or not):

with duplicates:

wiDups <- data.table(time  = c(1, 1, 2, 3, 4, 5, 5),
                     abst  = c(1, 1, NA, 1, NA, 5, 5),
                     farbe = as.factor(c("keine", "keine", NA, "keine", NA, "rot", "blau")),
                     gier  = c(2.5, 2.5, NA, 0, NA, 4.5, 4.5),
                     goff  = as.factor(c("haus", "maus", NA, "maus", NA, "maus", "maus")),
                     huft  = as.factor(c(NA, NA, NA, "wolle", NA, "holz", "holz")),
                     mode  = c(5, 5, NA, 2.5, NA, 4, 4))

and without duplicates:

noDups <- data.table(time  = c(1, 2, 3, 4, 5),
                     abst  = c(1, NA, 1, NA, 5),
                     farbe = as.factor(c("keine", NA, "keine", NA, "rot")),
                     gier  = c(2.5, NA, 0, NA, 4.5),
                     goff  = as.factor(c("haus", NA, "maus", NA, "maus")),
                     huft  = as.factor(c(NA, NA, "wolle", NA, "holz")),
                     mode  = c(5, NA, 2.5, NA, 4))

Is it better to convert it into a time series object?

Body:
Here's a data.table answer:

Rounding up time to the nearest second:

> dtRes[,
+       lapply(.SD, function(z) {return(ifelse(is.factor(z), levels(z)[unique(z)[1]], mean(z, na.rm = T)))} ),
+       by = .(time = round(time, digits = 0))]
   time abst farbe gier goff  huft mode
1:    0    1 keine  2.5 haus  <NA>  4.0
2:    1    1 keine  2.5 maus  <NA>  4.0
3:    2    0 keine  0.0 maus wolle  2.5
4:    5    3   rot  3.0 maus  holz  3.0

Using the ceiling function:

> dtRes[,
+       lapply(.SD, function(z) {return(ifelse(is.factor(z), levels(z)[unique(z)[1]], mean(z, na.rm = T)))} ),
+       by = .(time = ceiling(time))]
   time abst farbe gier goff  huft mode
1:    1    1 keine  2.5 haus  <NA>  4.0
2:    3    0 keine  0.0 maus wolle  2.5
3:    5    3   rot  3.0 maus  holz  3.0

You can adjust the logic for returning the level based on what you want. Here I'm returning the level corresponding to the first non-unique value.

You may switch to using as.numeric in the ifelse statement - with similar results. I realized the data type for factor columns changes to character - if you need factor then you can set this specifically in a separate statement or use chaining.

dtRes[, lapply(.SD, ....), by = .(....)][, lapply(.SD, as.factor(...)), .SDcols = .( columns you want as factors), ]


问:
How to stop and restart memcached server?
How to stop and restart memcached server 1.4.5 in linux OS from command line?</p>

答:
This worked for me:</p>

```<code>brew services stop memcached
</code>```

Body:
This worked for me:

brew services stop memcached


问:
How to get columns from joined table in django ORM
Keeping the problem simple :

Trying to Learn ORM.

And now I am stuck with simple left join issue .

So Lets start with basic model :

```<code>class City(models.Model):
    city=models.CharField(max_length=30)
    pin_code = models.IntegerField(null=False)

class State(models.Model)
    city = models.ForeignKey(City,on_delete=models.CASCADE)
    state = models.CharField(max_length=30)
    province = models.CharField(max_length=30)
</code>```

Now, I basically want to do :

```<code>select c.pin_code
from
  State s
left join City c on s.city = c.city;
</code>```

The equivalent of above in ORM that I could grasp from the mighty World Wide Web is :

```<code>State.objects.select_related('city')
</code>```

The above querset on looping through gives me only data from State Table .
I dont get 'pin_code' column .

I did all the search possible on the internet , but couldnt find any solution .

答:
You just access it by following relationship</p>

```<code>states = State.objects.select_related('city')

for state in states:
    state.city.pin_code
</code>```

Body:
Keeping the problem simple :

Trying to Learn ORM.

And now I am stuck with simple left join issue .

So Lets start with basic model :

class City(models.Model):
    city=models.CharField(max_length=30)
    pin_code = models.IntegerField(null=False)

class State(models.Model)
    city = models.ForeignKey(City,on_delete=models.CASCADE)
    state = models.CharField(max_length=30)
    province = models.CharField(max_length=30)

Now, I basically want to do :

select c.pin_code
from
  State s
left join City c on s.city = c.city;

The equivalent of above in ORM that I could grasp from the mighty World Wide Web is :

State.objects.select_related('city')

The above querset on looping through gives me only data from State Table .
I dont get 'pin_code' column .

I did all the search possible on the internet , but couldnt find any solution .

Body:
You just access it by following relationship

states = State.objects.select_related('city')

for state in states:
    state.city.pin_code


问:
Prepend string to list item and turn it into JSON in Ansible
I have a list of ports

ports:
  - 123
  - 456
  - 789
```

<p>that I like to turn into <code>containerPort</code> for usage in a Kubernetes deployment:</p>

```"container_ports": [
            {
                "containerPort": 123
            },
            {
                "containerPort": 456
            },
            {
                "containerPort": 789
            }
        ]
```

<p>The example above is created when I define <code>ports</code> as </p>

<pre class="lang-yaml prettyprint-override"><code>ports:
  - containerPort: 123
  - containerPort: 456
  - containerPort: 789
</code>```

However, I'd like to save the user some typing and add containerPort automatically. I am able to prepend it using

- name: Creating custom ports
  set_fact:
    container_ports: "{{ ports | map('regex_replace', '(^)', '- containerPort: \\1') | list }}"
  when: ports is defined

```

<p>This does only create </p>

```    ok: [localhost] => {
        "container_ports": [
            "- containerPort: 123",
            "- containerPort: 456",
            "- containerPort: 789"
        ]
    }
```

though, which is close, but not quite right.

答:
You can do this like so:

```<code>---
- hosts: localhost
  connection: local
  gather_facts: no
  vars:
    ports:
      - 123
      - 456

  tasks:
    - name: Creating custom ports
      set_fact:
        container_ports: '{{ ports | map("regex_replace", "^(.*)$", "containerPort: \1") | map("from_yaml") | list }}'
    - debug:
        var: container_ports
...
</code>```

The trick is to convert each item into a YAML hash and then convert that to a Python dict using from_yaml.

Debug output:

```<code>ok: [localhost] => {
    "container_ports": [
        {
            "containerPort": 123
        },
        {
            "containerPort": 456
        }
    ]
}
</code>```

Body:
I have a list of ports

ports:
  - 123
  - 456
  - 789

that I like to turn into containerPort for usage in a Kubernetes deployment:

"container_ports": [
            {
                "containerPort": 123
            },
            {
                "containerPort": 456
            },
            {
                "containerPort": 789
            }
        ]

The example above is created when I define ports as

ports:
  - containerPort: 123
  - containerPort: 456
  - containerPort: 789

However, I'd like to save the user some typing and add containerPort automatically. I am able to prepend it using

- name: Creating custom ports
  set_fact:
    container_ports: "{{ ports | map('regex_replace', '(^)', '- containerPort: \\1') | list }}"
  when: ports is defined

This does only create

    ok: [localhost] => {
        "container_ports": [
            "- containerPort: 123",
            "- containerPort: 456",
            "- containerPort: 789"
        ]
    }

though, which is close, but not quite right.

Body:
You can do this like so:

---
- hosts: localhost
  connection: local
  gather_facts: no
  vars:
    ports:
      - 123
      - 456

  tasks:
    - name: Creating custom ports
      set_fact:
        container_ports: '{{ ports | map("regex_replace", "^(.*)$", "containerPort: \1") | map("from_yaml") | list }}'
    - debug:
        var: container_ports
...

The trick is to convert each item into a YAML hash and then convert that to a Python dict using from_yaml.

Debug output:

ok: [localhost] => {
    "container_ports": [
        {
            "containerPort": 123
        },
        {
            "containerPort": 456
        }
    ]
}