问:
How do i merge changes to directories when making a pull request and then merging?
I have multi-user repository and each user has his own directory, as well as branch. For example:

master

DirectoryA

DirectoryB

BranchA (used by UserA)

DirectoryA (used by UserA)

DirectoryB

BranchB (used by UserB)

DirectoryA

DirectoryB (used by UserB)

Initially, the master branch has files in each directories, then Branch A and B were created. UserA has modified files in his folder in his BranchA, while UserB has modified files in his folder in his BranchB.

How do I create pull requests to the master branch such that the changes made by UserA in DirectoryA located in BranchA is preserved to the master, while UserB in DirectoryB located in BranchB is also preserved?

答:
Shouldn't be any problem with the usual workflow. UserA hasn't touched directory B so his pull request will not contain any changes for B. A pull request from UserB will not change directory A. No problem so far.

But after both PRs are accepted both users must update — and UserA will fetch changes in directory B while UserB will pull changes for directory A.


来源: stackexchange

问:
memory size of int vs integer in java
I have doubt in memory allocation for int and Integer variable in Java. For measuring memory i have used Instrumentation.getObjectSize() and it produces the same size for both the variables. Please find my code below:

ObjectSizeFetcher.java

```<code>import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}
</code>```

Test.java

```<code>public class Test {
public static void main(String[] args) throws Exception {
        int i=0;
        Integer i1 = new Integer(0);
        long value = ObjectSizeFetcher.getObjectSize(i);
        System.out.println(value);//prints 16

        long value1 = ObjectSizeFetcher.getObjectSize(i1);
        System.out.println(value1);//prints 16
}
}
</code>```

In the above case both the variable size prints the same. My doubt is, int is primitive type and it size 4 bytes and Integer is reference type and its size is 16 bytes but in this case why produces 16 bytes for both the values? If both the take same amount of memory in heap means, it leads to memory issue in java right?

答:
int is a primitive type and it size 4 bytes and Integer is reference type and its size is 16 bytes.  In this case, why does it retuyrn 16 bytes for both the values?

Because the ObjectSizeFetcher.getObjectSize(Object) call is autoboxing the int to an Integer.

AFAIK, there is no standard API to measure the size of a primitive type, or a reference.  One reason is that the size will depend on where / how it is stored.  For example, a byte stored in a (large) byte[] will most likely take less space than a byte stored as a field of an object.  And a byte held is a local variable could be different again.  (There are issues of packing and alignment to tack account of.)

It is simple to write overloaded methods to return constant minimum size for each primitive types.  References are a bit more tricky because the size of a reference depends on whether you are using a 32 or 64 bit JVM, and whether compressed oops are enabled.

ContentLicense: CC BY-SA 3.0

Title: memory size of int vs integer in java

Body:
I have doubt in memory allocation for int and Integer variable in Java. For measuring memory i have used Instrumentation.getObjectSize() and it produces the same size for both the variables. Please find my code below:

ObjectSizeFetcher.java

import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}

Test.java

public class Test {
public static void main(String[] args) throws Exception {
        int i=0;
        Integer i1 = new Integer(0);
        long value = ObjectSizeFetcher.getObjectSize(i);
        System.out.println(value);//prints 16

        long value1 = ObjectSizeFetcher.getObjectSize(i1);
        System.out.println(value1);//prints 16
}
}

In the above case both the variable size prints the same. My doubt is, int is primitive type and it size 4 bytes and Integer is reference type and its size is 16 bytes but in this case why produces 16 bytes for both the values? If both the take same amount of memory in heap means, it leads to memory issue in java right?


问:
SQL/PLSQL merge multilist value
I have two table name table1 and table2.

from first table I'm getting number,id and value.ID column is multilist so values in that column are separated by comma, eg: 3799952,3799953. For each ID there is some value in table2. eg for 3799952 value is Assembly and for 3799953 value is Indiviual. I have to get these values with comma separation. in multilist as of now I have only two value so I used sequence upto 2, tomorrow I will be getting multiple value . can anyone help me procedures or userdefined function.

```<code>select id,item_number,max(decode(seq,1,entry_id))||','||max(decode(seq,2,entry_id)) entry_id,
  max(decode(seq,1,entryvalue))||','||max(decode(seq,2,entryvalue)) entryvalue
  from (

  select a.id,a.item_number,a.entry_id,list.entryvalue,row_number() over (partition by item_number order by entry_id) seq
  from  (SELECT i.id,i.item_number,
 trim(regexp_substr(i.product_lines, '[^,]+', 1, lines.column_value)) entry_id
  FROM item i,
     TABLE (CAST (MULTISET
     (SELECT LEVEL FROM dual CONNECT BY LEVEL <= regexp_count(i.product_lines, ','))AS sys.odciNumberList)) lines   ORDER BY i.id)a , listentry list where a.entry_id=list.entryid and a.entry_id is not null)
  group by id,item_number;
</code>```

This is my query and output for this is given below,

```<code>**ID    ITEM_NUMBER ENTRY_ID             ENTRYVALUE**
6024065 P00008           3799953,            Individual,
6024607 U00024          3799952,3799953       Assembly,Individual
6024886 U00154      3799952,3799953       Assembly,Individual
6015685 INK_PEN         3799952,              Assembly,
6036877 P0000020    3799952,3799953       Assembly,Individual
</code>```

As of now I have only two entryvalue so used max(decode(seq,1,entry_id))||','||max(decode(seq,2,entry_id)) entry_id could any one tell me how to modify this for multiple values.

Thanks in advance

答:
Your question is not very clear about what you are trying to achieve - however, it appears you have two comma-delimited lists that you want to separate so that the values remain correlated. You can use a recursive sub-query factoring clause. Something like this (untested):</p>

```<code>WITH data ( id, item_number, entity_id, entryvalue,
            entity_start, entity_end, entry_start, entry_end ) AS (
  SELECT id,
         item_number,
         entity_id,
         entryvalue,
         1,
         INSTR( entity_id, ',', 1 ),
         1,
         INSTR( entryvalue, ',', 1 )
  FROM   your_table
UNION ALL
  SELECT id,
         item_number,
         entity_id,
         entryvalue,
         entity_end + 1,
         INSTR( entity_id, ',', entity_end + 1 ),
         entry_end + 1,
         INSTR( entryvalue, ',', entry_end + 1 )
  FROM   data
  WHERE  entity_end > 0 AND entry_start > 0
)
SELECT id,
       item_number,
       CASE entity_end
         WHEN 0
         THEN SUBSTR( entity_id, entity_start )
         ELSE SUBSTR( entity_id, entity_start, entity_end - entity_start )
       END AS entity_id,
       CASE entry_end
         WHEN 0
         THEN SUBSTR( entryvalue, entry_start )
         ELSE SUBSTR( entryvalue, entry_start, entry_end - entry_start )
       END AS entryvalue
FROM   data;
</code>```

Title: SQL/PLSQL merge multilist value

Body:
I have two table name table1 and table2.

from first table I'm getting number,id and value.ID column is multilist so values in that column are separated by comma, eg: 3799952,3799953. For each ID there is some value in table2. eg for 3799952 value is Assembly and for 3799953 value is Indiviual. I have to get these values with comma separation. in multilist as of now I have only two value so I used sequence upto 2, tomorrow I will be getting multiple value . can anyone help me procedures or userdefined function.

select id,item_number,max(decode(seq,1,entry_id))||','||max(decode(seq,2,entry_id)) entry_id,
  max(decode(seq,1,entryvalue))||','||max(decode(seq,2,entryvalue)) entryvalue
  from (

  select a.id,a.item_number,a.entry_id,list.entryvalue,row_number() over (partition by item_number order by entry_id) seq
  from  (SELECT i.id,i.item_number,
 trim(regexp_substr(i.product_lines, '[^,]+', 1, lines.column_value)) entry_id
  FROM item i,
     TABLE (CAST (MULTISET
     (SELECT LEVEL FROM dual CONNECT BY LEVEL <= regexp_count(i.product_lines, ','))AS sys.odciNumberList)) lines   ORDER BY i.id)a , listentry list where a.entry_id=list.entryid and a.entry_id is not null)
  group by id,item_number;

This is my query and output for this is given below,

**ID    ITEM_NUMBER ENTRY_ID             ENTRYVALUE**
6024065 P00008           3799953,            Individual,
6024607 U00024          3799952,3799953       Assembly,Individual
6024886 U00154      3799952,3799953       Assembly,Individual
6015685 INK_PEN         3799952,              Assembly,
6036877 P0000020    3799952,3799953       Assembly,Individual

As of now I have only two entryvalue so used max(decode(seq,1,entry_id))||','||max(decode(seq,2,entry_id)) entry_id could any one tell me how to modify this for multiple values.

Thanks in advance

Body:
Your question is not very clear about what you are trying to achieve - however, it appears you have two comma-delimited lists that you want to separate so that the values remain correlated. You can use a recursive sub-query factoring clause. Something like this (untested):

WITH data ( id, item_number, entity_id, entryvalue,
            entity_start, entity_end, entry_start, entry_end ) AS (
  SELECT id,
         item_number,
         entity_id,
         entryvalue,
         1,
         INSTR( entity_id, ',', 1 ),
         1,
         INSTR( entryvalue, ',', 1 )
  FROM   your_table
UNION ALL
  SELECT id,
         item_number,
         entity_id,
         entryvalue,
         entity_end + 1,
         INSTR( entity_id, ',', entity_end + 1 ),
         entry_end + 1,
         INSTR( entryvalue, ',', entry_end + 1 )
  FROM   data
  WHERE  entity_end > 0 AND entry_start > 0
)
SELECT id,
       item_number,
       CASE entity_end
         WHEN 0
         THEN SUBSTR( entity_id, entity_start )
         ELSE SUBSTR( entity_id, entity_start, entity_end - entity_start )
       END AS entity_id,
       CASE entry_end
         WHEN 0
         THEN SUBSTR( entryvalue, entry_start )
         ELSE SUBSTR( entryvalue, entry_start, entry_end - entry_start )
       END AS entryvalue
FROM   data;


问:
Binding images dynamically but not all images are clickable in Angular
This is my typescript code where I bound multiple images dynamically in list items.

```<code> for (let i = 0; i < event.target.files.length; ++i) {
            var reader = new FileReader();
            console.log(this.imgs);
            reader.onload = (e: any) => {
                var src = e.target.result;
                $("#UiImage").append("<li style=\"float:left;margin: 10px 5px\" id=\"liimage" + i + "\" ><img src=\"" + src + "\" id=\"Upimage" + i + "\" (click)=\"ZoomImage()\" \height=\"100px\" \width=\"100px\" /></li>  ");
                this.imgs.push(src);
                this.src_pt = src;
            }
            reader.readAsDataURL(event.target.files[i]);
        }
</code>```

When I click particular image for preview, that click event is not working.

答:
Just Try this one and let me know whether its working or not? :

In HTML you do like this...

```<code> <ul style="list-style-type: none; display: inline;" *ngFor="let row of rows">
                                <li style="float:left;margin: 10px 5px">
                                    <img src="{{row}}" width="100px" height="100px" (click)="ZoomImage($event,row)" />
                                </li>
                            </ul>
</code>```

And in typescript, you implement the loop concept as mentioned below!

```<code>  for (let i = 0; i < event.target.files.length; ++i) {
            var reader = new FileReader();
            console.log(this.imgs);
            reader.onload = (e: any) => {
                var src = e.target.result;
                this.rows.push(src);
            }
            reader.readAsDataURL(event.target.files[i]);
        }
</code>```

Body:
This is my typescript code where I bound multiple images dynamically in list items.

 for (let i = 0; i < event.target.files.length; ++i) {
            var reader = new FileReader();
            console.log(this.imgs);
            reader.onload = (e: any) => {
                var src = e.target.result;
                $("#UiImage").append("

  ");
                this.imgs.push(src);
                this.src_pt = src;
            }
            reader.readAsDataURL(event.target.files[i]);
        }

When I click particular image for preview, that click event is not working.

Body:
Just Try this one and let me know whether its working or not? :

In HTML you do like this...

 <ul style="list-style-type: none; display: inline;" *ngFor="let row of rows">
                                <li style="float:left;margin: 10px 5px">
                                    <img src="{{row}}" width="100px" height="100px" (click)="ZoomImage($event,row)" /> &nbsp;
                                </li>
                            </ul>

And in typescript, you implement the loop concept as mentioned below!

  for (let i = 0; i < event.target.files.length; ++i) {
            var reader = new FileReader();
            console.log(this.imgs);
            reader.onload = (e: any) => {
                var src = e.target.result;
                this.rows.push(src);
            }
            reader.readAsDataURL(event.target.files[i]);
        }


问:
CALayers didn't get resized on its UIView's bounds change. Why?
I have a UIView which has about 8 different CALayer sublayers added to its layer.
If I modify the view's bounds (animated), then the view itself shrinks (I checked it with a backgroundColor), but the sublayers' size remains unchanged.

How to solve this?

答:
Swift 3 Version

In Custom cell, Add Following lines

Declare first

```<code>let gradientLayer: CAGradientLayer = CAGradientLayer()
</code>```

Then add following lines

```<code>override func layoutSubviews() {
    gradientLayer.frame = self.YourCustomView.bounds
}
</code>```

Body:
Swift 3 Version

In Custom cell, Add Following lines

Declare first

let gradientLayer: CAGradientLayer = CAGradientLayer()

Then add following lines

override func layoutSubviews() {
    gradientLayer.frame = self.YourCustomView.bounds
}


问:
Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'
I am a greenhorn in gradle and i just tried to create a new Android Gradle Project in IntelliJ. After filling up the necessities it started to download something which took hours so i decided to force quit my IDE and open the project again.

And now I am getting this:

And when I open the IDE logs, I see this:

```<code>2014-12-13 22:27:37,940 [103759372]   INFO - .BaseProjectImportErrorHandler - Failed to import Gradle project at '/Users/ramswaroop/Documents/My Workspace/PopoPics'
org.gradle.tooling.GradleConnectionException: Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:124)
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:112)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
    at org.gradle.tooling.internal.consumer.BlockingResultHandler.getResult(BlockingResultHandler.java:46)
    at org.gradle.tooling.internal.consumer.DefaultBuildActionExecuter.run(DefaultBuildActionExecuter.java:46)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.doResolveProjectInfo(GradleProjectResolver.java:177)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.access$300(GradleProjectResolver.java:63)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:363)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:335)
    at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.execute(GradleExecutionHelper.java:214)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:95)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:63)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:41)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:49)
    at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:51)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:137)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:123)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$2.execute(ExternalSystemUtil.java:475)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3$2.run(ExternalSystemUtil.java:552)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$TaskRunnable.run(ProgressManagerImpl.java:621)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$3.run(ProgressManagerImpl.java:194)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.a(ProgressManagerImpl.java:281)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:233)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:181)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$9.run(ProgressManagerImpl.java:530)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:405)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
    at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:56)
Caused by: java.nio.channels.OverlappingFileLockException
    at sun.nio.ch.FileChannelImpl$SharedFileLockTable.checkList(FileChannelImpl.java:1166)
    at sun.nio.ch.FileChannelImpl$SharedFileLockTable.add(FileChannelImpl.java:1068)
    at sun.nio.ch.FileChannelImpl.tryLock(FileChannelImpl.java:868)
    at java.nio.channels.FileChannel.tryLock(FileChannel.java:962)
    at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:51)
    at org.gradle.wrapper.Install.createDist(Install.java:44)
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:118)
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:112)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
2014-12-13 22:27:37,941 [103759373]   WARN - nal.AbstractExternalSystemTask - Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.
com.intellij.openapi.externalSystem.model.ExternalSystemException: Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectImportErrorHandler.createUserFriendlyError(AbstractProjectImportErrorHandler.java:106)
    at org.jetbrains.plugins.gradle.service.project.BaseProjectImportErrorHandler.getUserFriendlyError(BaseProjectImportErrorHandler.java:158)
    at org.jetbrains.plugins.gradle.service.project.BaseGradleProjectResolverExtension.getUserFriendlyError(BaseGradleProjectResolverExtension.java:401)
    at com.android.tools.idea.gradle.project.AndroidGradleProjectResolver.getUserFriendlyError(AndroidGradleProjectResolver.java:309)
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension.getUserFriendlyError(AbstractProjectResolverExtension.java:164)
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension.getUserFriendlyError(AbstractProjectResolverExtension.java:164)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:369)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:335)
    at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.execute(GradleExecutionHelper.java:214)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:95)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:63)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:41)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:49)
    at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:51)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:137)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:123)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$2.execute(ExternalSystemUtil.java:475)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3$2.run(ExternalSystemUtil.java:552)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$TaskRunnable.run(ProgressManagerImpl.java:621)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$3.run(ProgressManagerImpl.java:194)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.a(ProgressManagerImpl.java:281)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:233)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:181)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$9.run(ProgressManagerImpl.java:530)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:405)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
    at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:56)

2014-12-13 22:27:37,942 [103759374]   WARN - radle.project.ProjectSetUpTask -
2014-12-13 22:27:37,942 [103759374]   INFO - radle.project.ProjectSetUpTask - Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.

Consult IDE log for more details (Help | Show Log)
 </code>```

INFO: Running on Mac Yosemite with Gradle 2.2 and IntelliJ IDEA 14 Ultimate.

答:
It could be that the corresponding Gradle version was not downloaded properly.

You could delete the broken file at

```<code>rm -rf .gradle/wrapper/dists/
</code>```

and restart studio.

or try

```<code>File -> Settings -> Gradle -> Check Offline Work
</code>```

and download the file from the official site and extract to the destination location

```<code>.gradle/wrapper/dists/
</code>```

Body:
I am a greenhorn in gradle and i just tried to create a new Android Gradle Project in IntelliJ. After filling up the necessities it started to download something which took hours so i decided to force quit my IDE and open the project again.

And now I am getting this:

And when I open the IDE logs, I see this:

2014-12-13 22:27:37,940 [103759372]   INFO - .BaseProjectImportErrorHandler - Failed to import Gradle project at '/Users/ramswaroop/Documents/My Workspace/PopoPics'
org.gradle.tooling.GradleConnectionException: Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:124)
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:112)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
    at org.gradle.tooling.internal.consumer.BlockingResultHandler.getResult(BlockingResultHandler.java:46)
    at org.gradle.tooling.internal.consumer.DefaultBuildActionExecuter.run(DefaultBuildActionExecuter.java:46)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.doResolveProjectInfo(GradleProjectResolver.java:177)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.access$300(GradleProjectResolver.java:63)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:363)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:335)
    at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.execute(GradleExecutionHelper.java:214)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:95)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:63)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:41)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:49)
    at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:51)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:137)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:123)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$2.execute(ExternalSystemUtil.java:475)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3$2.run(ExternalSystemUtil.java:552)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$TaskRunnable.run(ProgressManagerImpl.java:621)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$3.run(ProgressManagerImpl.java:194)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.a(ProgressManagerImpl.java:281)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:233)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:181)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$9.run(ProgressManagerImpl.java:530)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:405)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
    at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:56)
Caused by: java.nio.channels.OverlappingFileLockException
    at sun.nio.ch.FileChannelImpl$SharedFileLockTable.checkList(FileChannelImpl.java:1166)
    at sun.nio.ch.FileChannelImpl$SharedFileLockTable.add(FileChannelImpl.java:1068)
    at sun.nio.ch.FileChannelImpl.tryLock(FileChannelImpl.java:868)
    at java.nio.channels.FileChannel.tryLock(FileChannel.java:962)
    at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:51)
    at org.gradle.wrapper.Install.createDist(Install.java:44)
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:118)
    at org.gradle.tooling.internal.consumer.DistributionFactory$ZippedDistribution$1.call(DistributionFactory.java:112)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
2014-12-13 22:27:37,941 [103759373]   WARN - nal.AbstractExternalSystemTask - Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.
com.intellij.openapi.externalSystem.model.ExternalSystemException: Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectImportErrorHandler.createUserFriendlyError(AbstractProjectImportErrorHandler.java:106)
    at org.jetbrains.plugins.gradle.service.project.BaseProjectImportErrorHandler.getUserFriendlyError(BaseProjectImportErrorHandler.java:158)
    at org.jetbrains.plugins.gradle.service.project.BaseGradleProjectResolverExtension.getUserFriendlyError(BaseGradleProjectResolverExtension.java:401)
    at com.android.tools.idea.gradle.project.AndroidGradleProjectResolver.getUserFriendlyError(AndroidGradleProjectResolver.java:309)
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension.getUserFriendlyError(AbstractProjectResolverExtension.java:164)
    at org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension.getUserFriendlyError(AbstractProjectResolverExtension.java:164)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:369)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:335)
    at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.execute(GradleExecutionHelper.java:214)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:95)
    at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:63)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:41)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59)
    at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37)
    at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:49)
    at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:51)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:137)
    at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:123)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$2.execute(ExternalSystemUtil.java:475)
    at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3$2.run(ExternalSystemUtil.java:552)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$TaskRunnable.run(ProgressManagerImpl.java:621)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$3.run(ProgressManagerImpl.java:194)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.a(ProgressManagerImpl.java:281)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:233)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcess(ProgressManagerImpl.java:181)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl$9.run(ProgressManagerImpl.java:530)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:405)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
    at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:56)

2014-12-13 22:27:37,942 [103759374]   WARN - radle.project.ProjectSetUpTask -
2014-12-13 22:27:37,942 [103759374]   INFO - radle.project.ProjectSetUpTask - Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'.

Consult IDE log for more details (Help | Show Log)

INFO: Running on Mac Yosemite with Gradle 2.2 and IntelliJ IDEA 14 Ultimate.

Body:
It could be that the corresponding Gradle version was not downloaded properly.

You could delete the broken file at

rm -rf .gradle/wrapper/dists/

and restart studio.

or try

File -> Settings -> Gradle -> Check Offline Work

and download the file from the official site and extract to the destination location

.gradle/wrapper/dists/


问:
Failure of building Jenkins Docker Image
I am using the following Dockerfile to build a Jenkins Image with pre-installed plugins.

FROM jenkins

USER root
RUN apt-get -yqq update
RUN curl -sSL https://get.docker.com/ | sh
RUN usermod -aG docker jenkins

COPY plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN /usr/local/bin/install-plugins.sh $(cat /usr/share/jenkins/ref/plugins.txt)

USER jenkins```
</div>
</div>
</p>

<p>However, ran into an error about an existing plugin.lock problem.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Step 10/11 : RUN /usr/local/bin/install-plugins.sh $(cat /usr/share/jenkins/ref/plugins.txt)
 ---> Running in 0823515c2574
Creating initial locks...
[91mmkdir: cannot create directory ‘/usr/share/jenkins/ref/plugins/Plugin.lock’: File exists
[0mThe command '/bin/sh -c /usr/local/bin/install-plugins.sh $(cat /usr/share/jenkins/ref/plugins.txt)' returned a non-zero code: 1
Build step 'Execute shell' marked build as failure</code>```

I have used "--no-cache" option in docker build, but didn't work.
Here is the docker build command I used:

docker build --build-arg http_proxy=$http_proxy --build-arg https_proxy=$https_proxy --no-cache -t ci/jenkins .```
</div>
</div>
</p>

<p>Has anyone ran into this problem before?</p>

<p>Update: Here is my plugins.txt</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>bouncycastle API Plugin (bouncycastle-api): 2.16.1
Pipeline: Groovy (workflow-cps): 2.33
Folders Plugin (cloudbees-folder): 6.0.4
Structs Plugin (structs): 1.7
Branch API Plugin (branch-api): 2.0.9
JUnit Plugin (junit): 1.20
OWASP Markup Formatter Plugin (antisamy-markup-formatter): 1.5
Docker Commons Plugin (docker-commons): 1.6
PAM Authentication plugin (pam-auth): 1.3
Windows Slaves Plugin (windows-slaves): 1.3.1
Pipeline: Stage View Plugin (pipeline-stage-view): 2.8
Display URL API (display-url-api): 2.0
Mailer Plugin (mailer): 1.20
LDAP Plugin (ldap): 1.15
Docker Pipeline (docker-workflow): 1.11
Token Macro Plugin (token-macro): 2.1
External Monitor Job Type Plugin (external-monitor-job): 1.7
Icon Shim Plugin (icon-shim): 2.0.3
Matrix Authorization Strategy Plugin (matrix-auth): 1.6
Pipeline: Build Step (pipeline-build-step): 2.5
Script Security Plugin (script-security): 1.27
Matrix Project Plugin (matrix-project): 1.11
Pipeline: Model API (pipeline-model-api): 1.1.4
build timeout plugin (build-timeout): 1.18
Credentials Plugin (credentials): 2.1.13
Pipeline: Step API (workflow-step-api): 2.10
Plain Credentials Plugin (plain-credentials): 1.4
SSH Credentials Plugin (ssh-credentials): 1.13
Credentials Binding Plugin (credentials-binding): 1.11
Timestamper (timestamper): 1.8.8
SCM API Plugin (scm-api): 2.1.1
Jackson 2 API Plugin (jackson2-api): 2.7.3
Pipeline: API (workflow-api): 2.16
Pipeline: Supporting APIs (workflow-support): 2.14
Durable Task Plugin (durable-task): 1.13
Pipeline: Nodes and Processes (workflow-durable-task-step): 2.11
Git client plugin (git-client): 2.4.6
Resource Disposer Plugin (resource-disposer): 0.6
GitHub API Plugin (github-api): 1.85.1
Workspace Cleanup Plugin (ws-cleanup): 0.33
Ant Plugin (ant): 1.5
Gradle Plugin (gradle): 1.26
Pipeline: SCM Step (workflow-scm-step): 2.4
Pipeline: Milestone Step (pipeline-milestone-step): 1.3.1
JavaScript GUI Lib: jQuery bundles (jQuery and jQuery UI) plugin (jquery-detached): 1.2.1
GIT server Plugin (git-server): 1.7
Pipeline: Input Step (pipeline-input-step): 2.7
Git plugin (git): 3.3.0
JavaScript GUI Lib: ACE Editor bundle plugin (ace-editor): 1.1
Pipeline: Shared Groovy Libraries (workflow-cps-global-lib): 2.8
Pipeline: Stage Step (pipeline-stage-step): 2.2
Pipeline: Job (workflow-job): 2.11
Pipeline Graph Analysis Plugin (pipeline-graph-analysis): 1.3
Pipeline: REST API Plugin (pipeline-rest-api): 2.8
GitHub plugin (github): 1.27.0
JavaScript GUI Lib: Handlebars bundle plugin (handlebars): 1.1.1
JavaScript GUI Lib: Moment.js bundle plugin (momentjs): 1.1.1
Pipeline: Declarative Extension Points API (pipeline-model-extensions): 1.1.4
Pipeline: Multibranch (workflow-multibranch): 2.15
Authentication Tokens API Plugin (authentication-tokens): 1.3
Pipeline: Stage Tags Metadata (pipeline-stage-tags-metadata): 1.1.4
Pipeline: Declarative Agent API (pipeline-model-declarative-agent): 1.1.1
Pipeline: Basic Steps (workflow-basic-steps): 2.5
Pipeline: Model Definition (pipeline-model-definition): 1.1.4
Pipeline (workflow-aggregator): 2.5
GitHub Branch Source Plugin (github-branch-source): 2.0.6
Pipeline: GitHub Groovy Libraries (pipeline-github-lib): 1.0
GitHub Organization Folder Plugin (github-organization-folder): 1.6
MapDB API Plugin (mapdb-api): 1.0.9.0
Subversion Plug-in (subversion): 2.7.2
SSH Slaves plugin (ssh-slaves): 1.17
Email Extension Plugin (email-ext): 2.57.2
Docker Slaves Plugin (docker-slaves): 1.0.6
Docker plugin (docker-plugin): 0.16.1</code>```

答:
You need your text file like

```<code>bouncycastle-api:2.16.1
workflow-cps:2.33
</code>```

as per

```<code>RUN /usr/local/bin/install-plugins.sh \
   docker-slaves \
   github-branch-source:1.8
</code>```

Tweaked from here

Body:
I am using the following Dockerfile to build a Jenkins Image with pre-installed plugins.

FROM jenkins

USER root
RUN apt-get -yqq update
RUN curl -sSL https://get.docker.com/ | sh
RUN usermod -aG docker jenkins

COPY plugins.txt /usr/share/jenkins/ref/plugins.txt
RUN /usr/local/bin/install-plugins.sh $(cat /usr/share/jenkins/ref/plugins.txt)

USER jenkins

However, ran into an error about an existing plugin.lock problem.

Step 10/11 : RUN /usr/local/bin/install-plugins.sh $(cat /usr/share/jenkins/ref/plugins.txt)
 ---> Running in 0823515c2574
Creating initial locks...
[91mmkdir: cannot create directory ‘/usr/share/jenkins/ref/plugins/Plugin.lock’: File exists
[0mThe command '/bin/sh -c /usr/local/bin/install-plugins.sh $(cat /usr/share/jenkins/ref/plugins.txt)' returned a non-zero code: 1
Build step 'Execute shell' marked build as failure

I have used "--no-cache" option in docker build, but didn't work.
Here is the docker build command I used:

docker build --build-arg http_proxy=$http_proxy --build-arg https_proxy=$https_proxy --no-cache -t ci/jenkins .

Has anyone ran into this problem before?

Update: Here is my plugins.txt

bouncycastle API Plugin (bouncycastle-api): 2.16.1
Pipeline: Groovy (workflow-cps): 2.33
Folders Plugin (cloudbees-folder): 6.0.4
Structs Plugin (structs): 1.7
Branch API Plugin (branch-api): 2.0.9
JUnit Plugin (junit): 1.20
OWASP Markup Formatter Plugin (antisamy-markup-formatter): 1.5
Docker Commons Plugin (docker-commons): 1.6
PAM Authentication plugin (pam-auth): 1.3
Windows Slaves Plugin (windows-slaves): 1.3.1
Pipeline: Stage View Plugin (pipeline-stage-view): 2.8
Display URL API (display-url-api): 2.0
Mailer Plugin (mailer): 1.20
LDAP Plugin (ldap): 1.15
Docker Pipeline (docker-workflow): 1.11
Token Macro Plugin (token-macro): 2.1
External Monitor Job Type Plugin (external-monitor-job): 1.7
Icon Shim Plugin (icon-shim): 2.0.3
Matrix Authorization Strategy Plugin (matrix-auth): 1.6
Pipeline: Build Step (pipeline-build-step): 2.5
Script Security Plugin (script-security): 1.27
Matrix Project Plugin (matrix-project): 1.11
Pipeline: Model API (pipeline-model-api): 1.1.4
build timeout plugin (build-timeout): 1.18
Credentials Plugin (credentials): 2.1.13
Pipeline: Step API (workflow-step-api): 2.10
Plain Credentials Plugin (plain-credentials): 1.4
SSH Credentials Plugin (ssh-credentials): 1.13
Credentials Binding Plugin (credentials-binding): 1.11
Timestamper (timestamper): 1.8.8
SCM API Plugin (scm-api): 2.1.1
Jackson 2 API Plugin (jackson2-api): 2.7.3
Pipeline: API (workflow-api): 2.16
Pipeline: Supporting APIs (workflow-support): 2.14
Durable Task Plugin (durable-task): 1.13
Pipeline: Nodes and Processes (workflow-durable-task-step): 2.11
Git client plugin (git-client): 2.4.6
Resource Disposer Plugin (resource-disposer): 0.6
GitHub API Plugin (github-api): 1.85.1
Workspace Cleanup Plugin (ws-cleanup): 0.33
Ant Plugin (ant): 1.5
Gradle Plugin (gradle): 1.26
Pipeline: SCM Step (workflow-scm-step): 2.4
Pipeline: Milestone Step (pipeline-milestone-step): 1.3.1
JavaScript GUI Lib: jQuery bundles (jQuery and jQuery UI) plugin (jquery-detached): 1.2.1
GIT server Plugin (git-server): 1.7
Pipeline: Input Step (pipeline-input-step): 2.7
Git plugin (git): 3.3.0
JavaScript GUI Lib: ACE Editor bundle plugin (ace-editor): 1.1
Pipeline: Shared Groovy Libraries (workflow-cps-global-lib): 2.8
Pipeline: Stage Step (pipeline-stage-step): 2.2
Pipeline: Job (workflow-job): 2.11
Pipeline Graph Analysis Plugin (pipeline-graph-analysis): 1.3
Pipeline: REST API Plugin (pipeline-rest-api): 2.8
GitHub plugin (github): 1.27.0
JavaScript GUI Lib: Handlebars bundle plugin (handlebars): 1.1.1
JavaScript GUI Lib: Moment.js bundle plugin (momentjs): 1.1.1
Pipeline: Declarative Extension Points API (pipeline-model-extensions): 1.1.4
Pipeline: Multibranch (workflow-multibranch): 2.15
Authentication Tokens API Plugin (authentication-tokens): 1.3
Pipeline: Stage Tags Metadata (pipeline-stage-tags-metadata): 1.1.4
Pipeline: Declarative Agent API (pipeline-model-declarative-agent): 1.1.1
Pipeline: Basic Steps (workflow-basic-steps): 2.5
Pipeline: Model Definition (pipeline-model-definition): 1.1.4
Pipeline (workflow-aggregator): 2.5
GitHub Branch Source Plugin (github-branch-source): 2.0.6
Pipeline: GitHub Groovy Libraries (pipeline-github-lib): 1.0
GitHub Organization Folder Plugin (github-organization-folder): 1.6
MapDB API Plugin (mapdb-api): 1.0.9.0
Subversion Plug-in (subversion): 2.7.2
SSH Slaves plugin (ssh-slaves): 1.17
Email Extension Plugin (email-ext): 2.57.2
Docker Slaves Plugin (docker-slaves): 1.0.6
Docker plugin (docker-plugin): 0.16.1

Body:
You need your text file like

bouncycastle-api:2.16.1
workflow-cps:2.33

as per

RUN /usr/local/bin/install-plugins.sh \
   docker-slaves \
   github-branch-source:1.8

Tweaked from here


问:
Disable springframework logging
I want to disable console logging messages spawned by org.springframework.* stuff. My log4j.xml looks like this

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC
  "-//APACHE//DTD LOG4J 1.2//EN"
  "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern" value="%d %-5p  [%c{1}] %m %n" />
        </layout>
    </appender>

    <logger name="org.springframework">
        <level value="off" />
    </logger>

    <logger name="com.myapp">
        <level value="all" />
        <appender-ref ref="consoleAppender"/>
    </logger>

</log4j:configuration>
</code>```

But it doesn't work. I still see a lot of DEBUG, INFO messages produces by org.springframework on my console.

What should I change to make it works?

答:
Add JCL over SLF4J dependency to redirect logs from commons-logging to SLF4J:</p>

```<code>    <jcl.over.slf4j.version>1.7.13</jcl.over.slf4j.version>
    ...
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>${jcl.over.slf4j.version}</version>
    </dependency>
</code>```

Title: Disable springframework logging

Body:
I want to disable console logging messages spawned by org.springframework.* stuff. My log4j.xml looks like this

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC
  "-//APACHE//DTD LOG4J 1.2//EN"
  "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
          <param name="ConversionPattern" value="%d %-5p  [%c{1}] %m %n" />
        </layout>
    </appender>

    <logger name="org.springframework">
        <level value="off" />
    </logger>

    <logger name="com.myapp">
        <level value="all" />
        <appender-ref ref="consoleAppender"/>
    </logger>

</log4j:configuration>

But it doesn't work. I still see a lot of DEBUG, INFO messages produces by org.springframework on my console.

What should I change to make it works?

Body:
Add JCL over SLF4J dependency to redirect logs from commons-logging to SLF4J:

    <jcl.over.slf4j.version>1.7.13</jcl.over.slf4j.version>
    ...
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>${jcl.over.slf4j.version}</version>
    </dependency>


问:
Make notification when app is closed
I have separate API for my Android app and I'm using Restful services for connecting my API. For now, I need to show notification even app is closed by the way of connecting my backend using the Restful method because all notification messages are, will get only the way of calling the API.
What is the correct implementation to solve this problem?</p>

答:
You can use push notifications for this. Integrate with FCM that will allow your app to get notification from backend even when app is closed.

You can follow below links for this

https://firebase.google.com/docs/cloud-messaging/android/client
https://firebase.google.com/docs/cloud-messaging/

Title: Make notification when app is closed


问:
How can I convert a .py to .exe for Python?
I'm trying to convert a fairly simple Python program to an executable and couldn't find what I was looking for, so I have a few questions (I'm running Python 3.6):

The methods of doing this that I have found so far are as follows

downloading an old version of Python and using pyinstaller/py2exe

setting up a virtual environment in Python 3.6 that will allow me to do 1.

downloading a Python to C++ converter and using that.

Here is what I've tried/what problems I've run into.

I installed pyinstaller before the required download before it (pypi-something) so it did not work. After downloading the prerequisite file, pyinstaller still does not recognize it.

If I'm setting up a virtualenv in Python 2.7, do I actually need to have Python 2.7 installed?

similarly, the only python to C++ converters I see work only up until Python 3.5 - do I need to download and use this version if attempting this?

答:
Steps to convert .py to .exe in Python 3.6

Install Python 3.6.

Install cx_Freeze, (open your command prompt and type pip install cx_Freeze.

Install idna, (open your command prompt and type pip install idna.

Write a .py program named myfirstprog.py.

Create a new python file named setup.py on the current directory of your script.

In the setup.py file, copy the code below and save it.

With shift pressed right click on the same directory, so you are able to open a command prompt window.

In the prompt, type python setup.py build

If your script is error free, then there will be no problem on creating application.

Check the newly created folder build. It has another folder in it. Within that folder you can find your application. Run it. Make yourself happy.

See the original script in my blog.

setup.py:

from cx_Freeze import setup, Executable

base = None

executables = [Executable("myfirstprog.py", base=base)]

packages = ["idna"]
options = {
    'build_exe': {
        'packages':packages,
    },
}

setup(
    name = "<any name>",
    options = options,
    version = "<any number>",
    description = '<any description>',
    executables = executables
)
```

EDIT:

be sure that instead of myfirstprog.py you should put your .pyextension file name as created in step 4;

you should include each imported package in your .py into packages list (ex: packages = ["idna", "os","sys"])

any name, any number, any description in setup.py file should not remain the same, you should change it accordingly (ex:name = "<first_ever>", version = "0.11", description = '' )

the imported packages must be installed before you start step 8.

ContentLicense: CC BY-SA 4.0

Body:
Steps to convert .py to .exe in Python 3.6

Install Python 3.6.

Install cx_Freeze, (open your command prompt and type pip install cx_Freeze.

Install idna, (open your command prompt and type pip install idna.

Write a .py program named myfirstprog.py.

Create a new python file named setup.py on the current directory of your script.

In the setup.py file, copy the code below and save it.

With shift pressed right click on the same directory, so you are able to open a command prompt window.

In the prompt, type python setup.py build

If your script is error free, then there will be no problem on creating application.

Check the newly created folder build. It has another folder in it. Within that folder you can find your application. Run it. Make yourself happy.

See the original script in my blog.

setup.py:

from cx_Freeze import setup, Executable

base = None

executables = [Executable("myfirstprog.py", base=base)]

packages = ["idna"]
options = {
    'build_exe': {
        'packages':packages,
    },
}

setup(
    name = "<any name>",
    options = options,
    version = "<any number>",
    description = '<any description>',
    executables = executables
)

EDIT:

be sure that instead of myfirstprog.py you should put your .pyextension file name as created in step 4;

you should include each imported package in your .py into packages list (ex: packages = ["idna", "os","sys"])

any name, any number, any description in setup.py file should not remain the same, you should change it accordingly (ex:name = "<first_ever>", version = "0.11", description = '' )

the imported packages must be installed before you start step 8.


问:
Unable to create or switch to new tab in Selenium Webdriver with JAVA on MAC
I've tried a different options just to open new tab but all of them lead to the same result : sending char "t" to google search field.
The goal in my real test is to switch between tabs in browser, but I am unable even open new one.

Very simple test

```<code>    public class LoginPhp2 {

        @Test
        public void testGoogle() {
            WebDriver driver = new SafariDriver();
            driver.get("https://www.google.com");
            //driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND + "t");
            Actions action= new Actions(driver);
           action.keyDown(Keys.COMMAND).sendKeys("t").build().perform();
            //action.keyDown(Keys.COMMAND).sendKeys("t").keyUp(Keys.COMMAND).build().perform();

        }
    }
</code>```

答:
I have followed the approach suggested earlier:

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("window.open();");

This is opening new tab in the same window. I have tried it on my MAC machine

Body:
I've tried a different options just to open new tab but all of them lead to the same result : sending char "t" to google search field.
The goal in my real test is to switch between tabs in browser, but I am unable even open new one.

Very simple test

    public class LoginPhp2 {

        @Test
        public void testGoogle() {
            WebDriver driver = new SafariDriver();
            driver.get("https://www.google.com");
            //driver.findElement(By.cssSelector("body")).sendKeys(Keys.COMMAND + "t");
            Actions action= new Actions(driver);
           action.keyDown(Keys.COMMAND).sendKeys("t").build().perform();
            //action.keyDown(Keys.COMMAND).sendKeys("t").keyUp(Keys.COMMAND).build().perform();

        }
    }


问:
For each loop takes all elements of array Laravel
I am having a issue here and I am not quite sure what is wrong. I make a query where I get Business categories which is serialized (categories), then for each of them I try to unserialize, but as result I get only the unserialized categories of the first item.

Here is my code:

```<code>$businesses= Businesses::where('visible' , 'yes')->where( 'delete' , 'no')->select('categories')->get();
        foreach ($businesses as $key => $business) {

            $categories = unserialize($business->categories);

            return view('test',['categories'=>$categories]);
        }
</code>```

答:
Please check if this helps you,

```<code>$businesses= Businesses::where('visible' , 'yes')->where( 'delete' , 'no')->select('categories')->get();
$categories = array();
foreach($businesses as $key => $business) {
   $categories[] = unserialize($business->categories);
}
return view('test',['categories'=>$categories]);
</code>```

Issue: you are returning the categories at the first iteration in foreach loop.

Suggestion: you can make an associative array in the foreach loop & return to view after the loop. Then in view, you can make use of the categories

Body:
I am having a issue here and I am not quite sure what is wrong. I make a query where I get Business categories which is serialized (categories), then for each of them I try to unserialize, but as result I get only the unserialized categories of the first item.

Here is my code:

$businesses= Businesses::where('visible' , 'yes')->where( 'delete' , 'no')->select('categories')->get();
        foreach ($businesses as $key => $business) {

            $categories = unserialize($business->categories);

            return view('test',['categories'=>$categories]);
        }

Body:
Please check if this helps you,

$businesses= Businesses::where('visible' , 'yes')->where( 'delete' , 'no')->select('categories')->get();
$categories = array();
foreach($businesses as $key => $business) {
   $categories[] = unserialize($business->categories);
}
return view('test',['categories'=>$categories]);

Issue: you are returning the categories at the first iteration in foreach loop.

Suggestion: you can make an associative array in the foreach loop & return to view after the loop. Then in view, you can make use of the categories


问:
Download file using ASP.NET Core
I´m trying to download a excel file after the file is created and I´m having the following error:

UnauthorizedAccessException: Access to the path 'C:\Users\user_name\Documents\Visual Studio 2015\Projects\Project_Name\src\Project_Name\wwwroot' is denied.

The file is created successfully, the problem is in the download method.

I already try to solve this error doing the following actions:

Open VS as Admin

Add IIS_IUSR user to the project folder

Here´s the code:

```<code>    private readonly IHostingEnvironment _hostingEnvironment;
    public EmployeeController(ApplicationDbContext context, IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }
    public void createFile()
    {
        string wwwrootPath = _hostingEnvironment.WebRootPath;
        string fileName = @"Employees.xlsx";
        FileInfo file = new FileInfo(Path.Combine(wwwrootPath, fileName));

        if (file.Exists)
        {
            file.Delete();
            file = new FileInfo(Path.Combine(wwwrootPath, fileName));
        }
        using (ExcelPackage package = new ExcelPackage(file))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
            worksheet.Cells[1, 1].Value = "ID";
            worksheet.Cells[1, 2].Value = "Name";
            worksheet.Cells[1, 3].Value = "Gender";
            worksheet.Cells[1, 4].Value = "Salary (in $)";

            worksheet.Cells["A2"].Value = 1000;
            worksheet.Cells["B2"].Value = "Jon";
            worksheet.Cells["C2"].Value = "M";
            worksheet.Cells["D2"].Value = 5000;

            worksheet.Cells["A3"].Value = 1001;
            worksheet.Cells["B3"].Value = "Graham";
            worksheet.Cells["C3"].Value = "M";
            worksheet.Cells["D3"].Value = 10000;

            worksheet.Cells["A4"].Value = 1002;
            worksheet.Cells["B4"].Value = "Jenny";
            worksheet.Cells["C4"].Value = "F";
            worksheet.Cells["D4"].Value = 5000;

            package.Save();
            downloadFile(wwwrootPath);

        }

}
    public FileResult downloadFile(string filePath)
    {
        var mimeType = "application/vnd.ms-excel";
        FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

        return File(fileStream, mimeType, "Employees.xlsx");
    }
</code>```

Note: I didn´t make the deploy of the project in IIS.

Best Regards

答:
In ASP.NET Core you should use PhysicalFileProvider class to access the actual system's files. If you look into File providers section in the documentation:

The PhysicalFileProvider provides access to the physical file system. It wraps the System.IO.File type (for the physical provider), scoping all paths to a directory and its children. This scoping limits access to a certain directory and its children, preventing access to the file system outside of this boundary.

The following should work for you:

```<code>string wwwrootPath = _hostingEnvironment.WebRootPath;
string fileName = @"Employees.xlsx";

IFileProvider provider = new PhysicalFileProvider(wwwrootPath);
IFileInfo fileInfo = provider.GetFileInfo(fileName);
var readStream = fileInfo.CreateReadStream();
</code>```

//  PhysicalFileProvider.GetFileInfo returns instance of PhysicalFileInfo that provides implementation of IFileInfo.CreateReadStream method.

Title: Download file using ASP.NET Core

Body:
I´m trying to download a excel file after the file is created and I´m having the following error:

UnauthorizedAccessException: Access to the path 'C:\Users\user_name\Documents\Visual Studio 2015\Projects\Project_Name\src\Project_Name\wwwroot' is denied.

The file is created successfully, the problem is in the download method.

I already try to solve this error doing the following actions:

Open VS as Admin

Add IIS_IUSR user to the project folder

Here´s the code:

    private readonly IHostingEnvironment _hostingEnvironment;
    public EmployeeController(ApplicationDbContext context, IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }
    public void createFile()
    {
        string wwwrootPath = _hostingEnvironment.WebRootPath;
        string fileName = @"Employees.xlsx";
        FileInfo file = new FileInfo(Path.Combine(wwwrootPath, fileName));

        if (file.Exists)
        {
            file.Delete();
            file = new FileInfo(Path.Combine(wwwrootPath, fileName));
        }
        using (ExcelPackage package = new ExcelPackage(file))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
            worksheet.Cells[1, 1].Value = "ID";
            worksheet.Cells[1, 2].Value = "Name";
            worksheet.Cells[1, 3].Value = "Gender";
            worksheet.Cells[1, 4].Value = "Salary (in $)";

            worksheet.Cells["A2"].Value = 1000;
            worksheet.Cells["B2"].Value = "Jon";
            worksheet.Cells["C2"].Value = "M";
            worksheet.Cells["D2"].Value = 5000;

            worksheet.Cells["A3"].Value = 1001;
            worksheet.Cells["B3"].Value = "Graham";
            worksheet.Cells["C3"].Value = "M";
            worksheet.Cells["D3"].Value = 10000;

            worksheet.Cells["A4"].Value = 1002;
            worksheet.Cells["B4"].Value = "Jenny";
            worksheet.Cells["C4"].Value = "F";
            worksheet.Cells["D4"].Value = 5000;

            package.Save();
            downloadFile(wwwrootPath);

        }

}
    public FileResult downloadFile(string filePath)
    {
        var mimeType = "application/vnd.ms-excel";
        FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

        return File(fileStream, mimeType, "Employees.xlsx");
    }

Note: I didn´t make the deploy of the project in IIS.

Best Regards

Body:
In ASP.NET Core you should use PhysicalFileProvider class to access the actual system's files. If you look into File providers section in the documentation:

The PhysicalFileProvider provides access to the physical file system. It wraps the System.IO.File type (for the physical provider), scoping all paths to a directory and its children. This scoping limits access to a certain directory and its children, preventing access to the file system outside of this boundary.

The following should work for you:

string wwwrootPath = _hostingEnvironment.WebRootPath;
string fileName = @"Employees.xlsx";

IFileProvider provider = new PhysicalFileProvider(wwwrootPath);
IFileInfo fileInfo = provider.GetFileInfo(fileName);
var readStream = fileInfo.CreateReadStream();

//  PhysicalFileProvider.GetFileInfo returns instance of PhysicalFileInfo that provides implementation of IFileInfo.CreateReadStream method.


问:
How Can i subtract two columns in different tables in SQL
I want to enter in a query the subtract between two columns in different tables it keeps saying error ...</p>

```<code>SELECT FlightDate,
       Plane,
       Destination,
       Capacity
FROM
       FlightSchedule,
       Routes,
       Aircrafts
WHERE
       FlightSchedule.RID=Routes.RouteID
       AND FlightSchedule.Plane=Aircrafts.AcID
       AND (SELECT SUM(Capacity)
            FROM Aircrafts)
            -
           (SELECT Class , count(*)
           FROM Tickets);
</code>```

答:
I would split this up into 2 parts. First get the data you need, then perform the math. You are also using old SQL syntax. You should re-format using the new JOIN syntax. It's also easier to read.

1st declare a table to hold you flight schedule and aircraft info.

```<code>Declare @AIRCRAFTCAPACITY Table
(
    [FlightDate] [datetime] NOT NULL,
    [Plane] [varchar](50) NOT NULL,
    [Destination] [varchar](50) NOT NULL,
    [Capacity] [INT] NOT NULL,
    [NoOfSeatsRemaining] [INT] NULL
);
</code>```

Then insert the data you need.

```<code>INSERT @AIRCRAFTCAPACITY
(
    [FlightDate],
    [Plane],
    [Destination],
    [Capacity]
)
SELECT  FS.FlightDate,
        A.Plane,
        FS.Destination,
        A.Capacity
FROM
        FlightSchedule FS
INNER
JOIN    Routes R
ON
        FS.RID = R.RouteID
INNER
JOIN    Aircrafts A
ON
        FS.Plane = A.AcID
</code>```

Now perform the math to calculate the remaining capacity. I've made an assumption that you are doing this for a particular route. But I'm sure you can adjust your SQL accordingly.

```<code>UPDATE  @AIRCRAFTCAPACITY
SET
        [NoOfSeatsRemaining] = [Capacity] - T.TICKETS_SOLD
FROM
        @AIRCRAFTCAPACITY A
INNER
JOIN
        (
            SELECT ROUTEID, COUNT(ROUTEID) AS TICKETS_SOLD
            FROM
                   Tickets T1
            WHERE
                   T1.ROUTEID = A.ROUTEID
            GROUP
            BY     ROUTEID
        ) T
ON
        A.ROUTEID = T.ROUTEID
</code>```

Apolgies if the syntax is a little off as it's hard to construct SQL when you dont have the underlying tables.

But hopefully it will help.

Body:
I want to enter in a query the subtract between two columns in different tables it keeps saying error ...

SELECT FlightDate,
       Plane,
       Destination,
       Capacity
FROM
       FlightSchedule,
       Routes,
       Aircrafts
WHERE
       FlightSchedule.RID=Routes.RouteID
       AND FlightSchedule.Plane=Aircrafts.AcID
       AND (SELECT SUM(Capacity)
            FROM Aircrafts)
            -
           (SELECT Class , count(*)
           FROM Tickets);

Body:
I would split this up into 2 parts. First get the data you need, then perform the math. You are also using old SQL syntax. You should re-format using the new JOIN syntax. It's also easier to read.

1st declare a table to hold you flight schedule and aircraft info.

Declare @AIRCRAFTCAPACITY Table
(
    [FlightDate] [datetime] NOT NULL,
    [Plane] [varchar](50) NOT NULL,
    [Destination] [varchar](50) NOT NULL,
    [Capacity] [INT] NOT NULL,
    [NoOfSeatsRemaining] [INT] NULL
);

Then insert the data you need.

INSERT @AIRCRAFTCAPACITY
(
    [FlightDate],
    [Plane],
    [Destination],
    [Capacity]
)
SELECT  FS.FlightDate,
        A.Plane,
        FS.Destination,
        A.Capacity
FROM
        FlightSchedule FS
INNER
JOIN    Routes R
ON
        FS.RID = R.RouteID
INNER
JOIN    Aircrafts A
ON
        FS.Plane = A.AcID

Now perform the math to calculate the remaining capacity. I've made an assumption that you are doing this for a particular route. But I'm sure you can adjust your SQL accordingly.

UPDATE  @AIRCRAFTCAPACITY
SET
        [NoOfSeatsRemaining] = [Capacity] - T.TICKETS_SOLD
FROM
        @AIRCRAFTCAPACITY A
INNER
JOIN
        (
            SELECT ROUTEID, COUNT(ROUTEID) AS TICKETS_SOLD
            FROM
                   Tickets T1
            WHERE
                   T1.ROUTEID = A.ROUTEID
            GROUP
            BY     ROUTEID
        ) T
ON
        A.ROUTEID = T.ROUTEID

Apolgies if the syntax is a little off as it's hard to construct SQL when you dont have the underlying tables.

But hopefully it will help.


问:
Javascript: variable is not undefined but while returning, being returned undefined
In the snippet below, before return(res) , I log it, and it's not undefined

but somehow, it's being returned as undefined.

What am I doing wrong?

filterData = (inputData, searchedKey) => {
  inputData.forEach((data, index) => {
    if(data){
      if(data.hasOwnProperty(searchedKey)){
        const res = data[searchedKey]
        console.log(res) /// logs the results
        return(res) /// returns undefined
      }
      var dataToProcess = [];

      var fieldKeys = Object.keys(data)
      fieldKeys = fieldKeys.filter((field, index) => !field.includes("#"))
      fieldKeys.forEach((key, index) => {
        dataToProcess.push(data[key]);
      })
      this.filterData(dataToProcess, searchedKey)
    }
  })
}

console.log(this.filterData([{"#name": "foo", "#type": "bar"}], "#type"))```

答:
Some issues:

forEach does not return anything else than undefined, so returning a value in its callback function does not do anything useful.

Your function does not return a value

The return value of the recursive call is not used.

if (data) is not good enough to make sure data is an object. For instance, it would also be true for a non-zero number. Use Object(data) === data instead.

Since there could be multiple matches (in a nested input object), your function should return an array, which is also what someone would expect when seeing your function name. Also the standard array filter method returns an array. So it would be in line with that.

Here is how you could make it work:

var filterData = (inputData, searchedKey) => {
    inputData = inputData.filter( data => Object(data) === data );
    return !inputData.length ? [] :
        inputData.filter( data => data.hasOwnProperty(searchedKey) )
            .map( data => data[searchedKey] )
            // Add the results from recursion:
            .concat(filterData([].concat(...
                inputData.map( data =>
                    Object.keys(data)
                        .filter( key => !key.startsWith("#") )
                        .map( key => data[key] )
                )
            ), searchedKey));
};

var data = [{
    "#name": "foo",
    "#title": "mr",
    "deeper": [{
        "#nope": "bad",
        "deepest": [{
            "nothing_here": null,
            "#type": "deeper bar",
        }]
    }, {
        "#type": "bar",
    }]
}];

console.log(filterData(data, "#type"));```
</div>
</div>
</p>

<p>If you need only the first match, then use this variant:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var filterData = (inputData, searchedKey) => {
    inputData = inputData.filter( data => Object(data) === data );
    var res = inputData.find( data => data.hasOwnProperty(searchedKey) );
    return res !== undefined ? res[searchedKey] :
        // Try in nested objects:
        filterData([].concat(...
            inputData.map( data =>
                Object.keys(data)
                    .filter( key => !key.startsWith("#") )
                    .map( key => data[key] )
            )
        ), searchedKey);
};

var data = [{
    "#name": "foo",
    "#title": "mr",
    "deeper": [{
        "#nope": "bad",
        "deepest": [{
            "nothing_here": null,
            "#type": "deeper bar",
        }]
    }, {
        "#type": "bar",
    }]
}];

console.log(filterData(data, "#type"));</code>```

Body:
Some issues:

forEach does not return anything else than undefined, so returning a value in its callback function does not do anything useful.

Your function does not return a value

The return value of the recursive call is not used.

if (data) is not good enough to make sure data is an object. For instance, it would also be true for a non-zero number. Use Object(data) === data instead.

Since there could be multiple matches (in a nested input object), your function should return an array, which is also what someone would expect when seeing your function name. Also the standard array filter method returns an array. So it would be in line with that.

Here is how you could make it work:

var filterData = (inputData, searchedKey) => {
    inputData = inputData.filter( data => Object(data) === data );
    return !inputData.length ? [] :
        inputData.filter( data => data.hasOwnProperty(searchedKey) )
            .map( data => data[searchedKey] )
            // Add the results from recursion:
            .concat(filterData([].concat(...
                inputData.map( data =>
                    Object.keys(data)
                        .filter( key => !key.startsWith("#") )
                        .map( key => data[key] )
                )
            ), searchedKey));
};

var data = [{
    "#name": "foo",
    "#title": "mr",
    "deeper": [{
        "#nope": "bad",
        "deepest": [{
            "nothing_here": null,
            "#type": "deeper bar",
        }]
    }, {
        "#type": "bar",
    }]
}];

console.log(filterData(data, "#type"));

If you need only the first match, then use this variant:

var filterData = (inputData, searchedKey) => {
    inputData = inputData.filter( data => Object(data) === data );
    var res = inputData.find( data => data.hasOwnProperty(searchedKey) );
    return res !== undefined ? res[searchedKey] :
        // Try in nested objects:
        filterData([].concat(...
            inputData.map( data =>
                Object.keys(data)
                    .filter( key => !key.startsWith("#") )
                    .map( key => data[key] )
            )
        ), searchedKey);
};

var data = [{
    "#name": "foo",
    "#title": "mr",
    "deeper": [{
        "#nope": "bad",
        "deepest": [{
            "nothing_here": null,
            "#type": "deeper bar",
        }]
    }, {
        "#type": "bar",
    }]
}];

console.log(filterData(data, "#type"));


问:
To subtract two dates without Using DateAdd Function or DateDiff Function
How i got this output, can you please explain the reason behind it?

```<code>declare @a datetime = '2017-06-08 16:02:22.467',
        @b datetime = '2017-10-23 00:00:00.000'

select DAY(@a - @b)

select @a - @b
</code>```

Output:

```<code>17
1899-08-17 16:02:22.467
</code>```

答: This will subtract the two date and will add it to Minimum Date in SQL which is '1900-01-01 00:00:00.000'. So after subtracting both dates and getting the difference, it will add it in subsequent minimum date which is '1900-01-01 00:00:00.000'.</p>

Body:
How i got this output, can you please explain the reason behind it?

declare @a datetime = '2017-06-08 16:02:22.467',
        @b datetime = '2017-10-23 00:00:00.000'

select DAY(@a - @b)

select @a - @b

Output:

17
1899-08-17 16:02:22.467


问:
ASP.NET Event Subs in VS 2010
I've got an issue involving a website that I have been using VS 2008 for, until a few months ago when I bought VS 2010.  I did not 'upgrade' the website -- VS 2010 asked me if I wanted to, and I said 'no'.  I ran into a problem the first time I tried to use VS 2010 to edit this website -- found a work-around that has been working for the past 3 months.  But now, all of a sudden, the work-around seem to be failing.

When working on a website from the design window (either 2008 or 2010), you can double-click, for example, a button and it will open the code-behind for the button's on-click event.

For some reason that I have not figured out yet, VS 2010 decides to make a brand-new event sub, in addition to the one I've already got.  For example, I've got a button with an on-click event (Created in VS 2008) like this:

```<code>Protected Sub btn_next_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_next.Click
...
End Sub
</code>```

As soon as I open the website in VS2010, and double-click the button in the design window, it creates a brand new event (duplicating all of the code inside the 'sub / end sub') like this:

```<code>Protected Sub btn_next_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_next.Click
...
End Sub
</code>```

(notice that in the duplicate event sub it changes the name of the sub by adding a '1')

If I delete the duplicate sub, it just comes back next time I double-click the button in the designer.

Not to mention, if I delete the duplicate sub and try to build the website, I get an error telling me it can't find 'Sub btn_next_Click1...'.  (I've verified that the button's markup does not have an 'onclick=...' attribute that would force it to look for this specific sub.

Finally, If I leave the duplicate sub there...the event is handled twice (the original sub runs once, and the duplicate sub runs once, since they both 'handle' the same event).

My work-around was to delete the original sub.  That seemed to work for a time.  But ever since I re-published the app yesterday, the duplicate sub has started running twice, even though the original sub has been deleted.  I've verified this by adding stops in the debugger, and then stepping-through each line.  This work-around, which has worked for a few months, all of a sudden isn't working.  Whatever I've done to cause it, I can't see it.

BTW -- the 're-publish' I'm referring two was for a different page int he website.  The page that's got the problem I'm talking about in this post hasn't been modified for months, and has been working fine all this time.

Any experience with this?  Am I going to have to re-code my app from scratch in VS 2010?

答:
I don't think this is related to moving from 2008 to 2010. I get this from time to time as a result of edits that confuse the IDE.

The answer is to delete the original. The reason a "1" is appended is because one without the "1" exists. Deleting the original fixes that.

If that causes errors, you may need to edit the designer code directly.

ContentLicense: CC BY-SA 2.5

Title: ASP.NET Event Subs in VS 2010

Body:
I've got an issue involving a website that I have been using VS 2008 for, until a few months ago when I bought VS 2010.  I did not 'upgrade' the website -- VS 2010 asked me if I wanted to, and I said 'no'.  I ran into a problem the first time I tried to use VS 2010 to edit this website -- found a work-around that has been working for the past 3 months.  But now, all of a sudden, the work-around seem to be failing.

When working on a website from the design window (either 2008 or 2010), you can double-click, for example, a button and it will open the code-behind for the button's on-click event.

For some reason that I have not figured out yet, VS 2010 decides to make a brand-new event sub, in addition to the one I've already got.  For example, I've got a button with an on-click event (Created in VS 2008) like this:

Protected Sub btn_next_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_next.Click
...
End Sub

As soon as I open the website in VS2010, and double-click the button in the design window, it creates a brand new event (duplicating all of the code inside the 'sub / end sub') like this:

Protected Sub btn_next_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_next.Click
...
End Sub

(notice that in the duplicate event sub it changes the name of the sub by adding a '1')

If I delete the duplicate sub, it just comes back next time I double-click the button in the designer.

Not to mention, if I delete the duplicate sub and try to build the website, I get an error telling me it can't find 'Sub btn_next_Click1...'.  (I've verified that the button's markup does not have an 'onclick=...' attribute that would force it to look for this specific sub.

Finally, If I leave the duplicate sub there...the event is handled twice (the original sub runs once, and the duplicate sub runs once, since they both 'handle' the same event).

My work-around was to delete the original sub.  That seemed to work for a time.  But ever since I re-published the app yesterday, the duplicate sub has started running twice, even though the original sub has been deleted.  I've verified this by adding stops in the debugger, and then stepping-through each line.  This work-around, which has worked for a few months, all of a sudden isn't working.  Whatever I've done to cause it, I can't see it.

BTW -- the 're-publish' I'm referring two was for a different page int he website.  The page that's got the problem I'm talking about in this post hasn't been modified for months, and has been working fine all this time.

Any experience with this?  Am I going to have to re-code my app from scratch in VS 2010?


问:
JavaScript: how to handle all the errors except ones which can be produced by mistype
Consider a code sample:

```<code>const someThing = { f: function() {} }
try {
    something.f() // there is a mistype
} catch(e) {
    // some error handling specific to function f
}
</code>```

So, I want to not handle all the errors which can be produced by my mistype like: ReferenceError, TypeError and also I don't want to handle AssertionError.

Is there any idiomatic way to do that?

答:
You could do it like this:

var ignoredErrors = [TypeError, ReferenceError];

function handleError (e) {
  for (var index in ignoredErrors) {
    if (e instanceof ignoredErrors[index]) {
      return;
    }
  }
  console.log('A "real" error occured:', e.message);
}

const someThing = { f: function() {} }
try {
  something.f(); // ReferenceError: ignored
} catch(e) {
  handleError(e);
}

try {
  eval('()'); // SyntaxError: not ignored
} catch(e) {
  handleError(e);
}```

But do you really want to have that? Do you want to ignore your mistakes instead of solving the errors in your program?

Body:
Consider a code sample:

const someThing = { f: function() {} }
try {
    something.f() // there is a mistype
} catch(e) {
    // some error handling specific to function f
}

So, I want to not handle all the errors which can be produced by my mistype like: ReferenceError, TypeError and also I don't want to handle AssertionError.

Is there any idiomatic way to do that?

Body:
You could do it like this:

var ignoredErrors = [TypeError, ReferenceError];

function handleError (e) {
  for (var index in ignoredErrors) {
    if (e instanceof ignoredErrors[index]) {
      return;
    }
  }
  console.log('A "real" error occured:', e.message);
}

const someThing = { f: function() {} }
try {
  something.f(); // ReferenceError: ignored
} catch(e) {
  handleError(e);
}

try {
  eval('()'); // SyntaxError: not ignored
} catch(e) {
  handleError(e);
}

But do you really want to have that? Do you want to ignore your mistakes instead of solving the errors in your program?


问:
Correct way to use parameters within Groovy SQL
I am using Groovy SQL to execute a query which adds some JSON to an array in my Postgres JSONB database.

When I run the code below, I get a warning about SQL injection, the warning I get is below.

In Groovy SQL please do not use quotes around dynamic expressions
  (which start with $) as this means we cannot use a JDBC
  PreparedStatement and so is a security hole. Groovy has worked around
  your mistake but the security hole is still there.

Also I can't save the JSON in my database if there is a ' character in my JSON, I get the below error:

Sql failed to process query unterminated ' character

```<code>@Override
Operation save(Player player) {
    String json = objectMapper.writeValueAsString(player)
    Blocking.get {
        sql.executeUpdate("""
            UPDATE site_content
            SET content = jsonb_set(content, '{playersContainer,players}'::text[], content->'playersContainer'->'players' || '${json}'::jsonb)
            where id = :id
            """,id: player.teamId)
    }.operation()
}
</code>```

I have changed the code to this

```<code>@Override
Operation save(Player player) {
    String json = objectMapper.writeValueAsString(player)
    Blocking.get {
        sql.executeUpdate("""
            UPDATE site_content
            SET content = jsonb_set(content, '{playersContainer,players}'::text[], content->'playersContainer'->'players' || ':json'::jsonb)
            where id = :id
            """, json: json, id: player.teamId)
    }.operation()
}
</code>```

But I get the error

Detail: Expected JSON value, but found ":".   Position: 167

What is the correct way to place dynamic parameters into my Groovy SQL queries? And should I have to encode the JSON when I send it to the query? At the moment before I send it from my React app, I do JSON.stringfy(json) is this not enough?

答:
There shall not be quotes around a binding name.

Use :json instead of ':json'.

The first is binding, the second is a string starting with a colon. So the error message is straightforward about that: unable to parse a json object from string ':json'.

Body:
I am using Groovy SQL to execute a query which adds some JSON to an array in my Postgres JSONB database.

When I run the code below, I get a warning about SQL injection, the warning I get is below.

In Groovy SQL please do not use quotes around dynamic expressions
  (which start with $) as this means we cannot use a JDBC
  PreparedStatement and so is a security hole. Groovy has worked around
  your mistake but the security hole is still there.

Also I can't save the JSON in my database if there is a ' character in my JSON, I get the below error:

Sql failed to process query unterminated ' character

@Override
Operation save(Player player) {
    String json = objectMapper.writeValueAsString(player)
    Blocking.get {
        sql.executeUpdate("""
            UPDATE site_content
            SET content = jsonb_set(content, '{playersContainer,players}'::text[], content->'playersContainer'->'players' || '${json}'::jsonb)
            where id = :id
            """,id: player.teamId)
    }.operation()
}

I have changed the code to this

@Override
Operation save(Player player) {
    String json = objectMapper.writeValueAsString(player)
    Blocking.get {
        sql.executeUpdate("""
            UPDATE site_content
            SET content = jsonb_set(content, '{playersContainer,players}'::text[], content->'playersContainer'->'players' || ':json'::jsonb)
            where id = :id
            """, json: json, id: player.teamId)
    }.operation()
}

But I get the error

Detail: Expected JSON value, but found ":".   Position: 167

What is the correct way to place dynamic parameters into my Groovy SQL queries? And should I have to encode the JSON when I send it to the query? At the moment before I send it from my React app, I do JSON.stringfy(json) is this not enough?


问:
ERR_INVALID_RESPONSE on Chrome while opening PDF generated through PHP
I am trying to open a PDF that is dynamically generated by PHP using html2pdf.
It is working well on Firefox and Safari. However on Chrome giving ERR_INVALID_RESPONSE.
All was working well before, till we updated our site to CodeIgniter 3.1.4.
Have already searched everywhere and didn't found any suitable solution for my issue.
Any help would be highly appreciated.

```<code>function property_pdf_ver2($property_id = FALSE, $tenure_text = FALSE) {
    error_reporting(E_ALL);
    require_once(APPPATH . 'third_party/html2pdf/html2pdf.class.php');
    $template_pdf = $this->load->view('templates/property-pdf-ver2', $data, TRUE);
    $html2pdf = new HTML2PDF('L', 'A5', 'en', true, 'UTF-8', array(0, 0, 0, 0));
    $html2pdf->setDefaultFont('helvetica');
    $html2pdf->addFont('robotolight', false, getcwd() . '/assets/fonts/robotottf/robotolight.php');
    $html2pdf->addFont('robotomedium', false, getcwd() . '/assets/fonts/robotottf/robotomedium.php');
    $html2pdf->addFont('robotothin', false, getcwd() . '/assets/fonts/robotottf/robotothin.php');
    $html2pdf->WriteHTML($template_pdf);
    $html2pdf->Output('sample.pdf');
    $html2pdf->SetFillColor(0, 128, 190);
}
</code>```

答:
It's weird but after a careful debugging I found the cause for issue.
The below line was preventing the chrome from loading the PDF. I had to remove it for the function to work.

```<code>$html2pdf->SetFillColor(0, 128, 190);
</code>```

Thanks all, for your consideration towards my issue.

Body:
I am trying to open a PDF that is dynamically generated by PHP using html2pdf.
It is working well on Firefox and Safari. However on Chrome giving ERR_INVALID_RESPONSE.
All was working well before, till we updated our site to CodeIgniter 3.1.4.
Have already searched everywhere and didn't found any suitable solution for my issue.
Any help would be highly appreciated.

function property_pdf_ver2($property_id = FALSE, $tenure_text = FALSE) {
    error_reporting(E_ALL);
    require_once(APPPATH . 'third_party/html2pdf/html2pdf.class.php');
    $template_pdf = $this->load->view('templates/property-pdf-ver2', $data, TRUE);
    $html2pdf = new HTML2PDF('L', 'A5', 'en', true, 'UTF-8', array(0, 0, 0, 0));
    $html2pdf->setDefaultFont('helvetica');
    $html2pdf->addFont('robotolight', false, getcwd() . '/assets/fonts/robotottf/robotolight.php');
    $html2pdf->addFont('robotomedium', false, getcwd() . '/assets/fonts/robotottf/robotomedium.php');
    $html2pdf->addFont('robotothin', false, getcwd() . '/assets/fonts/robotottf/robotothin.php');
    $html2pdf->WriteHTML($template_pdf);
    $html2pdf->Output('sample.pdf');
    $html2pdf->SetFillColor(0, 128, 190);
}

Body:
It's weird but after a careful debugging I found the cause for issue.
The below line was preventing the chrome from loading the PDF. I had to remove it for the function to work.

$html2pdf->SetFillColor(0, 128, 190);

Thanks all, for your consideration towards my issue.


问:
Run-Time Check Failure #2 - Stack around the variable 'obj' was corrupted
I am getting Run-Time Check Failure #2 - Stack around the variable 'obj' was corrupted error when I run the following code. I know this is failing because of overwriting the bounds of 'obj' causing corrupting the stack. So how to prevent buffer overrun here.</p>

```<code>typedef struct _INFO {
    int Count;
} Info, *InfoPtr;

#define MAX_COUNT               10

//void fn(Info(*obj)[MAX_COUNT])
void fn(Info (*obj)[MAX_COUNT])
{
    for (int i = 0; i < 2; i++)
    {
        obj[i]->Count = i;
    }
}

int main()
{
    Info    obj[MAX_COUNT];
    fn(&obj);
    return 1;
}
</code>```

答:
With Info (*obj)[MAX_COUNT] you say that obj is a pointer to an array of MAX_COUNT objects of type Info.

But then you use it like obj[i]->Count = i which treats obj as an array of pointers to Info objects. I.e. Info *obj][]. Not the same thing. And that leads to undefined behavior.

The solution is quite simple, don't pass a pointer to the array as argument, and treat it as an array of objects and not pointers to objects.

I.e.

```<code>typedef struct Info {
    int Count;
} Info;

#define MAX_COUNT               10

void fn(Info *obj, const size_t elems)
{
    for (size_t i = 0; i < elems; i++)
    {
        obj[i].Count = i;
    }
}

int main()
{
    Info    obj[MAX_COUNT];
    fn(obj, MAX_COUNT);
}
</code>```

The changes are most notably the fn function declaration, which takes a pointer to Info. That is because arrays naturally decays to pointers to their first element. I also added an argument to hold the number of elements in the array, so the function knows it. That makes the function more general and you can pass it different arrays of different sizes.

I also changed to main function to not return anything at all. Since the C99 standard a main function without an explicit return will implicitly get a return 0 by the compiler. And returning 0 from the main function is usually seen as "okay" or "no failure". Returning a non-zero value is considered as a failure or error.

I also changed the name of your structure. Names (C or preprocessor) with a leading underscore followed by an upper-case letter is reserved in all scopes by the compiler and the standard C library. Also, structure tag names live in a separate namespace, so you can have the same name of the structure as a type-name (type-alias, as defined by typedef). I also removed the InfoPtr type-name, using such pointers as type-names obfuscates the code and makes it less readable and maintainable.

Body:
I am getting Run-Time Check Failure #2 - Stack around the variable 'obj' was corrupted error when I run the following code. I know this is failing because of overwriting the bounds of 'obj' causing corrupting the stack. So how to prevent buffer overrun here.

typedef struct _INFO {
    int Count;
} Info, *InfoPtr;

#define MAX_COUNT               10

//void fn(Info(*obj)[MAX_COUNT])
void fn(Info (*obj)[MAX_COUNT])
{
    for (int i = 0; i < 2; i++)
    {
        obj[i]->Count = i;
    }
}

int main()
{
    Info    obj[MAX_COUNT];
    fn(&obj);
    return 1;
}

Body:
With Info (*obj)[MAX_COUNT] you say that obj is a pointer to an array of MAX_COUNT objects of type Info.

But then you use it like obj[i]->Count = i which treats obj as an array of pointers to Info objects. I.e. Info *obj][]. Not the same thing. And that leads to undefined behavior.

The solution is quite simple, don't pass a pointer to the array as argument, and treat it as an array of objects and not pointers to objects.

I.e.

typedef struct Info {
    int Count;
} Info;

#define MAX_COUNT               10

void fn(Info *obj, const size_t elems)
{
    for (size_t i = 0; i < elems; i++)
    {
        obj[i].Count = i;
    }
}

int main()
{
    Info    obj[MAX_COUNT];
    fn(obj, MAX_COUNT);
}

The changes are most notably the fn function declaration, which takes a pointer to Info. That is because arrays naturally decays to pointers to their first element. I also added an argument to hold the number of elements in the array, so the function knows it. That makes the function more general and you can pass it different arrays of different sizes.

I also changed to main function to not return anything at all. Since the C99 standard a main function without an explicit return will implicitly get a return 0 by the compiler. And returning 0 from the main function is usually seen as "okay" or "no failure". Returning a non-zero value is considered as a failure or error.

I also changed the name of your structure. Names (C or preprocessor) with a leading underscore followed by an upper-case letter is reserved in all scopes by the compiler and the standard C library. Also, structure tag names live in a separate namespace, so you can have the same name of the structure as a type-name (type-alias, as defined by typedef). I also removed the InfoPtr type-name, using such pointers as type-names obfuscates the code and makes it less readable and maintainable.