问:
Javascript regex selecting numbers that are not connected to letters
This is my current regex:

```<code>var re = '/\d+\s+[\d+a-z]+/gi';
</code>```

I'm trying to get my regex to select numbers before if there are there own and then any abc characters and numbers after a whitespace

This is my test string

```<code>part1 6

22 part2

part3 8
</code>```

At the moment its selecting the following

```<code>1 : 6

22 part2

3 8
</code>```

But I just want to be selecting this

```<code>22 part2
</code>```

So i'm only wanting to select this if the number is on its own.

Any help thanks ?

答:
you can try this regex </p>

```<code>regex : /^\d+\s[a-zA-Z0-9]+\s\d+$;
</code>```

Body:
This is my current regex:

var re = '/\d+\s+[\d+a-z]+/gi';

I'm trying to get my regex to select numbers before if there are there own and then any abc characters and numbers after a whitespace

This is my test string

part1 6

22 part2

part3 8

At the moment its selecting the following

1 : 6

22 part2

3 8

But I just want to be selecting this

22 part2

So i'm only wanting to select this if the number is on its own.

Any help thanks ?

Body:
you can try this regex

regex : /^\d+\s[a-zA-Z0-9]+\s\d+$;


来源: stackexchange

问:
Jenkins pipeline share information between jobs
We are trying to define a set of jobs on Jenkins that will do really specific actions. JobA1 will build maven project, while JobA2 will build .NET code, JobB will upload it to Artifactory, JobC will download it from Artifactory and JobD will deploy it.
Every job will have a set of parameters so we can reuse the same job for any product (around 100).

The idea behind this is to create black boxes, I call a job with some input and I get always some output, whatever happens between is something that I don't care. On the other side, this allows us to improve each job separately, adding the required complexity, and instantly all products will get benefit.

We want to use Jenkins Pipeline to orchestrate the execution of actions. We are going to have a pipeline per environment/usage.

PipelineA will call JobA1, then JobB to upload to artifactory.

PipelineB will download package JobC and then deploy to staging.

PipelineC will download package JobC and then deploy to production based on some internal validations.

I have tried to get some variables from JobA1 (POM basic stuff such as ArtifactID or Version) injected to JobB but the information seems not to be transfered.
Same happens while downloading files, I call JobC but the file is in the job workspace not available for any other and I'm afraid that"External Workspace Manager" plugin adds too much complexity.

Is there any way rather than share the workspace to achieve my purpose? I understand that share the workspace will make it impossible to run two pipelines at the same time
Am I following the right path or am I doing something weird?

答:
The first part of your question(to pass variables between jobs) please use the below command as a post build section:

```<code>post {
    always {
        build job:'/Folder/JobB',parameters: [string(name: 'BRANCH', value: "${params.BRANCH}")], propagate: false
    }
}
</code>```

The above post build action is for all build results. Similarly, the post build action could be triggered on the current build status. I have used the BRANCH parameter from current build(JobA) as a parameter to be consumed by 'JobB' (provide the exact location of the job). Please note that there should be a similar parameter defined in JobB.

Moreover, for sharing the workspace you can refer this link and share the workspace between the jobs.

ContentLicense: CC BY-SA 3.0

Body:
The first part of your question(to pass variables between jobs) please use the below command as a post build section:

post {
    always {
        build job:'/Folder/JobB',parameters: [string(name: 'BRANCH', value: "${params.BRANCH}")], propagate: false
    }
}

The above post build action is for all build results. Similarly, the post build action could be triggered on the current build status. I have used the BRANCH parameter from current build(JobA) as a parameter to be consumed by 'JobB' (provide the exact location of the job). Please note that there should be a similar parameter defined in JobB.

Moreover, for sharing the workspace you can refer this link and share the workspace between the jobs.


问:
Domino Xpage database building automation or continuous Integration using Jenkins with maven.
we are trying to build an automation building environment for the Domino xpage database, The approach is using the headless designer feature , there are some links which I have followed are

presentation on integration work flow

Demo Xpage project

After this I tried to build the project just using maven as the above demo project contains a pom.xml .
pom.xml code:

```<code> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <artifactId>test</artifactId>
    <groupId>Forum</groupId>
    <version>1.0.0</version>
    <packaging>domino-nsf</packaging>

    <properties>
                <ddehd.designerexec>${notes-designer}</ddehd.designerexec>
                <ddehd.notesdata>${notes-data}</ddehd.notesdata>
        <ddehd.targetdbname>forum1.nsf</ddehd.targetdbname>
        <ddehd.odpdirectory>${basedir}/forum</ddehd.odpdirectory>

    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.openntf.maven</groupId>
                <artifactId>headlessdesigner-maven-plugin</artifactId>
                <version>1.3.0</version>
                <extensions>true</extensions>
                <configuration>

                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

I have done setup in maven settings.xml for the path of designer.exe and notes data for the headless designer purpose.So that this path is used in pom.xml for the specific projects. till here all the concepts are very much clear.

setting.xml changes

```<code>  <profiles>
     <profile>
      <id>test</id>

  <properties>
    <notes-program>C:\Program Files (x86)\IBM\Notes</notes-program>
    <notes-designer>C:\Program Files (x86)\IBM\Notes\designer.exe</notes-designer>
    <notes-data>C:\Program Files (x86)\IBM\Notes\Data\</notes-data>
  </properties>

    </profile>
   </profiles>
 <activeProfiles>
    <activeProfile>test</activeProfile>
  </activeProfiles>
</code>```

Now I go the command line at the project path and enter 'mvn package' it works all as required. that is , it opens the designer , gets the ondisk project files (the current directory files of xpage project) and builds the new nsf ,

Till here all works perfect ,

But now when I am trying perform the same thing but just from jenkins by crating new Item with maven settings , The designer gets open but only seems in task manager , In this case there is no designer.exe command line opens at the build.

Jenkis tries to build the project till I manually end the designer.exe task from task manager.

I am just wondering is there any settings or permission access for the jenkins to work with headless designer ,

Any kind of suggestion would be helpful.

答:
Domino Designer needs to run as a regular user. It wouldn't run when started as a Windows service. Also make sure your projects are NOT somewhere in the Program Files(x86) directory structure.

The right place for data files (both the NSF and the On_disk_Project) is in [Users]\[account-name-of-user-you-used]\LocalData\IBM\Notes\data]

Basically where data directory in a shared client install (no designer, just client) would be too

Body:
we are trying to build an automation building environment for the Domino xpage database, The approach is using the headless designer feature , there are some links which I have followed are

presentation on integration work flow

Demo Xpage project

After this I tried to build the project just using maven as the above demo project contains a pom.xml .
pom.xml code:

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <artifactId>test</artifactId>
    <groupId>Forum</groupId>
    <version>1.0.0</version>
    <packaging>domino-nsf</packaging>

    <properties>
                <ddehd.designerexec>${notes-designer}</ddehd.designerexec>
                <ddehd.notesdata>${notes-data}</ddehd.notesdata>
        <ddehd.targetdbname>forum1.nsf</ddehd.targetdbname>
        <ddehd.odpdirectory>${basedir}/forum</ddehd.odpdirectory>

    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.openntf.maven</groupId>
                <artifactId>headlessdesigner-maven-plugin</artifactId>
                <version>1.3.0</version>
                <extensions>true</extensions>
                <configuration>

                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

I have done setup in maven settings.xml for the path of designer.exe and notes data for the headless designer purpose.So that this path is used in pom.xml for the specific projects. till here all the concepts are very much clear.

setting.xml changes

  <profiles>
     <profile>
      <id>test</id>

  <properties>
    <notes-program>C:\Program Files (x86)\IBM\Notes</notes-program>
    <notes-designer>C:\Program Files (x86)\IBM\Notes\designer.exe</notes-designer>
    <notes-data>C:\Program Files (x86)\IBM\Notes\Data\</notes-data>
  </properties>

    </profile>
   </profiles>
 <activeProfiles>
    <activeProfile>test</activeProfile>
  </activeProfiles>

Now I go the command line at the project path and enter 'mvn package' it works all as required. that is , it opens the designer , gets the ondisk project files (the current directory files of xpage project) and builds the new nsf ,

Till here all works perfect ,

But now when I am trying perform the same thing but just from jenkins by crating new Item with maven settings , The designer gets open but only seems in task manager , In this case there is no designer.exe command line opens at the build.

Jenkis tries to build the project till I manually end the designer.exe task from task manager.

I am just wondering is there any settings or permission access for the jenkins to work with headless designer ,

Any kind of suggestion would be helpful.


问:
java.util.zip.ZipException: error in opening zip file
I have a Jar file, which contains other nested Jars. When I invoke the new JarFile() constructor on this file, I get an exception which says:

java.util.zip.ZipException: error in opening zip file

When I manually unzip the contents of this Jar file and zip it up again, it works fine.

I only see this exception on WebSphere 6.1.0.7 and higher versions. The same thing works fine on tomcat and WebLogic.

When I use JarInputStream instead of JarFile, I am able to read the contents of the Jar file without any exceptions.

答:
I was getting exception

```<code>java.util.zip.ZipException: invalid entry CRC (expected 0x0 but got 0xdeadface)
    at java.util.zip.ZipInputStream.read(ZipInputStream.java:221)
    at java.util.zip.ZipInputStream.closeEntry(ZipInputStream.java:140)
    at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:118)
...
</code>```

when unzipping an archive in Java. The archive itself didn't seem corrupted as 7zip (and others) opened it without any problems or complaints about invalid CRC.

I switched to Apache Commons Compress for reading the zip-entries and that resolved the problem.

Body:
I was getting exception

java.util.zip.ZipException: invalid entry CRC (expected 0x0 but got 0xdeadface)
    at java.util.zip.ZipInputStream.read(ZipInputStream.java:221)
    at java.util.zip.ZipInputStream.closeEntry(ZipInputStream.java:140)
    at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:118)
...

when unzipping an archive in Java. The archive itself didn't seem corrupted as 7zip (and others) opened it without any problems or complaints about invalid CRC.

I switched to Apache Commons Compress for reading the zip-entries and that resolved the problem.


问:
What is Type & TypeToken?
I have the following method in my project

```<code> public void execute(final int apiId, final ResponseHandler handler, final Type type)
</code>```

and the type is determined using TypeToken as follows

```<code>final Type serviceErrorType = new TypeToken<>() {
    }.getType();
</code>```

I went through this link here but couldn't understand completely about Type and TypeToken

Can anyone please share a link or help understand these two concepts?

答:
From the link you provided:

Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.

Let's speak with example.

Assume you want to parse a JSON to Java class with Gson library.
Now, you have to specifically tell Gson, that:

I want this JSON to be translated to a List of User objects

How would you tell that to Gson? If it was only User, you could tell User.class. But it isn't possible to say List<User>.class

```<code>new Gson().fromJson(json, new TypeToken<List<User>>(){}.getType())
</code>```

But now you can specify precisely that Gson should convert it to a List of Users.

Should quote explanation from docs:

Represents a generic type T. Java doesn't yet provide a way to represent generic types, so this class does.

Have a look at this blog post for more details on the topic.

Title: What is Type & TypeToken?

Body:
I have the following method in my project

 public void execute(final int apiId, final ResponseHandler handler, final Type type)

and the type is determined using TypeToken as follows

final Type serviceErrorType = new TypeToken<>() {
    }.getType();

I went through this link here but couldn't understand completely about Type and TypeToken

Can anyone please share a link or help understand these two concepts?

Body:
From the link you provided:

Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.

Let's speak with example.

Assume you want to parse a JSON to Java class with Gson library.
Now, you have to specifically tell Gson, that:

I want this JSON to be translated to a List of User objects

How would you tell that to Gson? If it was only User, you could tell User.class. But it isn't possible to say List<User>.class

new Gson().fromJson(json, new TypeToken<List<User>>(){}.getType())

But now you can specify precisely that Gson should convert it to a List of Users.

Should quote explanation from docs:

Represents a generic type T. Java doesn't yet provide a way to represent generic types, so this class does.

Have a look at this blog post for more details on the topic.

ContentLicense: CC BY-SA 4.0


问:
onclick in javascript makes active in css
I have a little content slider in css and I have two little points that change the image when they are in hover mode.

My question is how can I make the slide stay active by onclick

At the moment, my script looks like this but I think there is a problem with the add:

```<code><script>
    function myFunction() {
        var button = document.getElementsByClassName("dia");
        button.classList.add('active');
    }
</code>```

thanks for helping

答:
You could use the jquery .addClass() function.

https://www.w3schools.com/jquery/html_addclass.asp

In your case:

```<code>function myFunction() {
  var button = document.getElementsByClassName("dia");
  button.addClass("active");
}
</code>```

Or now that you're using jquery:

```<code>function myFunction() {
  $('.dia').addClass("active");
}
</code>```

Body:
You could use the jquery .addClass() function.

https://www.w3schools.com/jquery/html_addclass.asp

In your case:

function myFunction() {
  var button = document.getElementsByClassName("dia");
  button.addClass("active");
}

Or now that you're using jquery:

function myFunction() {
  $('.dia').addClass("active");
}


问:
Unable to deploy WAR file in Wildfly Server - Scan found incompletely copied file content for deployment
I'm trying to deploy a WAR file, which I made in grails with the grails warcommand (55 MB), to a Wildfly 8 server. I use the scp command scp schedulingAPI-0.1.war user@xx.xx.xx.xx:/home/user/wildfly-8.0.0.CR1/standalone/deployments/ whereafter the fileschedulingAPI-0.1.war.isdeployingis present on the server. After a few minutes, the fileschedulingAPI-0.1.war.failed` appears on the server.

This is an output of my log file:

```<code>2014-04-02 15:15:04,581 INFO  [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) JBAS015009: Scan found incompletely copied file content for deployment /home/user/wildfly-8.0.0.CR1/standalone/deployments/schedulingAPI-0.1.war. Deployment changes will not be processed until all content is complete.
2014-04-02 15:37:04,566 INFO  [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 2) JBAS015009: Scan found incompletely copied file content for deployment /home/user/wildfly-8.0.0.CR1/standalone/deployments/schedulingAPI-0.1.war. Deployment changes will not be processed until all content is complete.
2014-04-02 15:53:15,600 INFO  [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 2) JBAS015009: Scan found incompletely copied file content for deployment /home/user/wildfly-8.0.0.CR1/standalone/deployments/schedulingAPI-0.1.war. Deployment changes will not be processed until all content is complete.
</code>```

I already tried the suggestion in this thread to add the attribute deployment-timeout="2400" to <deployment-scanner> in the /standalone/configuration/standalone.xml file but without success.

答:
I have experience this before when i try to send the war file directly to deployment over the network. You will have to restart the service if this happens.

Try and avoid this if you have a slow network. If you must, don't worry, just restart the service afterwards

Body:
I'm trying to deploy a WAR file, which I made in grails with the grails warcommand (55 MB), to a Wildfly 8 server. I use the scp command scp schedulingAPI-0.1.war user@xx.xx.xx.xx:/home/user/wildfly-8.0.0.CR1/standalone/deployments/ whereafter the fileschedulingAPI-0.1.war.isdeployingis present on the server. After a few minutes, the fileschedulingAPI-0.1.war.failed` appears on the server.

This is an output of my log file:

2014-04-02 15:15:04,581 INFO  [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) JBAS015009: Scan found incompletely copied file content for deployment /home/user/wildfly-8.0.0.CR1/standalone/deployments/schedulingAPI-0.1.war. Deployment changes will not be processed until all content is complete.
2014-04-02 15:37:04,566 INFO  [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 2) JBAS015009: Scan found incompletely copied file content for deployment /home/user/wildfly-8.0.0.CR1/standalone/deployments/schedulingAPI-0.1.war. Deployment changes will not be processed until all content is complete.
2014-04-02 15:53:15,600 INFO  [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 2) JBAS015009: Scan found incompletely copied file content for deployment /home/user/wildfly-8.0.0.CR1/standalone/deployments/schedulingAPI-0.1.war. Deployment changes will not be processed until all content is complete.

I already tried the suggestion in this thread to add the attribute deployment-timeout="2400" to <deployment-scanner> in the /standalone/configuration/standalone.xml file but without success.


问:
Function returning Variable in Batch File
I am trying to write a code which will create a folder tree depending on file name and then move it in respective folder last subfolder will be on Date.
Problem I am facing is Call :SubtractDate %Year% %Month% %Day% -10 Ret
here ret is not catching a passed value from function.

Code created so far::

```<code>@echo Off
SetLocal

set Path1= d:\A
Pushd %Path1%

for %%i in (*.*) do SET "FName=%%~ni"
For /F "Tokens=4-5 Delims=-" %%A In ("%FName%") Do (
Set "FoldOne=%%A"
Set "FoldTwo=%%B"
)

IF %FoldTwo% == ABC (
echo Daily
Call :GetDateTime Year Month Day
Call :SubtractDate %Year% %Month% %Day% -10 Ret
Echo %Year% %Month% %Day%
echo %Ret%
exit /b
)

if not exist %Path1%\"%FoldOne%"\"%FoldTwo%"\%Ret% (
  mkdir %Path1%\"%FoldOne%"\"%FoldTwo%"\%Ret% )
  move %Path1%\"%FName%".* %Path1%\"%FoldOne%"\"%FoldTwo%"\%Ret%\

Pushd d:\

GoTo :EOF

:SubtractDate Year Month Day <+/-Days> Ret
::Adapted from DosTips Functions::
@echo off & setlocal & set a=%4
set "yy=%~1"&set "mm=%~2"&set "dd=%~3"
set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
if %yy% LSS 100 set /a yy+=2000 &rem Adds 2000 to two digit years
set /a JD=dd-32075+1461*(yy+4800+(mm-14)/12)/4+367*(mm-2-(mm-14)/12*12)/12-3* ((yy+4900+(mm-14)/12)/100)/4
if %a:~0,1% equ + (set /a JD=%JD%+%a:~1%) else set /a JD=%JD%-%a:~1%
set /a L= %JD%+68569,     N= 4*L/146097, L= L-(146097*N+3)/4, I= 4000*    (L+1)/1461001
set /a L= L-1461*I/4+31, J= 80*L/2447,  K= L-2447*J/80,      L= J/11
set /a J= J+2-12*L,      I= 100*(N-49)+I+L
set /a YYYY=I, MM=100+J, DD=100+K
set MM=%MM:~-2,2% & set DD=%DD:~-2%
set ret=%DD: =%%MM: =%%YYYY: =%
endlocal & set %~5=%ret%
echo %ret%
exit /b

:GetDateTime Year Month Day Hour Minute Second
@echo off & setlocal
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
( ENDLOCAL
     IF "%~1" NEQ "" set "%~1=%YYYY%"
     IF "%~2" NEQ "" set "%~2=%MM%"
     IF "%~3" NEQ "" set "%~3=%DD%"
     IF "%~4" NEQ "" set "%~4=%HH%"
     IF "%~5" NEQ "" set "%~5=%Min%"
     IF "%~6" NEQ "" set "%~6=%Sec%"
)
exit /b
</code>```

答:
Based on the last reply I gave you, which you seem not to have really followed, you could try something like this:

@Echo Off
Set "Path1=D:\A"
Set "RelDays=-10"
Set "_="
If /I Not "%CD%"=="%Path1%" (Pushd "%Path1%" 2>Nul & Set "_=T") || Exit/B
For /F UseBackQ %%A In (
    `PowerShell "(Get-Date).AddDays(%RelDays%).ToString('ddMMyyy')"`
) Do Set "RDate=%%A"
For %%A In ("*-*-*-*-*.*") Do Call :Sub "%%A"
If Defined _ PopD
Timeout -1
GoTo :EOF

:Sub
For /F "Tokens=4-5Delims=-" %%A In ("%~n1") Do If Not "%%A"=="" (
    If "%%B"=="ABC" (If Not Exist "%%A\%%B\%RDate%\" MD "%%A\%%B\%RDate%"
        Move %1 "%%A\%%B\%RDate%"))
```

I used powershell to calculate the date instead of the function you had found.

Body:
I am trying to write a code which will create a folder tree depending on file name and then move it in respective folder last subfolder will be on Date.
Problem I am facing is Call :SubtractDate %Year% %Month% %Day% -10 Ret
here ret is not catching a passed value from function.

Code created so far::

@echo Off
SetLocal

set Path1= d:\A
Pushd %Path1%

for %%i in (*.*) do SET "FName=%%~ni"
For /F "Tokens=4-5 Delims=-" %%A In ("%FName%") Do (
Set "FoldOne=%%A"
Set "FoldTwo=%%B"
)

IF %FoldTwo% == ABC (
echo Daily
Call :GetDateTime Year Month Day
Call :SubtractDate %Year% %Month% %Day% -10 Ret
Echo %Year% %Month% %Day%
echo %Ret%
exit /b
)

if not exist %Path1%\"%FoldOne%"\"%FoldTwo%"\%Ret% (
  mkdir %Path1%\"%FoldOne%"\"%FoldTwo%"\%Ret% )
  move %Path1%\"%FName%".* %Path1%\"%FoldOne%"\"%FoldTwo%"\%Ret%\

Pushd d:\

GoTo :EOF

:SubtractDate Year Month Day <+/-Days> Ret
::Adapted from DosTips Functions::
@echo off & setlocal & set a=%4
set "yy=%~1"&set "mm=%~2"&set "dd=%~3"
set /a "yy=10000%yy% %%10000,mm=100%mm% %% 100,dd=100%dd% %% 100"
if %yy% LSS 100 set /a yy+=2000 &rem Adds 2000 to two digit years
set /a JD=dd-32075+1461*(yy+4800+(mm-14)/12)/4+367*(mm-2-(mm-14)/12*12)/12-3* ((yy+4900+(mm-14)/12)/100)/4
if %a:~0,1% equ + (set /a JD=%JD%+%a:~1%) else set /a JD=%JD%-%a:~1%
set /a L= %JD%+68569,     N= 4*L/146097, L= L-(146097*N+3)/4, I= 4000*    (L+1)/1461001
set /a L= L-1461*I/4+31, J= 80*L/2447,  K= L-2447*J/80,      L= J/11
set /a J= J+2-12*L,      I= 100*(N-49)+I+L
set /a YYYY=I, MM=100+J, DD=100+K
set MM=%MM:~-2,2% & set DD=%DD:~-2%
set ret=%DD: =%%MM: =%%YYYY: =%
endlocal & set %~5=%ret%
echo %ret%
exit /b

:GetDateTime Year Month Day Hour Minute Second
@echo off & setlocal
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
( ENDLOCAL
     IF "%~1" NEQ "" set "%~1=%YYYY%"
     IF "%~2" NEQ "" set "%~2=%MM%"
     IF "%~3" NEQ "" set "%~3=%DD%"
     IF "%~4" NEQ "" set "%~4=%HH%"
     IF "%~5" NEQ "" set "%~5=%Min%"
     IF "%~6" NEQ "" set "%~6=%Sec%"
)
exit /b

Body:
Based on the last reply I gave you, which you seem not to have really followed, you could try something like this:

@Echo Off
Set "Path1=D:\A"
Set "RelDays=-10"
Set "_="
If /I Not "%CD%"=="%Path1%" (Pushd "%Path1%" 2>Nul & Set "_=T") || Exit/B
For /F UseBackQ %%A In (
    `PowerShell "(Get-Date).AddDays(%RelDays%).ToString('ddMMyyy')"`
) Do Set "RDate=%%A"
For %%A In ("*-*-*-*-*.*") Do Call :Sub "%%A"
If Defined _ PopD
Timeout -1
GoTo :EOF

:Sub
For /F "Tokens=4-5Delims=-" %%A In ("%~n1") Do If Not "%%A"=="" (
    If "%%B"=="ABC" (If Not Exist "%%A\%%B\%RDate%\" MD "%%A\%%B\%RDate%"
        Move %1 "%%A\%%B\%RDate%"))

I used powershell to calculate the date instead of the function you had found.


问:
.net core testing dbsets
I´m preparing my test infrastructure, but i´m facing some problems with my test repository.

The real repository access EntityFramework DbSet, like this:

```<code>public class Repository<T>: IRepository<T> where T : ModelBase
{
    protected ApplicationDbContext db;
    private DbSet<T> dbSet;
    public Repository(ApplicationDbContext db)
    {
        this.db = db;
        dbSet = db.Set<T>();
    }

    public IQueryable<T> Where(Expression<Func<T, bool>> predicate)
    {
        return dbSet.Where(predicate).AsNoTracking();
    }

    ....
</code>```

My TestRepository uses List instead of DbSets:

```<code>public class TestRepository<T> : IRepository<T> where T : ModelBase
{
    private readonly List<T> dbSet;
    protected ApplicationDbContextFake db;

    public TestRepository(ApplicationDbContextFake db)
    {
        this.db = db;
        this.dbSet = db.Set<T>();
    }
</code>```

This db.Set<T>() returns a List

The problem occurs when testing my code and there are something like this:

```<code>public async Task DeleteAsync()
{
    var items = repository.Where(....);
    repository.RemoveRange(await items.ToListAsync());
</code>```

This code runs ok using Entity DbSets, but throws an exception when testing with my TestRepository:

The source IQueryable doesn't implement IAsyncEnumerable. Only sources that implement IAsyncEnumerable can be used for Entity Framework asynchronous operations.

Any suggestions to workaround this?

答:
If you are using EntityFramework Core (not EF6) - you may use in-memory implementation for your tests.

See docs for Microsoft.EntityFrameworkCore.InMemory provider.

Title: .net core testing dbsets

Body:
I´m preparing my test infrastructure, but i´m facing some problems with my test repository.

The real repository access EntityFramework DbSet, like this:

public class Repository<T>: IRepository<T> where T : ModelBase
{
    protected ApplicationDbContext db;
    private DbSet<T> dbSet;
    public Repository(ApplicationDbContext db)
    {
        this.db = db;
        dbSet = db.Set<T>();
    }

    public IQueryable<T> Where(Expression<Func<T, bool>> predicate)
    {
        return dbSet.Where(predicate).AsNoTracking();
    }

    ....

My TestRepository uses List instead of DbSets:

public class TestRepository<T> : IRepository<T> where T : ModelBase
{
    private readonly List<T> dbSet;
    protected ApplicationDbContextFake db;

    public TestRepository(ApplicationDbContextFake db)
    {
        this.db = db;
        this.dbSet = db.Set<T>();
    }

This db.Set<T>() returns a List

The problem occurs when testing my code and there are something like this:

public async Task DeleteAsync()
{
    var items = repository.Where(....);
    repository.RemoveRange(await items.ToListAsync());

This code runs ok using Entity DbSets, but throws an exception when testing with my TestRepository:

The source IQueryable doesn't implement IAsyncEnumerable. Only sources that implement IAsyncEnumerable can be used for Entity Framework asynchronous operations.

Any suggestions to workaround this?


问:
Android Vector Drawable crash
I use Vector Drawables. It works good on my several devices, but on my Sony with Android 5.0.2 I get at my application launch:

```<code>java.lang.ArrayIndexOutOfBoundsException: length=32; index=32
 at android.util.PathParser$PathDataNode.addCommand(PathParser.java:370)
 at android.util.PathParser$PathDataNode.nodesToPath(PathParser.java:260)
 at android.graphics.drawable.VectorDrawable$VPath.toPath(VectorDrawable.java:1265)
  at android.graphics.drawable.VectorDrawable$VPathRenderer.drawPath(VectorDrawable.java:950)
</code>```

Looks like I have some svgs converted to xml with unsupported tags for this device. But how to understand which ones and how to be sure that it will work on all other supported devices.

答:
In my xml were present <group></group> attributes.

After their removing problem was solved, also spent some time to understand where was the problem, and it was not by M and L letters (read more: https://developer.mozilla.org/en/docs/Web/SVG/Tutorial/Paths)

Title: Android Vector Drawable crash

Body:
I use Vector Drawables. It works good on my several devices, but on my Sony with Android 5.0.2 I get at my application launch:

java.lang.ArrayIndexOutOfBoundsException: length=32; index=32
 at android.util.PathParser$PathDataNode.addCommand(PathParser.java:370)
 at android.util.PathParser$PathDataNode.nodesToPath(PathParser.java:260)
 at android.graphics.drawable.VectorDrawable$VPath.toPath(VectorDrawable.java:1265)
  at android.graphics.drawable.VectorDrawable$VPathRenderer.drawPath(VectorDrawable.java:950)

Looks like I have some svgs converted to xml with unsupported tags for this device. But how to understand which ones and how to be sure that it will work on all other supported devices.


问:
How to define network interface
I'm developing Kaa. i don't understand this part:
$ sudo nano /etc/kaa-node/conf/kaa-node.properties
transport_public_interface=localhost=YOUR_PUBLIC_INTERFACE
the link is :http://kaaproject.github.io/kaa/docs/v0.10.0/Administration-guide/System-installation/Single-node-installation/

how to define YOUR_PUBLIC_INTERFACE ?

答: You should not define this as a variable. Just replace YOUR_PUBLIC_INTERFACE with the correct interface name.

Title: How to define network interface


问:
Java program on "friendly numbers "
I am working on a assignment about so called "friendly-numbers" with the following definition: An integer is said to be friendly if the leftmost digit is divisible by 1, the leftmost two digits are divisible by 2, and the leftmost three digits are divisible by 3, and so on. The n-digit itself is divisible by n.

Also it was given we need to call a method (as I did or at least tried to do in the code below). It should print whether a number is friendly or not. However, my program prints "The integer is not friendly." in both cases. From what I have tried, I know the counter does work. I just cannot find what I am missing or doing wrong. Help would be appreciated, and preferably with an adaptation of the code below, since that is what I came up with myself.

```<code>import java.util.Scanner;
public class A5E4 {

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter an integer: ");
        int friendlyNumber = in.nextInt();
        boolean result = isFriendly(friendlyNumber);
        if (result)
        {
            System.out.println("The integer is friendly");
        }
        else
        {
            System.out.println("The integer is not friendly");
        }
    }
    public static boolean isFriendly(int number)
    {
        int counter = 1;

        while (number / 10 >= 1)
        {
            counter ++;
            number = number / 10;
        }

        boolean check = true;

        for (int i = 1; i <= counter; i++)
        {

            if (number / Math.pow(10, (counter - i)) % i == 0 && check)
            {
                check = true;
            }
            else
            {
                check = false;
            }

        }
        return check;

    }
}
</code>```

答:
The first problem is that you are modifying the value of the number you are trying to check. So, if your method is called with 149, then after the while loop to count the digits, its value will be 1. So, you are always going to find that it is 'unfriendly'. Assuming you fix this so that number contains the number you are checking. Try this instead of your 'for' loop:

```<code>while ( counter && !( ( number % 10 / counter ) % counter ) )
{
    number = number / 10;
    counter--;
}
</code>```

It works by taking the last digit of your number using the modulus or remainder operator and then divides this by the digit position and checks that the remainder is zero. If all is good, it decrements the counter until it reaches zero, otherwise it terminates before counter is zero.

Title: Java program on "friendly numbers "

Body:
I am working on a assignment about so called "friendly-numbers" with the following definition: An integer is said to be friendly if the leftmost digit is divisible by 1, the leftmost two digits are divisible by 2, and the leftmost three digits are divisible by 3, and so on. The n-digit itself is divisible by n.

Also it was given we need to call a method (as I did or at least tried to do in the code below). It should print whether a number is friendly or not. However, my program prints "The integer is not friendly." in both cases. From what I have tried, I know the counter does work. I just cannot find what I am missing or doing wrong. Help would be appreciated, and preferably with an adaptation of the code below, since that is what I came up with myself.

import java.util.Scanner;
public class A5E4 {

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter an integer: ");
        int friendlyNumber = in.nextInt();
        boolean result = isFriendly(friendlyNumber);
        if (result)
        {
            System.out.println("The integer is friendly");
        }
        else
        {
            System.out.println("The integer is not friendly");
        }
    }
    public static boolean isFriendly(int number)
    {
        int counter = 1;

        while (number / 10 >= 1)
        {
            counter ++;
            number = number / 10;
        }

        boolean check = true;

        for (int i = 1; i <= counter; i++)
        {

            if (number / Math.pow(10, (counter - i)) % i == 0 && check)
            {
                check = true;
            }
            else
            {
                check = false;
            }

        }
        return check;

    }
}

Body:
The first problem is that you are modifying the value of the number you are trying to check. So, if your method is called with 149, then after the while loop to count the digits, its value will be 1. So, you are always going to find that it is 'unfriendly'. Assuming you fix this so that number contains the number you are checking. Try this instead of your 'for' loop:

while ( counter && !( ( number % 10 / counter ) % counter ) )
{
    number = number / 10;
    counter--;
}

It works by taking the last digit of your number using the modulus or remainder operator and then divides this by the digit position and checks that the remainder is zero. If all is good, it decrements the counter until it reaches zero, otherwise it terminates before counter is zero.


问:
Update table data from view in PostgreSQL/PostGIS
I am having an entity-relationship model in which I am trying to respect the normalization rules. But in order to work into QGIS through PostGIS and have only relevant data at the moment, I would like to work through some views, display these views into QGIS and possibly update the corresponding table according to the modifications made in the view.

For example I have three tables where cable is the one containing the datas I have to work with, modele_cable a reference table (weak entity) containing some informations which would fill the view, and type_cable a weak entity of modele_table, also containing some information relevant in the view. As such :

```<code>CREATE TABLE test.cable(
      id_cable serial NOT NULL,
      id_modele_cable integer,
      geom geometry(MultiLineString,2154),
      CONSTRAINT prk_constraint_cable PRIMARY KEY (id_cable),
      CONSTRAINT fk_cable_id_modele_cable FOREIGN KEY (id_modele_cable)
          REFERENCES test.modele_cable (id_modele_cable)
    );
    CREATE TABLE test.modele_cable(
      id_modele_cable serial NOT NULL,
      id_type_cable integer,
      CONSTRAINT prk_constraint_modele_cable PRIMARY KEY (id_modele_cable),
      CONSTRAINT fk_modele_cable_id_type_cable FOREIGN KEY (id_type_cable)
          REFERENCES test.type_cable (id_type_cable)
    );
    CREATE TABLE test.type_cable(
      id_type_cable serial NOT NULL,
      nb_fo integer,
      CONSTRAINT prk_constraint_type_cable PRIMARY KEY (id_type_cable)
    );
    CREATE VIEW public.cable_ok AS
     SELECT cable.id_cable,
        cable.designation,
        type_cable.nb_fo,
        cable.geom
       FROM test.cable
         LEFT JOIN test.modele_cable ON cable.id_modele_cable=modele_cable.id_modele_cable
         LEFT JOIN test.type_cable ON type_cable.id_type_cable=modele_cable.id_type_cable;
</code>```

I didn't find any information on how to do what I want, nor if it is even possible, and if not what could be a workaround. I tried to make a trigger which would detect the modification in the view in PostGIS, and update the table 'cable' accordingly, but I didn't manage to do so (I successfully only once created a trigger in another context before, and quite painfully). I also noticed that it is not possible to update a view manually inside the table of the view (which sounds logical since it is a view).

Does anyone have any clue, direction, help, experience that could help me solve this problem ?

UPDATE here is a trigger as I tried to implement it :

```<code>create or replace function tout.update_cable_view() returns trigger as
    $body$
    begin
    select modele_cable.id_modele_cable
    into cable.id_modele_cable
    from test.cable
    inner join test.modele_cable on cable.id_modele_cable=modele_cable.id_modele_cable
    inner join test.type_cable on modele_cable.id_type_cable=type_cable.id_type_cable,
    public.cable_ok
    where cable_ok.nb_fo=type_cable.nb_fo;
    return null;
    end;
    $body$
    language plpgsql;

    create trigger t_update_cable_view
    instead of insert or update on public.cable_ok
    for each row
    execute procedure tout.update_cable_view();
</code>```

UPDATE 2 here is a trigger function which should be working, but is not :

```<code>create or replace function tout.update_cable_view() returns trigger as
$body$
begin
update test.cable
set id_modele_cable = (select id_modele_cable from test.modele_cable
inner join test.type_cable on

modele_cable.id_type_cable=type_cable.id_type_cable
    where new.nb_fo=type_cable.nb_fo and old.id_cable=new.id_cable);
return new;
end;
$body$
language plpgsql;
</code>```

答:
I found another way of doing what I wanted using a rule. My guess is that PostgreSQL doesn't allow the saving of the view. With an INSTEAD rule it does not try to save the view, and instead update the original table, updating automatically the view then. Here is the piece of code, for an update :

```<code>create rule "_test_rule" as
on update to public.cable_ok
do instead update test.cable
set id_modele_cable = (select id_modele_cable from test.modele_cable
inner join test.type_cable on modele_cable.id_type_cable=type_cable.id_type_cable
where new.nb_fo=type_cable.nb_fo and new.id_cable=cable.id_cable)
where old.id_cable=cable.id_cable;
</code>```

Body:
I am having an entity-relationship model in which I am trying to respect the normalization rules. But in order to work into QGIS through PostGIS and have only relevant data at the moment, I would like to work through some views, display these views into QGIS and possibly update the corresponding table according to the modifications made in the view.

For example I have three tables where cable is the one containing the datas I have to work with, modele_cable a reference table (weak entity) containing some informations which would fill the view, and type_cable a weak entity of modele_table, also containing some information relevant in the view. As such :

CREATE TABLE test.cable(
      id_cable serial NOT NULL,
      id_modele_cable integer,
      geom geometry(MultiLineString,2154),
      CONSTRAINT prk_constraint_cable PRIMARY KEY (id_cable),
      CONSTRAINT fk_cable_id_modele_cable FOREIGN KEY (id_modele_cable)
          REFERENCES test.modele_cable (id_modele_cable)
    );
    CREATE TABLE test.modele_cable(
      id_modele_cable serial NOT NULL,
      id_type_cable integer,
      CONSTRAINT prk_constraint_modele_cable PRIMARY KEY (id_modele_cable),
      CONSTRAINT fk_modele_cable_id_type_cable FOREIGN KEY (id_type_cable)
          REFERENCES test.type_cable (id_type_cable)
    );
    CREATE TABLE test.type_cable(
      id_type_cable serial NOT NULL,
      nb_fo integer,
      CONSTRAINT prk_constraint_type_cable PRIMARY KEY (id_type_cable)
    );
    CREATE VIEW public.cable_ok AS
     SELECT cable.id_cable,
        cable.designation,
        type_cable.nb_fo,
        cable.geom
       FROM test.cable
         LEFT JOIN test.modele_cable ON cable.id_modele_cable=modele_cable.id_modele_cable
         LEFT JOIN test.type_cable ON type_cable.id_type_cable=modele_cable.id_type_cable;

I didn't find any information on how to do what I want, nor if it is even possible, and if not what could be a workaround. I tried to make a trigger which would detect the modification in the view in PostGIS, and update the table 'cable' accordingly, but I didn't manage to do so (I successfully only once created a trigger in another context before, and quite painfully). I also noticed that it is not possible to update a view manually inside the table of the view (which sounds logical since it is a view).

Does anyone have any clue, direction, help, experience that could help me solve this problem ?

UPDATE here is a trigger as I tried to implement it :

create or replace function tout.update_cable_view() returns trigger as
    $body$
    begin
    select modele_cable.id_modele_cable
    into cable.id_modele_cable
    from test.cable
    inner join test.modele_cable on cable.id_modele_cable=modele_cable.id_modele_cable
    inner join test.type_cable on modele_cable.id_type_cable=type_cable.id_type_cable,
    public.cable_ok
    where cable_ok.nb_fo=type_cable.nb_fo;
    return null;
    end;
    $body$
    language plpgsql;

    create trigger t_update_cable_view
    instead of insert or update on public.cable_ok
    for each row
    execute procedure tout.update_cable_view();

UPDATE 2 here is a trigger function which should be working, but is not :

create or replace function tout.update_cable_view() returns trigger as
$body$
begin
update test.cable
set id_modele_cable = (select id_modele_cable from test.modele_cable
inner join test.type_cable on

modele_cable.id_type_cable=type_cable.id_type_cable
    where new.nb_fo=type_cable.nb_fo and old.id_cable=new.id_cable);
return new;
end;
$body$
language plpgsql;

Body:
I found another way of doing what I wanted using a rule. My guess is that PostgreSQL doesn't allow the saving of the view. With an INSTEAD rule it does not try to save the view, and instead update the original table, updating automatically the view then. Here is the piece of code, for an update :

create rule "_test_rule" as
on update to public.cable_ok
do instead update test.cable
set id_modele_cable = (select id_modele_cable from test.modele_cable
inner join test.type_cable on modele_cable.id_type_cable=type_cable.id_type_cable
where new.nb_fo=type_cable.nb_fo and new.id_cable=cable.id_cable)
where old.id_cable=cable.id_cable;


问:
Git: Converging branches to a single commit object
Say I currently have the following in git:

```<code>master
  O
  |
  o  <-- commit objects on master branch
  |
  o -- O  <-- new branch: featureX
       |
       o  <-- commit objects on the featureX
       |
       o
</code>```

So I started with the master branch and after two commits, I branched to featureX.

Now, after 2 commits on featureX, I want to converge it with master and continue work on master from the last commit on featureX.

This means that I don't want to merge the files between master and featureX but transferring all the commits done on featureX to master and continue working on master from the last commit that was done on featureX.

Basically, something like this:

```<code>master
  O
  |
  o  <-- commit objects on master branch
  |
  o -- O  <-- new branch: featureX
       |
       o  <-- commit objects on the featureX
       |
  o -- o  <-- move everything back to master
  |
  o  <--continue working on master
</code>```

What are the steps I need to follow in order to this?

Note that I do not want to merge any files together...just overwrite the stuff on master.  You can also assume that no work has been done on master while working on featureX.

答:
If no other work has been done on master since branching for featureX:

```<code>git checkout master
git merge featureX
</code>```

This will be a "fast-forward" merge that should do what you want. After the above, you can:

```<code>git branch -d featureX
</code>```

to delete the old branch.

ContentLicense: CC BY-SA 2.5

Body:
Say I currently have the following in git:

master
  O
  |
  o  <-- commit objects on master branch
  |
  o -- O  <-- new branch: featureX
       |
       o  <-- commit objects on the featureX
       |
       o

So I started with the master branch and after two commits, I branched to featureX.

Now, after 2 commits on featureX, I want to converge it with master and continue work on master from the last commit on featureX.

This means that I don't want to merge the files between master and featureX but transferring all the commits done on featureX to master and continue working on master from the last commit that was done on featureX.

Basically, something like this:

master
  O
  |
  o  <-- commit objects on master branch
  |
  o -- O  <-- new branch: featureX
       |
       o  <-- commit objects on the featureX
       |
  o -- o  <-- move everything back to master
  |
  o  <--continue working on master

What are the steps I need to follow in order to this?

Note that I do not want to merge any files together...just overwrite the stuff on master.  You can also assume that no work has been done on master while working on featureX.

Body:
If no other work has been done on master since branching for featureX:

git checkout master
git merge featureX

This will be a "fast-forward" merge that should do what you want. After the above, you can:

git branch -d featureX

to delete the old branch.


问:
Appending in middle of text in column data oracle sql
I need to append the text in middle of text .

1 EX :existing text is : "Monoclonal Anti-FLAG, Clone 6F7"

Result :"<HIDE>Monoclonal Anti-<HIDE>FLAG, Clone 6F7".

2 EX :existing text is : "Anti-100-KD subunit"

Result  : "<HIDE> Anti-</HIDE>100-KD subunit"

I want to append <HIDE> tag where ever Anti and Monoclonal term is coming.

```<code>select * from table where regexp_like(colnanme, '^(Monoclonal Anti|Anti)')
</code>```

Can you suggest how should i write this .for select i have written query .

答:
you could use replace and like

```<code> select replace(colname, 'Anti', '"<HIDE> Anti-</HIDE> )
 from table where colname like '%Anti%'
 and colname not like 'Monoclonal Anti%';
</code>```

of for a combined situation you can use  a case when for lead replace

```<code>  select case when  colname like '%Monoclonal Anti%'
                then replace(colname, 'Monoclonal Anti', '"<HIDE> Monoclonal Anti-</HIDE> )
              when  colname like '%Anti%'
                 then replace(colname, 'Anti', '"<HIDE> Anti-</HIDE> )
               else colname
              end
 from table where colname like '%Anti%';
</code>```

Body:
I need to append the text in middle of text .

1 EX :existing text is : "Monoclonal Anti-FLAG, Clone 6F7"

Result :"<HIDE>Monoclonal Anti-<HIDE>FLAG, Clone 6F7".

2 EX :existing text is : "Anti-100-KD subunit"

Result  : "<HIDE> Anti-</HIDE>100-KD subunit"

I want to append <HIDE> tag where ever Anti and Monoclonal term is coming.

select * from table where regexp_like(colnanme, '^(Monoclonal Anti|Anti)')

Can you suggest how should i write this .for select i have written query .

Body:
you could use replace and like

 select replace(colname, 'Anti', '"<HIDE> Anti-</HIDE> )
 from table where colname like '%Anti%'
 and colname not like 'Monoclonal Anti%';

of for a combined situation you can use  a case when for lead replace

  select case when  colname like '%Monoclonal Anti%'
                then replace(colname, 'Monoclonal Anti', '"<HIDE> Monoclonal Anti-</HIDE> )
              when  colname like '%Anti%'
                 then replace(colname, 'Anti', '"<HIDE> Anti-</HIDE> )
               else colname
              end
 from table where colname like '%Anti%';


问:
"this" lost after construct? (ts/node/express)
I am trying to build a simple http app using node-express.

Issue when setting up routes, the constructor of the MyRouter class has this but it's lost in the getRoutes() function.

```<code>class Main {
    public async run(): Promise<void> {
        const myRouter = new MyRouter(this.config);
        // this.server is express() during construct
        this.server.use("/v1", myRouter.getRoutes);

        await this.server.listen(this.config.rest.port);
    }
}

class MyRouter {
    private router: express.Router;

    constructor(private config: any) {
        this.router = express.Router();
        console.log(this); // Prints the whole Router object!
    }

    public getRoutes(): express.Router {
        console.log(this); // = "undefined" !
        this.router.use("/test", otherClass.getRoutes);
        return this.router;
    }
}
</code>```

Why is this?

答:
The value of this depends not on where it is defined but by how a function is called. You did this:

```<code>this.server.use("/v1", myRouter.getRoutes);
</code>```

This is equivalent to:

```<code>var tmp = myRouter.getRoutes;

this.server.use("/v1", tmp); // `this` will refer to the global object
</code>```

There are two solutions. Either wrap it in an anonymous function to retain the object that calls the function:

```<code>this.server.use("/v1", function(){return myRouter.getRoutes()});
</code>```

Or use .bind()

```<code>this.server.use("/v1", myRouter.getRoutes.bind(myRouter));
</code>```

Body:
I am trying to build a simple http app using node-express.

Issue when setting up routes, the constructor of the MyRouter class has this but it's lost in the getRoutes() function.

class Main {
    public async run(): Promise<void> {
        const myRouter = new MyRouter(this.config);
        // this.server is express() during construct
        this.server.use("/v1", myRouter.getRoutes);

        await this.server.listen(this.config.rest.port);
    }
}

class MyRouter {
    private router: express.Router;

    constructor(private config: any) {
        this.router = express.Router();
        console.log(this); // Prints the whole Router object!
    }

    public getRoutes(): express.Router {
        console.log(this); // = "undefined" !
        this.router.use("/test", otherClass.getRoutes);
        return this.router;
    }
}

Why is this?

Body:
The value of this depends not on where it is defined but by how a function is called. You did this:

this.server.use("/v1", myRouter.getRoutes);

This is equivalent to:

var tmp = myRouter.getRoutes;

this.server.use("/v1", tmp); // `this` will refer to the global object

There are two solutions. Either wrap it in an anonymous function to retain the object that calls the function:

this.server.use("/v1", function(){return myRouter.getRoutes()});

Or use .bind()

this.server.use("/v1", myRouter.getRoutes.bind(myRouter));


问:
Dynamically creating HTML elements using Javascript?
I want to dynamically create some HTML elements (3 html element) and then return this html code as a string in a variable. I don't want to write the HTML code in the following function to some div, but, I want to return it in a var.

```<code>function createMyElements(id1,id2,id3){

   //create anchor with id1
   //create div with id 2
   //create xyz with id3

  //now return the html code of above created just now

}
</code>```

How can I do this?

答:
Here's simple illustration for converting the html-page (static), to javascript based html-page (dynamic).

Let us say, you have html-page as "index.html" (calling index_static.html here).

index_static.html

```<code><!DOCTYPE HTML>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <h1> Hello !!! </h1>
    </body>
</html>
</code>```

You can open this file in the browser, to see the desired output.

Now, lets create a javascript equivalent to this.
Use online-tool, to generate the javascript source (by pasting the above html file source to it). Therefore, it follows as:

dynamic.js

```<code>document.write("<!DOCTYPE HTML>");
document.write("<html>");
document.write("    <head>");
document.write("        <title>Test<\/title>");
document.write("    <\/head>");
document.write("    <body>");
document.write("        <h1> Hello !!! <\/h1>");
document.write("    <\/body>");
document.write("<\/html>");
</code>```

And now, your dynamic version of the static_index.html will be as below:

index_dynamic.html

```<code><script language="JavaScript" src="dynamic.js"></script>
</code>```

Open the index_dynamic.html on the browser to validate the web-page (dynamic though, down-the-line).

more info

Body:
I want to dynamically create some HTML elements (3 html element) and then return this html code as a string in a variable. I don't want to write the HTML code in the following function to some div, but, I want to return it in a var.

function createMyElements(id1,id2,id3){

   //create anchor with id1
   //create div with id 2
   //create xyz with id3

  //now return the html code of above created just now

}

How can I do this?

Body:
Here's simple illustration for converting the html-page (static), to javascript based html-page (dynamic).

Let us say, you have html-page as "index.html" (calling index_static.html here).

index_static.html

<!DOCTYPE HTML>
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
        <h1> Hello !!! </h1>
    </body>
</html>

You can open this file in the browser, to see the desired output.

Now, lets create a javascript equivalent to this.
Use online-tool, to generate the javascript source (by pasting the above html file source to it). Therefore, it follows as:

dynamic.js

document.write("<!DOCTYPE HTML>");
document.write("<html>");
document.write("    <head>");
document.write("        <title>Test<\/title>");
document.write("    <\/head>");
document.write("    <body>");
document.write("        <h1> Hello !!! <\/h1>");
document.write("    <\/body>");
document.write("<\/html>");

And now, your dynamic version of the static_index.html will be as below:

index_dynamic.html

<script language="JavaScript" src="dynamic.js"></script>

Open the index_dynamic.html on the browser to validate the web-page (dynamic though, down-the-line).

more info


问:
Is reusing a variable in VB6 a good idea?
Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong.  Will it cause a memory leak.

EG:

```<code>try

dim mySQL as new sqlcommand(sSQL, cnInput)

// do a sql execute and read the data

mySQL = new sqlcommand(sSQLdifferent, cnInput)

// do sql execute and read the data
catch ...

finally

if mysql isnot nothing then
   mysql.dispose
   mysql = nothing
end if
</code>```

EDIT: put try catch in to avoid the comments about not using them

答:
Be careful.  If you have to do a lot of these in a loop it can be slow.  It's much better to just update the .CommandText property of the same command, like this (also, you can clean up the syntax a little):

```<code>Using mysql as New SqlCommand(sSql, cnInput)
  ' do stuff'

    mySql.CommandText = otherSql

   'do other stuff'
End Using
</code>```

Of course, that only works if the first command is no longer active.  If you're still in the middle of going through a datareader then you better create a new command.

Body:
Essentially I want to know if in VB.NET 2005 if using a sqlcommand and then reusing it by using the NEW is wrong.  Will it cause a memory leak.

EG:

try

dim mySQL as new sqlcommand(sSQL, cnInput)

// do a sql execute and read the data

mySQL = new sqlcommand(sSQLdifferent, cnInput)

// do sql execute and read the data
catch ...

finally

if mysql isnot nothing then
   mysql.dispose
   mysql = nothing
end if

EDIT: put try catch in to avoid the comments about not using them

LastEditorDisplayName: Joel Coehoorn

Body:
Be careful.  If you have to do a lot of these in a loop it can be slow.  It's much better to just update the .CommandText property of the same command, like this (also, you can clean up the syntax a little):

Using mysql as New SqlCommand(sSql, cnInput)
  ' do stuff'

    mySql.CommandText = otherSql

   'do other stuff'
End Using

Of course, that only works if the first command is no longer active.  If you're still in the middle of going through a datareader then you better create a new command.

OwnerDisplayName: Joel Coehoorn


答:
Actually the property is "USD" not usd.

try this one

```<code>console.log(body); //first
    console.log(body.USD); //second
</code>```

Title: Nodejs returns the full JSON of the Blockchain Rates API but I can't access particular objects inside it. Why?

Body:
I have a file that makes a request to blockchain.info/ticker API in order to pull the latest price of bitcoin.

script.js:

let request = require('request');
let url = "https://blockchain.info/ticker"

request.get(url,
function(error, response, body) {
    console.log(body); //first
    console.log(body.USD); //second
});

The first console.log statement inside the request.get returns:

{
  "USD" : {"15m" : 1034.99, "last" : 1034.99, "buy" : 1033.63, "sell" : 1034.99,  "symbol" : "$"},
  "ISK" : {"15m" : 116090.37, "last" : 116090.37, "buy" : 115937.82, "sell" : 116090.37,  "symbol" : "kr"},
  "HKD" : {"15m" : 8043.46, "last" : 8043.46, "buy" : 8032.89, "sell" : 8043.46,  "symbol" : "$"},
  "TWD" : {"15m" : 31374.69, "last" : 31374.69, "buy" : 31333.46, "sell" : 31374.69,  "symbol" : "NT$"},
  "CHF" : {"15m" : 1030.89, "last" : 1030.89, "buy" : 1029.53, "sell" : 1030.89,  "symbol" : "CHF"},
  "EUR" : {"15m" : 963.89, "last" : 963.89, "buy" : 962.63, "sell" : 963.89,  "symbol" : "€"},
  "DKK" : {"15m" : 7170.6, "last" : 7170.6, "buy" : 7161.17, "sell" : 7170.6,  "symbol" : "kr"},
  "CLP" : {"15m" : 685784.37, "last" : 685784.37, "buy" : 684883.24, "sell" : 685784.37,  "symbol" : "$"},
  "CAD" : {"15m" : 1380.41, "last" : 1380.41, "buy" : 1378.6, "sell" : 1380.41,  "symbol" : "$"},
  "CNY" : {"15m" : 7131.48, "last" : 7131.48, "buy" : 7122.11, "sell" : 7131.48,  "symbol" : "¥"},
  "THB" : {"15m" : 35634.71, "last" : 35634.71, "buy" : 35587.88, "sell" : 35634.71,  "symbol" : "฿"},
  "AUD" : {"15m" : 1349.36, "last" : 1349.36, "buy" : 1347.58, "sell" : 1349.36,  "symbol" : "$"},
  "SGD" : {"15m" : 1443.9, "last" : 1443.9, "buy" : 1442.01, "sell" : 1443.9,  "symbol" : "$"},
  "KRW" : {"15m" : 1155773.33, "last" : 1155773.33, "buy" : 1154254.62, "sell" : 1155773.33,  "symbol" : "₩"},
  "JPY" : {"15m" : 115110.38, "last" : 115110.38, "buy" : 114959.12, "sell" : 115110.38,  "symbol" : "¥"},
  "PLN" : {"15m" : 4072.84, "last" : 4072.84, "buy" : 4067.49, "sell" : 4072.84,  "symbol" : "zł"},
  "GBP" : {"15m" : 832.11, "last" : 832.11, "buy" : 831.01, "sell" : 832.11,  "symbol" : "£"},
  "SEK" : {"15m" : 9212.32, "last" : 9212.32, "buy" : 9200.21, "sell" : 9212.32,  "symbol" : "kr"},
  "NZD" : {"15m" : 1474.6, "last" : 1474.6, "buy" : 1472.66, "sell" : 1474.6,  "symbol" : "$"},
  "BRL" : {"15m" : 3232.68, "last" : 3232.68, "buy" : 3228.43, "sell" : 3232.68,  "symbol" : "R$"},
  "RUB" : {"15m" : 58287.38, "last" : 58287.38, "buy" : 58210.79, "sell" : 58287.38,  "symbol" : "RUB"}

}

The second console.log statement returns:

undefined

What have I tried:
I have tried to assign the same output that I get in the terminal to a variable in a chrome inspector and access different objects just to test out if my syntax is correct. Syntax is correct so, I'm really puzzled.

Why is my second console.log statement undefined and how can I fix this in order to get the "15m" price inside of the USD object?

Body:
Actually the property is "USD" not usd.

try this one

console.log(body); //first
    console.log(body.USD); //second


问:
Find vba code from an excel file did not open
I have my code in an excel file but the problem that I can't open this file. What can I do in this case?
It's in 100% and I wait and it doesn't like to be opened.

答:
I am not really sure if this is going to help. But I was unable to post this "picture" in a comment. Hence, I am posting it as a possible solution to your problem:

Open Excel and go to the VBE (Developer Tab --> Macros)

Open the Immdediate Window in the VBE

Type in the command as given below (make sure to change the path and file name as necessary) and confirm by pressing return.

The file should now open in read only mode and a small window should notify you that Excel attempted to repair the file while opening it.

```<code>Workbooks.Open FileName:="C:\tmp\ProblematicFile.xlsm", UpdateLinks:=False, ReadOnly:=True, CorruptLoad:=xlRepairFile
</code>```

Body:
I am not really sure if this is going to help. But I was unable to post this "picture" in a comment. Hence, I am posting it as a possible solution to your problem:

Open Excel and go to the VBE (Developer Tab --> Macros)

Open the Immdediate Window in the VBE

Type in the command as given below (make sure to change the path and file name as necessary) and confirm by pressing return.

The file should now open in read only mode and a small window should notify you that Excel attempted to repair the file while opening it.

Workbooks.Open FileName:="C:\tmp\ProblematicFile.xlsm", UpdateLinks:=False, ReadOnly:=True, CorruptLoad:=xlRepairFile


问:
Method not found on runtime
I have an ASP.Net c# project trying to access methods in a class in another project. It's working for first half of methods in the class but not for the other half of the methods in the class which I recently added. They compile, but they throw a method not found exception at run-time.

Does anyone have any ideas I could try? I've tried:

recreating the .sln file

Subbing in another class library project, which I know works. It appears that the error is in my main project that calls the method in the other project.

答:
I had the same issue. In my case, it was caused by the addition of an [optional argument][1].
So first you would have:

referencingAssembly:

```<code>referencedAssembly.DoStuff(firstArgument, secondArgument)
</code>```

referencedAssembly:

```<code>public void DoStuff(string firstArgument, string secondArgument)
{
   //stuff to do
}
</code>```

Then you add an optional parameter to the method, but you don't provide that argument while calling it.

referencingAssembly:

```<code>referencedAssembly.DoStuff(firstArgument, secondArgument)//unchanged
</code>```

referencedAssembly:

```<code>public void DoStuff(string firstArgument, string secondArgument, string thirdArgument = "default value")
{
   //stuff to do
}
</code>```

Locally, this will build and run fine since the newly build referencingAssembly.dll will have a reference to the DoStuff(string, string, string) method. But when you only deploy the changed referencedAssembly (thinking: the added argument was optional, and the referencingAssembly still works), the old version of referencingAssembly will throw a MethodNotFound since it seeks a method with the signature DoStuff(string, string), which is no longer present in the referencedAssembly since we added the extra (optional) argument.

A possible solution could be an overload:

referencedAssembly:

```<code>public void DoStuff(string firstArgument, string secondArgument)//original method
{
   DoStuff(firstArgument, secondArgument, "default value")
}
public void DoStuff(string firstArgument, string secondArgument, string thirdArgument)//new overload of the method
{
//stuff to do
}
</code>```

Or deploying the newly build referencingAssembly (which will refer to the method with signature DoStuff(string, string, string)).
[1]: https://msdn.microsoft.com/en-us/library/dd264739.aspx

Title: Method not found on runtime

Body:
I had the same issue. In my case, it was caused by the addition of an [optional argument][1].
So first you would have:

referencingAssembly:

referencedAssembly.DoStuff(firstArgument, secondArgument)

referencedAssembly:

public void DoStuff(string firstArgument, string secondArgument)
{
   //stuff to do
}

Then you add an optional parameter to the method, but you don't provide that argument while calling it.

referencingAssembly:

referencedAssembly.DoStuff(firstArgument, secondArgument)//unchanged

referencedAssembly:

public void DoStuff(string firstArgument, string secondArgument, string thirdArgument = "default value")
{
   //stuff to do
}

Locally, this will build and run fine since the newly build referencingAssembly.dll will have a reference to the DoStuff(string, string, string) method. But when you only deploy the changed referencedAssembly (thinking: the added argument was optional, and the referencingAssembly still works), the old version of referencingAssembly will throw a MethodNotFound since it seeks a method with the signature DoStuff(string, string), which is no longer present in the referencedAssembly since we added the extra (optional) argument.

A possible solution could be an overload:

referencedAssembly:

public void DoStuff(string firstArgument, string secondArgument)//original method
{
   DoStuff(firstArgument, secondArgument, "default value")
}
public void DoStuff(string firstArgument, string secondArgument, string thirdArgument)//new overload of the method
{
//stuff to do
}

Or deploying the newly build referencingAssembly (which will refer to the method with signature DoStuff(string, string, string)).
[1]: https://msdn.microsoft.com/en-us/library/dd264739.aspx


答:
The easy way is to convert to string and then check if it is friendly:</p>

```<code>public static boolean isFriendly(int number)
{
    String num = Integer.toString(number);
    for (int i = 0, dividedBy = 1; i < num.length(); i++, dividedBy++)
    {
        String numToCheck = "";
        for (int j = 0; j <= i; j++)
        {
            numToCheck += num.charAt(j);
        }
        if (Integer.valueOf(numToCheck) % dividedBy != 0) {
            return false;
        }
    }
    return true;
}
</code>```

Title: Java program on "friendly numbers "

Body:
I am working on a assignment about so called "friendly-numbers" with the following definition: An integer is said to be friendly if the leftmost digit is divisible by 1, the leftmost two digits are divisible by 2, and the leftmost three digits are divisible by 3, and so on. The n-digit itself is divisible by n.

Also it was given we need to call a method (as I did or at least tried to do in the code below). It should print whether a number is friendly or not. However, my program prints "The integer is not friendly." in both cases. From what I have tried, I know the counter does work. I just cannot find what I am missing or doing wrong. Help would be appreciated, and preferably with an adaptation of the code below, since that is what I came up with myself.

import java.util.Scanner;
public class A5E4 {

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter an integer: ");
        int friendlyNumber = in.nextInt();
        boolean result = isFriendly(friendlyNumber);
        if (result)
        {
            System.out.println("The integer is friendly");
        }
        else
        {
            System.out.println("The integer is not friendly");
        }
    }
    public static boolean isFriendly(int number)
    {
        int counter = 1;

        while (number / 10 >= 1)
        {
            counter ++;
            number = number / 10;
        }

        boolean check = true;

        for (int i = 1; i <= counter; i++)
        {

            if (number / Math.pow(10, (counter - i)) % i == 0 && check)
            {
                check = true;
            }
            else
            {
                check = false;
            }

        }
        return check;

    }
}

Body:
The easy way is to convert to string and then check if it is friendly:

public static boolean isFriendly(int number)
{
    String num = Integer.toString(number);
    for (int i = 0, dividedBy = 1; i < num.length(); i++, dividedBy++)
    {
        String numToCheck = "";
        for (int j = 0; j <= i; j++)
        {
            numToCheck += num.charAt(j);
        }
        if (Integer.valueOf(numToCheck) % dividedBy != 0) {
            return false;
        }
    }
    return true;
}


问:
Why does SOCKS5 require to relay UDP over UDP?
The SOCKS5 protocol, described by RFC1928 provides support for UDP.

To summarize, a client wishing to relay UDP packets through a SOCKS5 server must, at least:

open a TCP connection to the SOCKS5 server;

send a UDP ASSOCIATE request (cf section 4);

receive from the server the address and port where it must send UDP packets to be relayed;

send datagrams (UDP) to that address, encapsulated with some headers (cf section 7).

Here are some relevant quotations, from section 6:

A UDP association terminates when the TCP connection that the UDP ASSOCIATE request arrived on terminates.

In the reply to a UDP ASSOCIATE request, the BND.PORT and BND.ADDR fields indicate the port number/address where the client MUST send UDP request messages to be relayed.

and section 7:

A UDP-based client MUST send its datagrams to the UDP relay server at the UDP port indicated by BND.PORT in the reply to the UDP ASSOCIATE request.

Why so much complexity? Why not just sending UDP packets in the pre-existing TCP connection?

EDIT: To clarify, I am expecting the SOCKS proxy to receive UDP packets over a TCP stream and then transmit them to the target using actual UDP. And then receive UDP packets from the target and send them back down the TCP stream.

Here is some context.

My goal is to implement reverse tethering, so that an Android device may use the internet connection of the computer it is plugged on, without requiring root access both on the device and the computer (SimpleRT works but requires root access on the computer).

My first idea was to start a simple SOCKS5 server with ssh -D on the computer, so that I only needed to implement the client. The packets would be transmitted from the device to the computer over adb, thanks to remote port forwarding provided by adb reverse…

Unfortunately, OpenSSH SOCKS server does not support UDP. But it was just a limitation from the implementation, I could have used another SOCKS server instead.

However, adb reverse does not support UDP forwarding either.

Hence my question about SOCKS5 protocol.

I am currently writing a PoC implementing my own (simple) protocol over TCP, which is able to relay UDP packets, but I am disappointed not to be able to use a standard protocol (and benefit from existing implementations).

答:
I am answering to my own question: it's probably to avoid TCP mechanisms (packet retransmission, head-of-line blocking…).

For a local reverse tethering tool, it is not a problem though, so I implemented UDP over TCP without using SOCKS.


问:
Display Activity Indicator for sharing to Facebook from UIActivityViewController?
I have a UIActivityViewControllerthat allows images to be shared to Facebook (if the system-wide Facebook account is configured).

This works as expected, but once the Facebook icon is tapped, there is a delay of several seconds before the Facebook sharing dialog is presented. The image is already in memory, so I am not certain what the lag is from, though I suspect it must be from contacting Facebook and waiting for a response.

I don't see any way possible to display an indeterminate UIActivityIndicatorView from the time the Facebook icon is tapped until the dialog is presented. Does anyone know of a way?

答:
Just had a similar problem! I wanted to execute an HTTP call to my web application, which was necessary so I would have the URL for a tweet. (In my case it was complicated further because the call to web application was on an async thread as well.) There are two ways to do it... you can add an Activity Indicator View to the storyboard and create IBActions as described here: http://sourcefreeze.com/uiactivityindicatorview-example-using-swift-in-ios/

I found it more straightforward to just add the UIActivityIndicatorView via code. As a member of your class:

let activityIndicator = UIActivityIndicatorView( activityIndicatorStyle: UIActivityIndicatorViewStyle.gray )

I added the startAnimating() and stopAnimating() calls within new methods:

```<code>func startActtivityIndicator(){

    activityIndicator.center = self.view.center
    activityIndicator.hidesWhenStopped = true
    self.view.addSubview( activityIndicator )
    activityIndicator.startAnimating()

}

func stopActtivityIndicator(){

    activityIndicator.stopAnimating()
    activityIndicator.removeFromSuperview()

}
</code>```

Then call startActivityIndicator() as your first action in your button handler, and stopActtivityIndicator() right before you show the facebook share. In my case, since I wanted to end the indicator and show the tweet box (using SLComposeViewController in response to an async http request, I had to call back into the main thread to the stop method this way:

```<code>DispatchQueue.main.async(execute: { () -> Void in

    self.stopActtivityIndicator()

})
</code>```

Body:
Just had a similar problem! I wanted to execute an HTTP call to my web application, which was necessary so I would have the URL for a tweet. (In my case it was complicated further because the call to web application was on an async thread as well.) There are two ways to do it... you can add an Activity Indicator View to the storyboard and create IBActions as described here: http://sourcefreeze.com/uiactivityindicatorview-example-using-swift-in-ios/

I found it more straightforward to just add the UIActivityIndicatorView via code. As a member of your class:

let activityIndicator = UIActivityIndicatorView( activityIndicatorStyle: UIActivityIndicatorViewStyle.gray )

I added the startAnimating() and stopAnimating() calls within new methods:

func startActtivityIndicator(){

    activityIndicator.center = self.view.center
    activityIndicator.hidesWhenStopped = true
    self.view.addSubview( activityIndicator )
    activityIndicator.startAnimating()

}

func stopActtivityIndicator(){

    activityIndicator.stopAnimating()
    activityIndicator.removeFromSuperview()

}

Then call startActivityIndicator() as your first action in your button handler, and stopActtivityIndicator() right before you show the facebook share. In my case, since I wanted to end the indicator and show the tweet box (using SLComposeViewController in response to an async http request, I had to call back into the main thread to the stop method this way:

DispatchQueue.main.async(execute: { () -> Void in

    self.stopActtivityIndicator()

})


问:
Insert list of objects with MyBatis annotation
I know how to insert list of values with xml config mapper, but I want to do it with annotation.

Something like this, but working

```<code>@Insert("insert into  tableName (param1, param2) values (#{obj1.param1}, #{obj1.param2})")
void insert(@Param("obj1") List<MyObject> obj1);
</code>```

答:
I guess in XML you do it with foreach, then it is the same in annotation, just surround with "})
void insert(@Param("obj1") List<MyObject> obj1);
```

Body:
I know how to insert list of values with xml config mapper, but I want to do it with annotation.

Something like this, but working

@Insert("insert into  tableName (param1, param2) values (#{obj1.param1}, #{obj1.param2})")
void insert(@Param("obj1") List<MyObject> obj1);

Body:
I guess in XML you do it with foreach, then it is the same in annotation, just surround with <script> tags.

@Insert({"<script>",
         "insert into  tableName (param1, param2) values ",
         "<foreach collection='obj1' item='o' separator = ', ' open ="(" close=")" >#{o}</foreach>",
         "</script>"})
void insert(@Param("obj1") List<MyObject> obj1);


问:
smooth scroll to name and ID
I have this code to scroll smoothly to a div id, but not to a name:

```<code>$('.scroll').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top - 70
    }, 800, function(){
        window.location.hash = "#";
        return false;
    });
});
</code>```

and this one does the opposite:

```<code>$('.scroll').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top - 70
    }, 800, function(){
        window.location.hash = "#";
        return false;
    });
});
</code>```

How can I mix both codes to scroll to ID's and names in one code?

答:
Is there a way to do this with vanilla javascript?

The best solution I have found for doing this in vanilla javascript is to import the package https://github.com/cferdinandi/smooth-scroll

Title: smooth scroll to name and ID

Body:
I have this code to scroll smoothly to a div id, but not to a name:

$('.scroll').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top - 70
    }, 800, function(){
        window.location.hash = "#";
        return false;
    });
});

and this one does the opposite:

$('.scroll').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top - 70
    }, 800, function(){
        window.location.hash = "#";
        return false;
    });
});

How can I mix both codes to scroll to ID's and names in one code?


问:
Linq to objects List in list
I have a list of movies

```<code>List<Movie> MovieList
</code>```

and I have a list of selected categories

```<code>List<string> SelCat
</code>```

And say I want to select from the movie list where it matches 2 categories, like the SQL statement below:

SELECT * FROM MovieList WHERE MovieList.Category = 'Action' AND MovieList.Category = 'Drama'

I can get kinda close with linq like so:

var q = (from b in MovieList where b.Categories.Any(p=> SelCat.Contains(p)) select b);

But it acts like an OR query, not an AND. I want it to select all movies that have a category of action and drama.

BTW: Movie.Categories is a List of string. AND Movie.Categories must contain items in the SelCat.

How do I achieve this with Linq to Objects?

答:
A bit convoluted:</p>

```<code>var moviesInSelCat = MovieList.Where(m => SelCat.All(sc => m.Category.Any(c => c == sc)));
</code>```

Title: Linq to objects List in list

Body:
I have a list of movies

List<Movie> MovieList

and I have a list of selected categories

List<string> SelCat

And say I want to select from the movie list where it matches 2 categories, like the SQL statement below:

SELECT * FROM MovieList WHERE MovieList.Category = 'Action' AND MovieList.Category = 'Drama'

I can get kinda close with linq like so:

var q = (from b in MovieList where b.Categories.Any(p=> SelCat.Contains(p)) select b);

But it acts like an OR query, not an AND. I want it to select all movies that have a category of action and drama.

BTW: Movie.Categories is a List of string. AND Movie.Categories must contain items in the SelCat.

How do I achieve this with Linq to Objects?

Body:
A bit convoluted:

var moviesInSelCat = MovieList.Where(m => SelCat.All(sc => m.Category.Any(c => c == sc)));


问:
How to resolve same package name in two different dependency issue in Jboss fuse
I'm trying to use Apache POI to work with excel sheet. The application should support .xlsx format files.

For this I am installing these two dependency as bundles in Jboss FUSE:

```<code><bundle start-level="15">wrap:mvn:org.apache.poi/poi/3.5-FINAL</bundle>
<bundle start-level="15">wrap:mvn:org.apache.poi/poi-ooxml/3.15</bundle>
</code>```

However I get an error saying that it finds below package in both the above bundles. Hence there is an ambiguity.

```<code>org.apache.poi.ss.usermodel
</code>```

ERROR:

```<code>Unable to resolve bundle revision wrap_mvn_org.apache.poi_poi-ooxml_3.15 [2133.0] because it exports package 'org.apache.poi.ss.usermodel' and is also exposed to it from bundle revision wrap_mvn_org.apache.poi_poi_3.5-FINAL [2094.0]
</code>```

As a matter of fact:

I need both the Apache POI dependency mentioned above.

Different set of classes belongs to above package in two
dependencies. And these classes are used in application. Hence I cannot unimport/unexport the package from any of the dependency.

Is there any workaround in FUSE to resolve the issue arising due to same package name in two dependencies.

答: A simple solution would be to create one bundle that contains the contents of both poi bundles. You can achieve this by using the maven-bundle-plugin and the Embed-Dependency option.</p>

Body:
I'm trying to use Apache POI to work with excel sheet. The application should support .xlsx format files.

For this I am installing these two dependency as bundles in Jboss FUSE:

<bundle start-level="15">wrap:mvn:org.apache.poi/poi/3.5-FINAL</bundle>
<bundle start-level="15">wrap:mvn:org.apache.poi/poi-ooxml/3.15</bundle>

However I get an error saying that it finds below package in both the above bundles. Hence there is an ambiguity.

org.apache.poi.ss.usermodel

ERROR:

Unable to resolve bundle revision wrap_mvn_org.apache.poi_poi-ooxml_3.15 [2133.0] because it exports package 'org.apache.poi.ss.usermodel' and is also exposed to it from bundle revision wrap_mvn_org.apache.poi_poi_3.5-FINAL [2094.0]

As a matter of fact:

I need both the Apache POI dependency mentioned above.

Different set of classes belongs to above package in two
dependencies. And these classes are used in application. Hence I cannot unimport/unexport the package from any of the dependency.

Is there any workaround in FUSE to resolve the issue arising due to same package name in two dependencies.


问:
How do I unpin and remove all IPFS content from my machine?
I've added a bunch of files via ipfs add. How do I unpin and remove all of these at once?

答:
to unpin all added content:

ipfs pin ls --type recursive | cut -d' ' -f1 | xargs -n1 ipfs pin rm

then optionally run storage garbage collection to actually remove things:

ipfs repo gc


问:
Python Importing exact hexa value and display
I have the Data structure where I defined the list.

```<code>data_items = [  {"ID":0x0202,  "Name":"Country"},
                { "ID":0x2007, "Name":"Sports"}]
</code>```

I want to import complete 'ID' value including '0', like example:

```<code>'0202'
'2007'
</code>```

Now it is printing as below:

```<code>'202'
'2007'
</code>```

Code:

```<code>Input = 1
SMI = data_items[Input-1]['ID']
hex(SMI)[2:]
</code>```

Suggest me how can I proceed?

答:
Try this: </p>

```<code>SMI = data_items[Input-1]['ID']
SMI = str(SMI).split('0x')[1]
</code>```

Body:
I have the Data structure where I defined the list.

data_items = [  {"ID":0x0202,  "Name":"Country"},
                { "ID":0x2007, "Name":"Sports"}]

I want to import complete 'ID' value including '0', like example:

'0202'
'2007'

Now it is printing as below:

'202'
'2007'

Code:

Input = 1
SMI = data_items[Input-1]['ID']
hex(SMI)[2:]

Suggest me how can I proceed?

Body:
Try this:

SMI = data_items[Input-1]['ID']
SMI = str(SMI).split('0x')[1]


问:
Create folder in custom photo album
I have a custom album in which my app saves picture from camera. I am wondering if there is a way I can create folders inside my album so I can stack certain images inside it?

ANSWER

As fellow members mentioned, sadly there is no way you can create a folder inside album.

答:
You should try code below. It's Swift 3.0 syntaxe. :)

```<code>import Foundation
import Photos

class CustomPhotoAlbum: NSObject {
    static let albumName = "Album Name"
    static let sharedInstance = CustomPhotoAlbum()

    var assetCollection: PHAssetCollection!

    override init() {
        super.init()

        if let assetCollection = fetchAssetCollectionForAlbum() {
            self.assetCollection = assetCollection
            return
        }

        if PHPhotoLibrary.authorizationStatus() != PHAuthorizationStatus.authorized {
            PHPhotoLibrary.requestAuthorization({ (status: PHAuthorizationStatus) -> Void in
                ()
            })
        }

        if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
            self.createAlbum()
        } else {
            PHPhotoLibrary.requestAuthorization(requestAuthorizationHandler)
        }
    }

    func requestAuthorizationHandler(status: PHAuthorizationStatus) {
        if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
            // ideally this ensures the creation of the photo album even if authorization wasn't prompted till after init was done
            print("trying again to create the album")
            self.createAlbum()
        } else {
            print("should really prompt the user to let them know it's failed")
        }
    }

    func createAlbum() {
        PHPhotoLibrary.shared().performChanges({
            PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: CustomPhotoAlbum.albumName)   // create an asset collection with the album name
        }) { success, error in
            if success {
                self.assetCollection = self.fetchAssetCollectionForAlbum()
            } else {
                print("error \(error)")
            }
        }
    }

    func fetchAssetCollectionForAlbum() -> PHAssetCollection? {
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "title = %@", CustomPhotoAlbum.albumName)
        let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

        if let _: AnyObject = collection.firstObject {
            return collection.firstObject
        }
        return nil
    }

    func save(image: UIImage) {
        if assetCollection == nil {
            return                          // if there was an error upstream, skip the save
        }

        PHPhotoLibrary.shared().performChanges({
            let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
            let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset
            let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
            let enumeration: NSArray = [assetPlaceHolder!]
            albumChangeRequest!.addAssets(enumeration)

        }, completionHandler: nil)
    }
}
</code>```

Title: Create folder in custom photo album

Body:
You should try code below. It's Swift 3.0 syntaxe. :)

import Foundation
import Photos

class CustomPhotoAlbum: NSObject {
    static let albumName = "Album Name"
    static let sharedInstance = CustomPhotoAlbum()

    var assetCollection: PHAssetCollection!

    override init() {
        super.init()

        if let assetCollection = fetchAssetCollectionForAlbum() {
            self.assetCollection = assetCollection
            return
        }

        if PHPhotoLibrary.authorizationStatus() != PHAuthorizationStatus.authorized {
            PHPhotoLibrary.requestAuthorization({ (status: PHAuthorizationStatus) -> Void in
                ()
            })
        }

        if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
            self.createAlbum()
        } else {
            PHPhotoLibrary.requestAuthorization(requestAuthorizationHandler)
        }
    }

    func requestAuthorizationHandler(status: PHAuthorizationStatus) {
        if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
            // ideally this ensures the creation of the photo album even if authorization wasn't prompted till after init was done
            print("trying again to create the album")
            self.createAlbum()
        } else {
            print("should really prompt the user to let them know it's failed")
        }
    }

    func createAlbum() {
        PHPhotoLibrary.shared().performChanges({
            PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: CustomPhotoAlbum.albumName)   // create an asset collection with the album name
        }) { success, error in
            if success {
                self.assetCollection = self.fetchAssetCollectionForAlbum()
            } else {
                print("error \(error)")
            }
        }
    }

    func fetchAssetCollectionForAlbum() -> PHAssetCollection? {
        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "title = %@", CustomPhotoAlbum.albumName)
        let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)

        if let _: AnyObject = collection.firstObject {
            return collection.firstObject
        }
        return nil
    }

    func save(image: UIImage) {
        if assetCollection == nil {
            return                          // if there was an error upstream, skip the save
        }

        PHPhotoLibrary.shared().performChanges({
            let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
            let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset
            let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
            let enumeration: NSArray = [assetPlaceHolder!]
            albumChangeRequest!.addAssets(enumeration)

        }, completionHandler: nil)
    }
}


问:
How to get object value from listview adapter position
How to get value from adapter position, i have code in below:

```<code>CategoriesXmlParser categoryXmlParser = new CategoriesXmlParser();
List<HashMap<String, Object>> categories = null;

try {
  categories = categoryXmlParser.parse(reader);
} catch (Exception e) {
  Log.d("Exception", e.toString());
}

String[] from = { "name", "image" };
int[] to = { R.id.nama_category, R.id.logo_category };

final SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
                    categories, R.layout.per_item_category, from, to);

mListView.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
    Object obj = mListView.getAdapter().getItem(position);
    String value = obj.toString();
    Log.d("MyLog", "Value is: "+value);
    String name = // how code to get name value.
  }
});
</code>```

If I look log it on logcat in the MyLog I get as:

Value is: {position=12,
  image_path=http://192.168.103.121/xml/icon.png,
  link=http://192.168.103.121/xml/category.php?kat_id=13, name=Category
  13}

So my question, I want to get value from name and stored to variable String name, I want to get just "Category 13" in String name. Because I want to passing it to another activity.

答:
This is what i did:-</p>
```<code>lvHomePage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                   @Override
                   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                       Transaction selectedFromList =(Transaction)parent.getAdapter().getItem(position);
                       Log.d("val:",selectedFromList.getDate());
                       Log.d("val:",selectedFromList.getMobile_no());
                   }
               });
</code>```

Body:
How to get value from adapter position, i have code in below:

CategoriesXmlParser categoryXmlParser = new CategoriesXmlParser();
List<HashMap<String, Object>> categories = null;

try {
  categories = categoryXmlParser.parse(reader);
} catch (Exception e) {
  Log.d("Exception", e.toString());
}

String[] from = { "name", "image" };
int[] to = { R.id.nama_category, R.id.logo_category };

final SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
                    categories, R.layout.per_item_category, from, to);

mListView.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
    Object obj = mListView.getAdapter().getItem(position);
    String value = obj.toString();
    Log.d("MyLog", "Value is: "+value);
    String name = // how code to get name value.
  }
});

If I look log it on logcat in the MyLog I get as:

Value is: {position=12,
  image_path=http://192.168.103.121/xml/icon.png,
  link=http://192.168.103.121/xml/category.php?kat_id=13, name=Category
  13}

So my question, I want to get value from name and stored to variable String name, I want to get just "Category 13" in String name. Because I want to passing it to another activity.

Body:
This is what i did:-

lvHomePage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                   @Override
                   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                       Transaction selectedFromList =(Transaction)parent.getAdapter().getItem(position);
                       Log.d("val:",selectedFromList.getDate());
                       Log.d("val:",selectedFromList.getMobile_no());
                   }
               });


问:
R programming spectrum analysis
hello am new to R programming in r studio . I will be analyzing the spectral data of raman spectrum in future.
which package will be useful to for the spectral data analysis.I would like to learn that package. I have attached the image how I want to analyze. Please give me suggestions, how to plot the graph as shown in the fig in r studio

thanks in advance

答:
There is a free package called hyperSpec that was specifically designed to handle spectral data together with associated extra data (e.g. experimental parameters etc.). The package also provides interface for common operations, like baseline correction, selection of spectral ranges, normalization, PCA, etc. Moreover, there is a host of plotting functions.

You can install it from CRAN with install.packages("hyperSpec"), however, as of today the CRAN version is outdated. I would recommend you to fetch the recent build from gitHub and install it via Rstudio (look for packages->install->from package archive file).

hyperSpec comes with an extensive documentation and example datasets. To browse through tutorials, run

```<code>browseVignettes("hyperSpec")
</code>```

Plotting is as easy as

```<code>plot(chondro)  # left plot
qplotspc(chondro) + ggtitle("Example dataset")  # right plot
</code>```

To import your own data, look for functions inside of hyperSpec, whose name starts with read. Just start typing hyperSpec::read and a pop-up will appear. A lot of device-specific data formats are supported. See vignette("fileio") for details.

Title: R programming spectrum analysis

Body:
There is a free package called hyperSpec that was specifically designed to handle spectral data together with associated extra data (e.g. experimental parameters etc.). The package also provides interface for common operations, like baseline correction, selection of spectral ranges, normalization, PCA, etc. Moreover, there is a host of plotting functions.

You can install it from CRAN with install.packages("hyperSpec"), however, as of today the CRAN version is outdated. I would recommend you to fetch the recent build from gitHub and install it via Rstudio (look for packages->install->from package archive file).

hyperSpec comes with an extensive documentation and example datasets. To browse through tutorials, run

browseVignettes("hyperSpec")

Plotting is as easy as

plot(chondro)  # left plot
qplotspc(chondro) + ggtitle("Example dataset")  # right plot

To import your own data, look for functions inside of hyperSpec, whose name starts with read. Just start typing hyperSpec::read and a pop-up will appear. A lot of device-specific data formats are supported. See vignette("fileio") for details.