问:
How to identify webelement using partial attribute of id?
I have to find xpath for a textbox using id attribute. However, a portion of the attribute keeps changing every time I login to the application which I'm automating and the remaining portion remains unchanged. PFB example -

```<code>Attribute ------> id="StringJob_value_1102199569"
</code>```

Here, the numeric value changes during every login and the portion "StringJob_value" remains unchanged.

Hence, is there any way in selenium to only use the constant portion of the attribute to identify the web element(Text Box)?

答:
Try the following xpath:</p>

```<code>//*[contains(@id, 'StringJob_value_')]
</code>```

Body:
I have to find xpath for a textbox using id attribute. However, a portion of the attribute keeps changing every time I login to the application which I'm automating and the remaining portion remains unchanged. PFB example -

Attribute ------> id="StringJob_value_1102199569"

Here, the numeric value changes during every login and the portion "StringJob_value" remains unchanged.

Hence, is there any way in selenium to only use the constant portion of the attribute to identify the web element(Text Box)?

Body:
Try the following xpath:

//*[contains(@id, 'StringJob_value_')]


来源: stackexchange

问:
Mockito - mock subclass method call
I am working with legacy code and trying to write a unit test for an implementation I did. I have the following structure:

```<code>   AbstractClass:
    ----------------

    public AbstractClass {

    abstract method2();

     void method1(){
      ...does something...
      ..calls --> method2()
     }
    }

    Subclass
    ------------
    public Subclass extends AbstractClass(){

     void method2(){
      ..do something....
      ..mockThisMethod()...

       return true;
     }
 }
</code>```

I have an abstract class which has some logic implemented in a specific method.
This method calls than another method implemented in the subclass. The method in the subclass calls other methods which I want to mock.

Is this possible without changing the implementation code (hard to change)?
Mos of the results are suggesting using mockito spying but it doesn't work.

I followed the TestDesign describer here:

https://www.tildedave.com/2011/03/06/pattern-stubbing-legacy-superclasses-with-mockito-spies.html

What I did is:

```<code> Subclass subclass= spy(Subclass.class);
 when(subclass.mockThisMethod()).thenReturn(something);
 subclass.method1() (I am not sure if this line is correct?)
</code>```

So what I want to avoid is, calling the method (mockThisMethod) in the Subclass.
Since this method does some db-stuff an so on. I know it would be easier to test, if I use object composition instead of inheritance but at this point, it is hard to change the whole implementation. The code above is not working..I get a NPE.

答:
1) You do not create a Spy by passing the class to the static Mockito.spy method.
Instead, you must pass an instance of that particular class:

```<code>Subclass subclassSpy = spy(new Subclass());
</code>```

Also, consider using annotations:

```<code>@Spy
private Subclass subclassSpy = new Sublcass();

@Before
public void init(){
   MockitoAnnotations.initMocks(this);
}
</code>```

2) Avoid using when.thenReturn when stubbing a spy.
Instead, use doReturn..when..methodCall:

```<code>doReturn(something).when(sublcass).mockThisMethod();
</code>```

otherwise you will invoke the actual method while stubbing and this may lead to unwanted behavior and/or exceptions.

ContentLicense: CC BY-SA 3.0

Title: Mockito - mock subclass method call

Body:
I am working with legacy code and trying to write a unit test for an implementation I did. I have the following structure:

   AbstractClass:
    ----------------

    public AbstractClass {

    abstract method2();

     void method1(){
      ...does something...
      ..calls --> method2()
     }
    }

    Subclass
    ------------
    public Subclass extends AbstractClass(){

     void method2(){
      ..do something....
      ..mockThisMethod()...

       return true;
     }
 }

I have an abstract class which has some logic implemented in a specific method.
This method calls than another method implemented in the subclass. The method in the subclass calls other methods which I want to mock.

Is this possible without changing the implementation code (hard to change)?
Mos of the results are suggesting using mockito spying but it doesn't work.

I followed the TestDesign describer here:

https://www.tildedave.com/2011/03/06/pattern-stubbing-legacy-superclasses-with-mockito-spies.html

What I did is:

 Subclass subclass= spy(Subclass.class);
 when(subclass.mockThisMethod()).thenReturn(something);
 subclass.method1() (I am not sure if this line is correct?)

So what I want to avoid is, calling the method (mockThisMethod) in the Subclass.
Since this method does some db-stuff an so on. I know it would be easier to test, if I use object composition instead of inheritance but at this point, it is hard to change the whole implementation. The code above is not working..I get a NPE.

Body:
1) You do not create a Spy by passing the class to the static Mockito.spy method.
Instead, you must pass an instance of that particular class:

Subclass subclassSpy = spy(new Subclass());

Also, consider using annotations:

@Spy
private Subclass subclassSpy = new Sublcass();

@Before
public void init(){
   MockitoAnnotations.initMocks(this);
}

2) Avoid using when.thenReturn when stubbing a spy.
Instead, use doReturn..when..methodCall:

doReturn(something).when(sublcass).mockThisMethod();

otherwise you will invoke the actual method while stubbing and this may lead to unwanted behavior and/or exceptions.


问:
Completion suggester not returning all suggestions
I'm using  completion suggester for auto completion. Everything is fine. but I'm not getting all   matched suggestions. I'm getting below 10 suggestions. How to increase suggestions count?</p>

答:
You can set the "size" attribute in the search request.

Look at the documentation at
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters-completion.html

Example:

```<code>POST music/_search
{
    "_source": "suggest",
    "suggest": {
        "song-suggest" : {
            "prefix" : "nir",
            "completion" : {
                "field" : "suggest",
                "size" : 20
            }
        }
    }
}
</code>```

Body:
You can set the "size" attribute in the search request.

Look at the documentation at
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters-completion.html

Example:

POST music/_search
{
    "_source": "suggest",
    "suggest": {
        "song-suggest" : {
            "prefix" : "nir",
            "completion" : {
                "field" : "suggest",
                "size" : 20
            }
        }
    }
}


问:
CruiseControl.Net "header.xsl" changes not showing in the dashboard
I've added a handful of new builds to a long standing CruiseControl.Net setup. Everything has been smooth up until this point. Now, any changes I make to the header.xsl file do not display on the build results dashboard page. This behavior only appeared after the weekend, and I'm not seeing any errors from CC.Net. Any clue as to what might be causing this? I've already attempted restarting both CC.Net and IIS.

Current CC.Net version info: 1.5.7256.1

答:
When changing something related to dashboard configuration (or XSL files) you should

restart web server

restart ccnet

From my experience

using ccnet as service + apache + mod_asp, I need to restart only ccnet service.

using ccnet as service + IIS, I need to restart IIS and sometimes to restart the PC !

ContentLicense: CC BY-SA 2.5


问:
Error in Angular 5 projects which use angular2-logger
I'm using angular2-logger version 0.6.0 in an Angular CLI project. When I try to upgrade to Angular CLI 1.5 and Angular 5, the following error occurs

```<code>ERROR in ./node_modules/angular2-logger/app/core/level.ts
Module build failed: Error: C:\test\sample-5\sample\node_module\angular2-logger\app\core\level.ts is not part of the compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.

at AngularCompilerPlugin.getCompiledFile (C:\test\sample-5\sample\node_modules\@ngtools\webpack\src\angular_compiler_plugin.js:624:23)
at plugin.done.then (C:\test\sample-5\sample\node_modules\@ngtools\webpack\src\loader.js:467:39)
at <anonymous>
@ ./node_modules/angular2-logger/core.js 6:9-36
@ ./src/app/app.module.ts
@ ./src/main.ts
@ multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts
</code>```

This is app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Logger } from 'angular2-logger/core';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [Logger],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

This sample project is created by ng new sample, so every settings are Angular CLI default.

答:
I found a temporary solution.

Go to node_modules\angular2-logger\app\core and there remove all of the .ts files.

More info:
https://github.com/code-chunks/angular2-logger/issues/175

Body:
I'm using angular2-logger version 0.6.0 in an Angular CLI project. When I try to upgrade to Angular CLI 1.5 and Angular 5, the following error occurs

ERROR in ./node_modules/angular2-logger/app/core/level.ts
Module build failed: Error: C:\test\sample-5\sample\node_module\angular2-logger\app\core\level.ts is not part of the compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.

at AngularCompilerPlugin.getCompiledFile (C:\test\sample-5\sample\node_modules\@ngtools\webpack\src\angular_compiler_plugin.js:624:23)
at plugin.done.then (C:\test\sample-5\sample\node_modules\@ngtools\webpack\src\loader.js:467:39)
at <anonymous>
@ ./node_modules/angular2-logger/core.js 6:9-36
@ ./src/app/app.module.ts
@ ./src/main.ts
@ multi webpack-dev-server/client?http://0.0.0.0:0 ./src/main.ts

This is app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Logger } from 'angular2-logger/core';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [Logger],
  bootstrap: [AppComponent]
})
export class AppModule { }

This sample project is created by ng new sample, so every settings are Angular CLI default.


问:
Extension method marked as ambiguous
I am having trouble with extension methods. Another method was causing the same error, now I am having the same issue again. While compiling - visual studio is marking my extension method as ambiguous. But I am pretty sure this is the only implementation I have -

The extension method I have is -

```<code>public static class TypeInfoExtensions
{
    /// <summary>
    /// Gets the property dictionary.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="types">The types.</param>
    /// <returns></returns>
    public static IEnumerable<Dictionary<string, object>> GetPropertyDictionaryList<T>(this IEnumerable<TypeInfo> types) where T : Attribute
    {
        return types.Select(x => x.GetPropertyDictionary<T>());
    }
    /// <summary>
    /// Gets the property dictionary.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="type">The type.</param>
    /// <returns></returns>
    public static Dictionary<string, object> GetPropertyDictionary<T>(this TypeInfo type) where T : Attribute
    {
        var dict = new Dictionary<string, object>();

        return dict;
    }
}
</code>```

And it is used like this -

```<code>var model = ...... // other codes

var parameters = Assembly.GetAssembly(typeof (Model.Domain.Tenants.Tenant)).DefinedTypes;
model.AvailableProperties = parameters.GetPropertyDictionaryList<MessageTemplateItem>().ToList()
</code>```

This is the only implementation I have, I just added it, but VS is showing this error -

Error 81  The call is ambiguous between the following methods or
  properties:
  'SMP.Core.Extensions.TypeInfoExtensions.GetPropertyDictionary(System.Reflection.TypeInfo)'
  and
  'SMP.Core.Extensions.TypeInfoExtensions.GetPropertyDictionary(System.Reflection.TypeInfo)'

I am thinking this might be a temporary error, may be cleaning the solution is not cleaning references or cache. But if any body else have faced this error, I would very much appreciate your feedback.

UPDATE Strangely enough this code works -

```<code>public static IEnumerable<Dictionary<string, object>> GetPropertyDictionaryList<T>(this IEnumerable<TypeInfo> types) where T : Attribute
{
    return types.Select(x => GetPropertyDictionary<T>(x));
}
</code>```

I am really confused now, so far I knew these are the same for an extension method -

```<code>GetPropertyDictionary<T>(x)
x.GetPropertyDictionary<T>()
</code>```

Any ideas guys?

答:
I had the same issue. I had declared an extension method in project A. While using it in this project worked, it would not work in another project B. There it was marked as being ambiguous. Calling it in a static way in project B worked however.

When searching by string in the whole solution or reference, I could not find any additional implementation to the one in project A.

The problem finally was: I accidentally added a link of the source file of the extension method from project A into project B. Removing the link to the source file in project B solved the problem.

Title: Extension method marked as ambiguous

Body:
I am having trouble with extension methods. Another method was causing the same error, now I am having the same issue again. While compiling - visual studio is marking my extension method as ambiguous. But I am pretty sure this is the only implementation I have -

The extension method I have is -

public static class TypeInfoExtensions
{
    ///
    /// Gets the property dictionary.
    ///
    /// <typeparam name="T"></typeparam>
    /// <param name="types">The types.</param>
    /// <returns></returns>
    public static IEnumerable<Dictionary<string, object>> GetPropertyDictionaryList<T>(this IEnumerable<TypeInfo> types) where T : Attribute
    {
        return types.Select(x => x.GetPropertyDictionary<T>());
    }
    ///
    /// Gets the property dictionary.
    ///
    /// <typeparam name="T"></typeparam>
    /// <param name="type">The type.</param>
    /// <returns></returns>
    public static Dictionary<string, object> GetPropertyDictionary<T>(this TypeInfo type) where T : Attribute
    {
        var dict = new Dictionary<string, object>();

        return dict;
    }
}

And it is used like this -

var model = ...... // other codes

var parameters = Assembly.GetAssembly(typeof (Model.Domain.Tenants.Tenant)).DefinedTypes;
model.AvailableProperties = parameters.GetPropertyDictionaryList<MessageTemplateItem>().ToList()

This is the only implementation I have, I just added it, but VS is showing this error -

Error 81  The call is ambiguous between the following methods or
  properties:
  'SMP.Core.Extensions.TypeInfoExtensions.GetPropertyDictionary(System.Reflection.TypeInfo)'
  and
  'SMP.Core.Extensions.TypeInfoExtensions.GetPropertyDictionary(System.Reflection.TypeInfo)'

I am thinking this might be a temporary error, may be cleaning the solution is not cleaning references or cache. But if any body else have faced this error, I would very much appreciate your feedback.

UPDATE Strangely enough this code works -

public static IEnumerable<Dictionary<string, object>> GetPropertyDictionaryList<T>(this IEnumerable<TypeInfo> types) where T : Attribute
{
    return types.Select(x => GetPropertyDictionary<T>(x));
}

I am really confused now, so far I knew these are the same for an extension method -

GetPropertyDictionary<T>(x)
x.GetPropertyDictionary<T>()

Any ideas guys?


问:
Compression utility for web videos?
For my current website project I have received a couple of HTML5-ready video assets; the only problem is that the assets are pretty large.

I know I could sacrifice quality in favor of size, but the client doesn't accept siginificant quality losses.

I know that there are a couple of image manipulation tools available (e.g. jpegmini) that can reduce image sizes significantly without much visual quality loss.

Is there anything comparable available for videos?

答:
FFmpeg (https://ffmpeg.org) is the usual go to solution in this area, certainly in the open source world.

There is a guide here to use h.264 encoding which is supported by most browsers and devices at this time: https://trac.ffmpeg.org/wiki/Encode/H.264

This includes some guidance on quality vs processing etc - look at the two pass graph.

Its also worth nothing that for streamed video, most serious streaming services will offer multiple bit rate versions of a given video also, and allow the client player download the file in, for example 10 second, chunks and select for each chunk the best bit rate for the current device and network conditions.

This is referred to as ABR, Adaptive Bit rate Streaming. See a little ore info in this answer: https://stackoverflow.com/a/42365034/334402

This is quite a specialist area and most people will use either a video hosting service which provides this or a dedicated video streaming server e.g. Wowza is a commercial example, or GStreamer with ABR plugins is an open source example.

Title: Compression utility for web videos?


问:
Unable to merge dex Android studio 3.0
I have some problem with my project. In Android studio 2.3.3 it works fine but when I updated to 3.0 I have problem to marge dex.

I clean and rebuild project.

What is wrong:

Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

StackTrace:

```<code>org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
at     org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeA  ctions(ExecuteActionsTaskExecuter.java:100)
at   org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(  ExecuteActionsTaskExecuter.java:70)
at    org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(Sk  ipUpToDateTaskExecuter.java:63)
at   org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecut  er.execute(ResolveTaskOutputCachingStateExecuter.java:54)
at   org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(Vali  datingTaskExecuter.java:58)
at   org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.ex  ecute(SkipEmptySourceFilesTaskExecuter.java:88)
at   org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
at   org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execu  te(SkipTaskWithNoActionsExecuter.java:52)
at   org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(Skip  OnlyIfTaskExecuter.java:54)
at   org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execu  te(ExecuteAtMostOnceTaskExecuter.java:43)
at   org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(  CatchExceptionTaskExecuter.java:34)
at   org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWork  er$1.run(DefaultTaskGraphExecuter.java:248)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOpe  rationWorker.execute(DefaultBuildOperationExecutor.java:336)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOpe  rationWorker.execute(DefaultBuildOperationExecutor.java:328)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultB  uildOperationExecutor.java:197)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuild  OperationExecutor.java:107)
at   org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWork  er.execute(DefaultTaskGraphExecuter.java:241)
at   org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWork  er.execute(DefaultTaskGraphExecuter.java:230)
at   org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.p  rocessTask(DefaultTaskPlanExecutor.java:124)
at   org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
at   org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1  .execute(DefaultTaskPlanExecutor.java:105)
at   org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1  .execute(DefaultTaskPlanExecutor.java:99)
at   org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTask  ExecutionPlan.java:625)
at   org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(Def  aultTaskExecutionPlan.java:580)
at   org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.r  un(DefaultTaskPlanExecutor.java:99)
at   org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExec  ute(ExecutorPolicy.java:63)
at   org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImp  l.java:46)
at   org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(  ThreadFactoryImpl.java:55)
Caused by: java.lang.RuntimeException:   com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
at   com.android.builder.dexing.DxDexArchiveMerger.mergeMultidex(DxDexArchiveMer ger.java:266)
at  com.android.builder.dexing.DxDexArchiveMerger.mergeDexArchives(DxDexArchive Merger.java:133)
at  com.android.build.gradle.internal.transforms.DexMergerTransformCallable.cal l(DexMergerTransformCallable.java:97)
at   com.android.build.gradle.internal.transforms.ExternalLibsMergerTransform.tr  ansform(ExternalLibsMergerTransform.kt:121)
at   com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTa  sk.java:222)
at   com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTa  sk.java:218)
at   com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
at   com.android.build.gradle.internal.pipeline.TransformTask.transform(Transfor  mTask.java:213)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at   org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$Incre  mentalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
at   org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$Stand  ardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
at   org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$Stand  ardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
at   org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(Ex  ecuteActionsTaskExecuter.java:122)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOpe  rationWorker.execute(DefaultBuildOperationExecutor.java:336)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOpe  rationWorker.execute(DefaultBuildOperationExecutor.java:328)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultB  uildOperationExecutor.java:197)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuild  OperationExecutor.java:107)
at   org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeA  ction(ExecuteActionsTaskExecuter.java:111)
at   org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeA  ctions(ExecuteActionsTaskExecuter.java:92)
... 27 more
Caused by: com.android.builder.dexing.DexArchiveMergerException: Unable     to merge dex
at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCa llable.java:72)
at   com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCa  llable.java:36)
... 46 more
Caused by: com.android.dex.DexException: Multiple dex files define     Landroid/support/v4/view/accessibility/AccessibilityRecordCompatIcsMr1;
at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:661)
at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:616)
at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:598)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:198)
at   com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCa  llable.java:61)
... 47 more
</code>```

build.gradle

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 21
buildToolsVersion '26.0.2'

defaultConfig {
    applicationId "...."
    minSdkVersion 21
    targetSdkVersion 21
    versionCode 2
    multiDexEnabled true
    versionName "1.01"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),      'proguard-rules.pro'
    }
}
}
repositories {
mavenCentral()

maven { url 'http://maven.livotovlabs.pro/content/groups/public' }
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:cardview-v7:21.0.3'
compile 'com.android.support:multidex:1.0.1' //1.0.1
compile 'com.google.android.gms:play-services:6.5.87' //6.5.87
compile fileTree(dir: 'libs', include: 'Parse-*.jar')
compile 'com.parse.bolts:bolts-tasks:1.4.0'
compile 'com.parse.bolts:bolts-applinks:1.4.0'
compile 'com.jakewharton:butterknife:8.8.0'
compile 'it.neokree:MaterialNavigationDrawer:1.3.3'
compile 'com.github.navasmdc:MaterialDesign:1.5@aar'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.github.bluejamesbond:textjustify-android:2.1.0'
compile 'it.neokree:MaterialTabs:0.11'
compile('com.googlecode.json-simple:json-simple:1.1.1') {
    exclude module: 'junit'
}
compile ('eu.livotov.labs.android:CAMView:2.0.1@aar') {transitive=true}
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}
</code>```

When i delete multiDexEnable:

```<code>org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
at com.android.builder.dexing.DxDexArchiveMerger.mergeMonoDex(DxDexArchiveMerger.java:177)
at com.android.builder.dexing.DxDexArchiveMerger.mergeDexArchives(DxDexArchiveMerger.java:118)
at com.android.build.gradle.internal.transforms.DexMergerTransformCallable.call(DexMergerTransformCallable.java:97)
at com.android.build.gradle.internal.transforms.ExternalLibsMergerTransform.transform(ExternalLibsMergerTransform.kt:121)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:222)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:218)
at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:213)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
... 27 more
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
at com.android.builder.dexing.DxDexArchiveMerger.lambda$mergeMonoDex$0(DxDexArchiveMerger.java:171)
Caused by: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
Caused by: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:72)
at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:36)
Caused by: com.android.dex.DexException: Multiple dex files define   Landroid/support/v4/view/accessibility/AccessibilityRecordCompatIcsMr1;
at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:661)
at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:616)
at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:598)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:198)
at   com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCa  llable.java:61)
... 1 more
</code>```

答:
This is related to duplicated dependencies in your project. There is a duplicate dependency which is happened because some libraries is implicitly dependent to the same library but with different version. Gradle 4.1 which is used in the Android Studio is not forgiving for library duplication.

You can check it from dependencies tree with the following command in your terminal in Linux (app is your module name):

```<code>./gradlew app:dependencies
</code>```

or if you're using Windows try this in command prompt:

```<code>gradlew.bat app:dependencies
</code>```

Then after you found it, you need to exclude it from the library and use only one of them. Something like this:

```<code>compile('com.library.name:version') {
  // this is a case for duplicate support library version.
  exclude group: 'com.android.support'
  exclude module: 'appcompat-v7'
}
</code>```

Be noted that you are better to use the same version of
compileSdkVersion, buildToolsVersion, targetSdkVersion, and Support Library.

Title: Unable to merge dex Android studio 3.0

Body:
I have some problem with my project. In Android studio 2.3.3 it works fine but when I updated to 3.0 I have problem to marge dex.

I clean and rebuild project.

What is wrong:

Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
  com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

StackTrace:

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
at     org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeA  ctions(ExecuteActionsTaskExecuter.java:100)
at   org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(  ExecuteActionsTaskExecuter.java:70)
at    org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(Sk  ipUpToDateTaskExecuter.java:63)
at   org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecut  er.execute(ResolveTaskOutputCachingStateExecuter.java:54)
at   org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(Vali  datingTaskExecuter.java:58)
at   org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.ex  ecute(SkipEmptySourceFilesTaskExecuter.java:88)
at   org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
at   org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execu  te(SkipTaskWithNoActionsExecuter.java:52)
at   org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(Skip  OnlyIfTaskExecuter.java:54)
at   org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execu  te(ExecuteAtMostOnceTaskExecuter.java:43)
at   org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(  CatchExceptionTaskExecuter.java:34)
at   org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWork  er$1.run(DefaultTaskGraphExecuter.java:248)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOpe  rationWorker.execute(DefaultBuildOperationExecutor.java:336)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOpe  rationWorker.execute(DefaultBuildOperationExecutor.java:328)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultB  uildOperationExecutor.java:197)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuild  OperationExecutor.java:107)
at   org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWork  er.execute(DefaultTaskGraphExecuter.java:241)
at   org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWork  er.execute(DefaultTaskGraphExecuter.java:230)
at   org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.p  rocessTask(DefaultTaskPlanExecutor.java:124)
at   org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
at   org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1  .execute(DefaultTaskPlanExecutor.java:105)
at   org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1  .execute(DefaultTaskPlanExecutor.java:99)
at   org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTask  ExecutionPlan.java:625)
at   org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(Def  aultTaskExecutionPlan.java:580)
at   org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.r  un(DefaultTaskPlanExecutor.java:99)
at   org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExec  ute(ExecutorPolicy.java:63)
at   org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImp  l.java:46)
at   org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(  ThreadFactoryImpl.java:55)
Caused by: java.lang.RuntimeException:   com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
at   com.android.builder.dexing.DxDexArchiveMerger.mergeMultidex(DxDexArchiveMer ger.java:266)
at  com.android.builder.dexing.DxDexArchiveMerger.mergeDexArchives(DxDexArchive Merger.java:133)
at  com.android.build.gradle.internal.transforms.DexMergerTransformCallable.cal l(DexMergerTransformCallable.java:97)
at   com.android.build.gradle.internal.transforms.ExternalLibsMergerTransform.tr  ansform(ExternalLibsMergerTransform.kt:121)
at   com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTa  sk.java:222)
at   com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTa  sk.java:218)
at   com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
at   com.android.build.gradle.internal.pipeline.TransformTask.transform(Transfor  mTask.java:213)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at   org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$Incre  mentalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
at   org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$Stand  ardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
at   org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$Stand  ardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
at   org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(Ex  ecuteActionsTaskExecuter.java:122)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOpe  rationWorker.execute(DefaultBuildOperationExecutor.java:336)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOpe  rationWorker.execute(DefaultBuildOperationExecutor.java:328)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultB  uildOperationExecutor.java:197)
at   org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuild  OperationExecutor.java:107)
at   org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeA  ction(ExecuteActionsTaskExecuter.java:111)
at   org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeA  ctions(ExecuteActionsTaskExecuter.java:92)
... 27 more
Caused by: com.android.builder.dexing.DexArchiveMergerException: Unable     to merge dex
at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCa llable.java:72)
at   com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCa  llable.java:36)
... 46 more
Caused by: com.android.dex.DexException: Multiple dex files define     Landroid/support/v4/view/accessibility/AccessibilityRecordCompatIcsMr1;
at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:661)
at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:616)
at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:598)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:198)
at   com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCa  llable.java:61)
... 47 more

build.gradle

apply plugin: 'com.android.application'

android {
compileSdkVersion 21
buildToolsVersion '26.0.2'

defaultConfig {
    applicationId "...."
    minSdkVersion 21
    targetSdkVersion 21
    versionCode 2
    multiDexEnabled true
    versionName "1.01"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),      'proguard-rules.pro'
    }
}
}
repositories {
mavenCentral()

maven { url 'http://maven.livotovlabs.pro/content/groups/public' }
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:cardview-v7:21.0.3'
compile 'com.android.support:multidex:1.0.1' //1.0.1
compile 'com.google.android.gms:play-services:6.5.87' //6.5.87
compile fileTree(dir: 'libs', include: 'Parse-*.jar')
compile 'com.parse.bolts:bolts-tasks:1.4.0'
compile 'com.parse.bolts:bolts-applinks:1.4.0'
compile 'com.jakewharton:butterknife:8.8.0'
compile 'it.neokree:MaterialNavigationDrawer:1.3.3'
compile 'com.github.navasmdc:MaterialDesign:1.5@aar'
compile 'com.nineoldandroids:library:2.4.0'
compile 'com.github.bluejamesbond:textjustify-android:2.1.0'
compile 'it.neokree:MaterialTabs:0.11'
compile('com.googlecode.json-simple:json-simple:1.1.1') {
    exclude module: 'junit'
}
compile ('eu.livotov.labs.android:CAMView:2.0.1@aar') {transitive=true}
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}

When i delete multiDexEnable:

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
at com.android.builder.dexing.DxDexArchiveMerger.mergeMonoDex(DxDexArchiveMerger.java:177)
at com.android.builder.dexing.DxDexArchiveMerger.mergeDexArchives(DxDexArchiveMerger.java:118)
at com.android.build.gradle.internal.transforms.DexMergerTransformCallable.call(DexMergerTransformCallable.java:97)
at com.android.build.gradle.internal.transforms.ExternalLibsMergerTransform.transform(ExternalLibsMergerTransform.kt:121)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:222)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:218)
at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:213)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
... 27 more
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
at com.android.builder.dexing.DxDexArchiveMerger.lambda$mergeMonoDex$0(DxDexArchiveMerger.java:171)
Caused by: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
Caused by: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:72)
at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:36)
Caused by: com.android.dex.DexException: Multiple dex files define   Landroid/support/v4/view/accessibility/AccessibilityRecordCompatIcsMr1;
at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:661)
at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:616)
at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:598)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:198)
at   com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCa  llable.java:61)
... 1 more

Body:
This is related to duplicated dependencies in your project. There is a duplicate dependency which is happened because some libraries is implicitly dependent to the same library but with different version. Gradle 4.1 which is used in the Android Studio is not forgiving for library duplication.

You can check it from dependencies tree with the following command in your terminal in Linux (app is your module name):

./gradlew app:dependencies

or if you're using Windows try this in command prompt:

gradlew.bat app:dependencies

Then after you found it, you need to exclude it from the library and use only one of them. Something like this:

compile('com.library.name:version') {
  // this is a case for duplicate support library version.
  exclude group: 'com.android.support'
  exclude module: 'appcompat-v7'
}

Be noted that you are better to use the same version of
compileSdkVersion, buildToolsVersion, targetSdkVersion, and Support Library.


问:
Creating a new project in Android studio-Kotlin error
I am very new to Kotlin and I am creating a new project that supports Kotlin in Android Studio 3.0 canary.

This project is having two issues.

The R file is not getting resolved

The package name must be a '.' separated identifier list

What should I do now?

Thanks in advance.

答:
I assume you are using one of Kotlin keywords in your package name.

To fix compilation error just surround the Keywords like in ,as,is with Grave accent ( ` ). E.g.
`is`.package.name,

`in`.company.app

Hope, it'll help you.

ContentLicense: CC BY-SA 4.0


问:
Jasper Reports Alternative for Google App Engine
What are the alternative for Jasper Reports that works in Google App Engine? Anyone tried?

Thanks.

答:
We tried a variant with JasperReports® Server on Compute Engine or Kubernetes but there are problems with the authentication;

AppEngine URLFetchService removing custom response header attribute?

The "Set-Cookie" attribute never appears in the response header even though the JasperReports server returns a 200 OK status for the login POST request.

Otherwise this would be a nice reporting solution for the Google Cloud platform.


问:
Will the ternary operator be executed on every digest?
If I use the ternary operator in my Angular.js view will it be executed on every digest(like functions) or only if the variables necessary for the decision are changed?

Example:

```<code><div>{{ui.isTrue ? "foo" : "bar"}}</div>
</code>```

or:

```<code><div ng-bind="ui.isTrue ? 'foo' : 'bar'"></div>
</code>```

Would it be executed on every digest or only when is ui.IsTrue changed?

答:
In AngularJS, every expression including the ternary operator will be executed:

First when the page is loaded.

And whenever the ui.isTrue variable is changed in the angular app scope.

If you take a look at angular scope documentation and specifically Scope as Data-Model section, you will see that:

Scope is the glue between application controller and the view. During the template linking phase the directives set up $watch expressions on the scope.

The $watch allows the directives to be notified of property
  changes, which allows the directive to render the updated value to the
  DOM.

So the view will be always notified when a property in the scope changes, so the ternary expression will be automatically evaluated.

Body:
If I use the ternary operator in my Angular.js view will it be executed on every digest(like functions) or only if the variables necessary for the decision are changed?

Example:

{{ui.isTrue ? "foo" : "bar"}}

or:

Would it be executed on every digest or only when is ui.IsTrue changed?


问:
redefining a function with a template
How do I redefine a call like this via C preprocessor Instructions to snprintf?

```<code>sprintf_s<sizeof(dataFile)>(dataFile, arg2, arg3);
</code>```

I tried this (which doesn't work):

```<code>#define sprintf_s<sizeof(x)>(args...) snprintf<sizeof(x)>(args)
</code>```

Especially because I already need this for calls to sprintf_s without a template in the same files:

```<code>#define sprintf_s(args...) snprintf(args)
</code>```

答:
As mkrs said in his/her answer, the preprocessor doesn't allow you to match template-like function invocations.

You don't need the preprocessor for this task - use a variadic template instead:

```<code>template <int Size, typename... Ts>
auto sprintf_s(Ts&&... xs)
{
    return snprintf<Size>(std::forward<Ts>(xs)...);
}
</code>```

If snprintf uses va_arg, you will need a different kind of wrapper:

```<code>template <int Size>
void sprintf_s(char* s, ...)
{
    va_list args;
    va_start(args, s);
    snprintf(args);
    va_end(args);
}
</code>```

See How to wrap a function with variable length arguments? for more examples.

Title: redefining a function with a template

Body:
How do I redefine a call like this via C preprocessor Instructions to snprintf?

sprintf_s<sizeof(dataFile)>(dataFile, arg2, arg3);

I tried this (which doesn't work):

#define sprintf_s<sizeof(x)>(args...) snprintf<sizeof(x)>(args)

Especially because I already need this for calls to sprintf_s without a template in the same files:

#define sprintf_s(args...) snprintf(args)

Body:
As mkrs said in his/her answer, the preprocessor doesn't allow you to match template-like function invocations.

You don't need the preprocessor for this task - use a variadic template instead:

template <int Size, typename... Ts>
auto sprintf_s(Ts&&... xs)
{
    return snprintf<Size>(std::forward<Ts>(xs)...);
}

If snprintf uses va_arg, you will need a different kind of wrapper:

template <int Size>
void sprintf_s(char* s, ...)
{
    va_list args;
    va_start(args, s);
    snprintf(args);
    va_end(args);
}

See How to wrap a function with variable length arguments? for more examples.


问:
how to append data continuously in data frame depending upon the number of times function is called
UseCase:

I have an xml file, from which i am parsing some values as per their attributes  and storing them in dictionary format.

Function add_data_to_data_frame is overwriting the data frame each time it is being called.

I want that data should be appended not overwrite while calling the function.

```<code>import pandas as pd
import datetime

date=datetime.datetime.now().date()
date=pd.to_datetime(date)

def add_data_to_dataframe():
    data={
        'fail':5,
        'Pass':5,
        'suite_name':['Robot'],
        'Report_datetime':[pd.to_datetime('today').now()],
        'datetime':[pd.to_datetime('today').now()]
        }
    rd=pd.DataFrame(columns=['suite_name','fail','Pass','Report_datetime','datetime'],index=[date])
    rd=pd.DataFrame(data,index=[date])
    rd=rd.append(pd.DataFrame(data,index=[date]))
    return rd

dq=add_data_to_dataframe()
print (dq)
</code>```

Each time when the function is called , i got 2 output

```<code>    Pass         Report_datetime                datetime  fail  \
2017-11-13     5 2017-11-13 15:51:51.648 2017-11-13 15:51:51.648     5
2017-11-13     5 2017-11-13 15:51:51.648 2017-11-13 15:51:51.648     5

           suite_name
2017-11-13      Robot
2017-11-13      Robot
</code>```

What i want is that if next time I call my function there should be 3 records in it and so on

答:
The reason its overwriting is you are using same variable name and performing the append operation inside the function which will empty everything when you call it for second time.

```<code>import pandas as pd
import datetime

rd=pd.DataFrame() # an empty dataframe
date=datetime.datetime.now().date()
date=pd.to_datetime(date)

def add_data_to_dataframe():
    data={
        'fail':5,
        'Pass':5,
        'suite_name':['Robot'],
        'Report_datetime':[pd.to_datetime('today').now()],
        'datetime':[pd.to_datetime('today').now()]
        }
       empty_list.append(data)
       return empty_list
</code>```

After I get the empty list I will define my dataframe

```<code>make_list = add_data_to_dataframe()
new_df = pd.DataFrame(make_list,columns=['suite_name','fail','Pass','Report_datetime','datetime'],index=[date])
</code>```

Now at the end append both the dataframes.

```<code>rd.append(new_df) # now instead of overwriting it will append
</code>```

Body:
UseCase:

I have an xml file, from which i am parsing some values as per their attributes  and storing them in dictionary format.

Function add_data_to_data_frame is overwriting the data frame each time it is being called.

I want that data should be appended not overwrite while calling the function.

import pandas as pd
import datetime

date=datetime.datetime.now().date()
date=pd.to_datetime(date)

def add_data_to_dataframe():
    data={
        'fail':5,
        'Pass':5,
        'suite_name':['Robot'],
        'Report_datetime':[pd.to_datetime('today').now()],
        'datetime':[pd.to_datetime('today').now()]
        }
    rd=pd.DataFrame(columns=['suite_name','fail','Pass','Report_datetime','datetime'],index=[date])
    rd=pd.DataFrame(data,index=[date])
    rd=rd.append(pd.DataFrame(data,index=[date]))
    return rd

dq=add_data_to_dataframe()
print (dq)

Each time when the function is called , i got 2 output

    Pass         Report_datetime                datetime  fail  \
2017-11-13     5 2017-11-13 15:51:51.648 2017-11-13 15:51:51.648     5
2017-11-13     5 2017-11-13 15:51:51.648 2017-11-13 15:51:51.648     5

           suite_name
2017-11-13      Robot
2017-11-13      Robot

What i want is that if next time I call my function there should be 3 records in it and so on

Body:
The reason its overwriting is you are using same variable name and performing the append operation inside the function which will empty everything when you call it for second time.

import pandas as pd
import datetime

rd=pd.DataFrame() # an empty dataframe
date=datetime.datetime.now().date()
date=pd.to_datetime(date)

def add_data_to_dataframe():
    data={
        'fail':5,
        'Pass':5,
        'suite_name':['Robot'],
        'Report_datetime':[pd.to_datetime('today').now()],
        'datetime':[pd.to_datetime('today').now()]
        }
       empty_list.append(data)
       return empty_list

After I get the empty list I will define my dataframe

make_list = add_data_to_dataframe()
new_df = pd.DataFrame(make_list,columns=['suite_name','fail','Pass','Report_datetime','datetime'],index=[date])

Now at the end append both the dataframes.

rd.append(new_df) # now instead of overwriting it will append


问:
Rails 5 Adding some attributes to `User` in Devise
I am using Rails 5.1, I added devise for user authentication. I added some extra attributes to my table. After I create a new user via ajax User created but some attribute is missing. I checked the log, devise doesn't send these columns in the insert query.

First I added the devise_parameter_sanitizer to my application controller :

```<code>before_action :configure_permitted_parameters, if: :devise_controller?

protected

def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up, keys: [:email,:password1,:password2,:title,:phone, :first_name , :last_name, :postalcode, :address,:coordinate, :latitude, :longitude])
end
</code>```

I added attr_accessor to my User model:

attr_accessor :password1,:password2, :phone, :postalcode, :first_name,
  :last_name, :address

end following code my create methods in registration controller :

```<code>    @user = User.new
    @user.email = params[:sign_up][:email]
    @user.password = params[:sign_up][:password1]
    @user.password_confirmation =params[:sign_up][:password2]
    @user.phone = params[:sign_up][:phone]
    @firstname = params[:sign_up][:first_name]
    @user.first_name = @firstname
    @user.last_name = params[:sign_up][:last_name]
    @user.postalcode = params[:sign_up][:postalcode]

    @coordinate = Geocoder.coordinates(params[:sign_up][:postalcode])

    @user.coordinate = @coordinate
    @user.latitude = @coordinate[0]
    @user.longitude = @coordinate[1]
    @user.address = params[:sign_up][:address]

    @user.valid?
    if @user.errors.blank?

      @user.save
    end
</code>```

I am seeing following log in my console :

SQL (0.5ms)  INSERT INTO "users" ("email", "encrypted_password",
  "created_at", "updated_at", "user_role", "latitude", "longitude",
  "coordinate") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"
  [["email", "jd@gmail.com"], ["encrypted_password",
  "$2a$11$Rsn8pM0wVfiRAHwMQ/8YTeYGDn6qzAvZEFPJjqq4Ri.xZfGdof9f6"],
  ["created_at", "2017-11-13 12:07:27.781262"], ["updated_at",
  "2017-11-13 12:07:27.781262"], ["user_role", "t"], ["latitude",
  53.3960084], ["longitude", -2.929237], ["coordinate", "[53.3960084, -2.929237]"]]

And why is my code save coorditanes, longitute and lattitude attributes to db and dont save first_name, last_name and address attributes?  How can I fix this?
Best

EDITED :
My js code :

```<code>            $.ajax({
            type: "POST",
            url: "/users",
            data: {
                sign_up: {
                    first_name: $('#firstname').val(),
                    last_name: $('#lastname').val(),
                    email: $('#email').val(),
                    password1: $('#password1').val(),
                    password2: $('#password2').val(),
                    postalcode: $('#postalcode').val(),
                    phone: $('#phone').val(),
                    website: $('#website').val(),
                    title: $('#title').val(),
                    address: $('#address').val(),
                }
            },
</code>```

My User Shcema

```<code>create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "superadmin_role"
t.boolean "user_role"
t.string "first_name"
t.string "last_name"
t.string "phone"
t.string "post_code"
t.float "latitude"
t.float "longitude"
t.string "coordinate"
t.string "address"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
</code>```

end

EDITED 2 :
I made test with  :

```<code> @u = User.create(first_name: params[:sign_up][:first_name], email:
 params[:sign_up][:email], password: params[:sign_up][:password1])
 @u.save!
</code>```

and de result is

Parameters: {"sign_up"=>{"first_name"=>"", "last_name"=>"Onder",
  "email"=>"Test1603@test.com", "password1"=>"[FILTERED]",
  "password2"=>"[FILTERED]", "postalcode"=>"L16 2WA", "phone"=>"123456",
  "address"=>"address"}}    (0.5ms)  BEGIN   User Exists (0.5ms)  SELECT
  1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email",
  "test1603@test.com"], ["LIMIT", 1]]   SQL (1.0ms)  INSERT INTO "users"
  ("email", "encrypted_password", "created_at", "updated_at") VALUES
  ($1, $2, $3, $4) RETURNING "id"  [["email", "test1603@test.com"],
  ["encrypted_password",
  "$2a$11$K2fQmO4GcnwH3egXLDzJr.KGERWoMR93tF9Vp7OMNxqVE7KPVKfwm"],
  ["created_at", "2017-11-13 13:03:56.876695"], ["updated_at",
  "2017-11-13 13:03:56.876695"]]    (0.5ms)  COMMIT    (0.0ms)  BEGIN

  (0.5ms)  COMMIT Completed 200 OK in 218ms (Views: 0.3ms |
  ActiveRecord: 3.0ms)

答: Remove attr_accessor from your model

Body:
I am using Rails 5.1, I added devise for user authentication. I added some extra attributes to my table. After I create a new user via ajax User created but some attribute is missing. I checked the log, devise doesn't send these columns in the insert query.

First I added the devise_parameter_sanitizer to my application controller :

before_action :configure_permitted_parameters, if: :devise_controller?

protected

def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up, keys: [:email,:password1,:password2,:title,:phone, :first_name , :last_name, :postalcode, :address,:coordinate, :latitude, :longitude])
end

I added attr_accessor to my User model:

attr_accessor :password1,:password2, :phone, :postalcode, :first_name,
  :last_name, :address

end following code my create methods in registration controller :

    @user = User.new
    @user.email = params[:sign_up][:email]
    @user.password = params[:sign_up][:password1]
    @user.password_confirmation =params[:sign_up][:password2]
    @user.phone = params[:sign_up][:phone]
    @firstname = params[:sign_up][:first_name]
    @user.first_name = @firstname
    @user.last_name = params[:sign_up][:last_name]
    @user.postalcode = params[:sign_up][:postalcode]

    @coordinate = Geocoder.coordinates(params[:sign_up][:postalcode])

    @user.coordinate = @coordinate
    @user.latitude = @coordinate[0]
    @user.longitude = @coordinate[1]
    @user.address = params[:sign_up][:address]

    @user.valid?
    if @user.errors.blank?

      @user.save
    end

I am seeing following log in my console :

SQL (0.5ms)  INSERT INTO "users" ("email", "encrypted_password",
  "created_at", "updated_at", "user_role", "latitude", "longitude",
  "coordinate") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"
  [["email", "jd@gmail.com"], ["encrypted_password",
  "$2a$11$Rsn8pM0wVfiRAHwMQ/8YTeYGDn6qzAvZEFPJjqq4Ri.xZfGdof9f6"],
  ["created_at", "2017-11-13 12:07:27.781262"], ["updated_at",
  "2017-11-13 12:07:27.781262"], ["user_role", "t"], ["latitude",
  53.3960084], ["longitude", -2.929237], ["coordinate", "[53.3960084, -2.929237]"]]

And why is my code save coorditanes, longitute and lattitude attributes to db and dont save first_name, last_name and address attributes?  How can I fix this?
Best

EDITED :
My js code :

            $.ajax({
            type: "POST",
            url: "/users",
            data: {
                sign_up: {
                    first_name: $('#firstname').val(),
                    last_name: $('#lastname').val(),
                    email: $('#email').val(),
                    password1: $('#password1').val(),
                    password2: $('#password2').val(),
                    postalcode: $('#postalcode').val(),
                    phone: $('#phone').val(),
                    website: $('#website').val(),
                    title: $('#title').val(),
                    address: $('#address').val(),
                }
            },

My User Shcema

create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "superadmin_role"
t.boolean "user_role"
t.string "first_name"
t.string "last_name"
t.string "phone"
t.string "post_code"
t.float "latitude"
t.float "longitude"
t.string "coordinate"
t.string "address"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

EDITED 2 :
I made test with  :

 @u = User.create(first_name: params[:sign_up][:first_name], email:
 params[:sign_up][:email], password: params[:sign_up][:password1])
 @u.save!

and de result is

Parameters: {"sign_up"=>{"first_name"=>"", "last_name"=>"Onder",
  "email"=>"Test1603@test.com", "password1"=>"[FILTERED]",
  "password2"=>"[FILTERED]", "postalcode"=>"L16 2WA", "phone"=>"123456",
  "address"=>"address"}}    (0.5ms)  BEGIN   User Exists (0.5ms)  SELECT
  1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email",
  "test1603@test.com"], ["LIMIT", 1]]   SQL (1.0ms)  INSERT INTO "users"
  ("email", "encrypted_password", "created_at", "updated_at") VALUES
  ($1, $2, $3, $4) RETURNING "id"  [["email", "test1603@test.com"],
  ["encrypted_password",
  "$2a$11$K2fQmO4GcnwH3egXLDzJr.KGERWoMR93tF9Vp7OMNxqVE7KPVKfwm"],
  ["created_at", "2017-11-13 13:03:56.876695"], ["updated_at",
  "2017-11-13 13:03:56.876695"]]    (0.5ms)  COMMIT    (0.0ms)  BEGIN

  (0.5ms)  COMMIT Completed 200 OK in 218ms (Views: 0.3ms |
  ActiveRecord: 3.0ms)

Body: Remove attr_accessor from your model


问:
jQuery $(this) works in Firefox; fails the second time in Internet Explorer?
My little jQuery snippet works great in Firefox; but fails in IE.  This is particularly annoying and mysterious because a very similar command, just a few lines earlier, does work in IE.  Any ideas?</p>

```<code>$('.bio_text').clone()
   .each ( function(index, value) {
     name = $(this).find('.lc_name').text();
       // Prior line works just fine

     name = '<span class="lc_name">' + name + '</span>';
     title = $(this).find('.lc_title').text();
       // Prior line fails in IE and doesn't execute anything further,
       //  as determined by sprinkling alert() statements after every line

     title = '<div class="lc_title">' + title + '</div>';
     $('<li>' + name + title + '</li>').appendTo('ul#nav_team');
    });
</code>```

答:
Could $(this).find('.lc_title'). be returning multiple items (or no items) and therefore effecting the .text() funciton? Just a thought...

Could be worth seperating out the line and inspecting what is being brought back (F12 in IE8).

Body:
My little jQuery snippet works great in Firefox; but fails in IE.  This is particularly annoying and mysterious because a very similar command, just a few lines earlier, does work in IE.  Any ideas?

$('.bio_text').clone()
   .each ( function(index, value) {
     name = $(this).find('.lc_name').text();
       // Prior line works just fine

     name = '' + name + '';
     title = $(this).find('.lc_title').text();
       // Prior line fails in IE and doesn't execute anything further,
       //  as determined by sprinkling alert() statements after every line

     title = '
' + title + '
';
     $('
' + name + title + '
').appendTo('ul#nav_team');
    });


问:
Updating Netbeans C++ Makefile
I added some outside library files to my C++ project in netbeans within my Source folder. However the makefile doesnt seem to build them. I cant figure out how to add them to my makefile to have them included in the build. Has anyone done this before?

Thanks!

答:
Did you add it as source files or as compiled library?

Source files: You need to add them to your Netbeans project (not only place them into the folder). Otherwise they aren't compiled when building it.

Compiled library: This typically needs two settings: Add the library to the linker (Build -> Linker -> Libraries) and add the libraries header path to the include path (Build -> C++ Compiler -> Include Directories)

Title: Updating Netbeans C++ Makefile


问:
Run combination of methods based on user input?
Assuming I have 4 methods

```<code>methodA()
methodB()
methodC()
methodD()
</code>```

Now I want the user to be able to input a number to run a combination of the methods.

So the user can choose if they want to run:

methodA() and methodB()

or:

methodB(), methodC() and methodD()

or just one of the methods or all of them.

Is there any other possibility than specifying any possible combination in if-statements?

答:
You could use a bitmask.  In that way one number could represent multiple flags that indicate which methods get called.  A quick google search returned the following:

http://drumcoder.co.uk/blog/2010/jan/06/bitmasks-java/ Explains some solutions for this problem, which is what I think you're facing.

If you need to store multiple boolean flags for something, you can do
  it using bits and storing that inside a single integer.

Body:
Assuming I have 4 methods

methodA()
methodB()
methodC()
methodD()

Now I want the user to be able to input a number to run a combination of the methods.

So the user can choose if they want to run:

methodA() and methodB()

or:

methodB(), methodC() and methodD()

or just one of the methods or all of them.

Is there any other possibility than specifying any possible combination in if-statements?


问:
Docker port 80:80 127.0.0.1
Im having a huge issue and I can't get round it

Basically i went through the Laravel installation and installed homestead 7 and im using virtual box... vagrant

Now before this I'm using docker to run other application through it... which worked and it looks like something i've done is using the same port so I now cant use docker on that port

Cannot start service website: driver failed programming external connectivity on endpoint distinctly_website_1 (edc81f653cb3ac8c2af9b7ce070d0a0ccbb3ec255af452338ff4677ce99b156a): Error starting userland proxy: Bind for 0.0.0.0:80: unexpected error (Failure EADDRINUSE)
  ERROR: Encountered errors while bringing up the project.

I just need some help with removing this conflict with the port so I can run my docker applications. I dont care about anything than docker

答:
Just use a different port on your host when running the container. something like docker run -p 8080:80 IMAGE_NAME.

So your container will be available on the host on port 8080, but it talks to the container (and application) on port 80.

Title: Docker port 80:80 127.0.0.1


问:
Send email from outlook by including dataframe as table in R
I have a dataframe as shown below. I am then converting the dataframe into an html table.

```<code># Use RDCOMClient to send email from outlook
library(RDCOMClient)
# Use xtable to convert dataframe into html table
library(xtable)

# Create dataframe
df <- as.data.frame(mtcars[1:3,1:3])

# Create HTML object
df_html <- xtable(df)
</code>```

Now, I am sending an email from outlook using the wonderful solution given in the email thread Sending email in R via outlook

```<code>## init com api
OutApp <- COMCreate("Outlook.Application")
## create an email
outMail = OutApp$CreateItem(0)
## configure  email parameter
outMail[["To"]] = "dest@dest.com"
outMail[["subject"]] = "some subject"
outMail[["body"]] = df_html
## send it
outMail$Send()
</code>```

For the body of my email, I want the data frame df which I want to attach as a html table. When I execute the above code, I get the below error message.

```<code>Error in `[[<-`(`*tmp*`, "body", value = list(mpg = c(21, 21, 22.8), cyl = c(6,  :
  Can't attach the RDCOMServer package needed to create a generic COM object
In addition: Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘RDCOMServer’
</code>```

When I change the line outMail[["body"]] = df_html to outMail[["body"]] = paste0(df_html), I get the email but the output does not come as a table. It comes as shown below in my outlook.

```<code>c(21, 21, 22.8), c(6, 6, 4), c(160, 160, 108)
</code>```

I want this to be a table. How can i achieve this? Thanks!

答:
I finally found a solution to pasting a dataframe as an HTML table in Microsoft outlook. This is using the xtable package. Part of the solution credit goes to @lukeA from here - How to show an excel worksheet in outlook body by R

Below is the solution.

```<code>library(RDCOMClient)
library(xtable)

x <- head(mtcars)
y <- print(xtable(x), type="html", print.results=FALSE)

body <- paste0("<html>", y, "</html>")

OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)
outMail[["To"]] = "test@test.com"
outMail[["subject"]] = "TEST EMAIL"
outMail[["HTMLbody"]] = body
outMail$Send()
</code>```

This is how the output looks like in Microsoft outlook.

Body:
I have a dataframe as shown below. I am then converting the dataframe into an html table.

# Use RDCOMClient to send email from outlook
library(RDCOMClient)
# Use xtable to convert dataframe into html table
library(xtable)

# Create dataframe
df <- as.data.frame(mtcars[1:3,1:3])

# Create HTML object
df_html <- xtable(df)

Now, I am sending an email from outlook using the wonderful solution given in the email thread Sending email in R via outlook

## init com api
OutApp <- COMCreate("Outlook.Application")
## create an email
outMail = OutApp$CreateItem(0)
## configure  email parameter
outMail[["To"]] = "dest@dest.com"
outMail[["subject"]] = "some subject"
outMail[["body"]] = df_html
## send it
outMail$Send()

For the body of my email, I want the data frame df which I want to attach as a html table. When I execute the above code, I get the below error message.

Error in `[[<-`(`*tmp*`, "body", value = list(mpg = c(21, 21, 22.8), cyl = c(6,  :
  Can't attach the RDCOMServer package needed to create a generic COM object
In addition: Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘RDCOMServer’

When I change the line outMail[["body"]] = df_html to outMail[["body"]] = paste0(df_html), I get the email but the output does not come as a table. It comes as shown below in my outlook.

c(21, 21, 22.8), c(6, 6, 4), c(160, 160, 108)

I want this to be a table. How can i achieve this? Thanks!

Body:
I finally found a solution to pasting a dataframe as an HTML table in Microsoft outlook. This is using the xtable package. Part of the solution credit goes to @lukeA from here - How to show an excel worksheet in outlook body by R

Below is the solution.

library(RDCOMClient)
library(xtable)

x <- head(mtcars)
y <- print(xtable(x), type="html", print.results=FALSE)

body <- paste0("<html>", y, "</html>")

OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)
outMail[["To"]] = "test@test.com"
outMail[["subject"]] = "TEST EMAIL"
outMail[["HTMLbody"]] = body
outMail$Send()

This is how the output looks like in Microsoft outlook.


问:
Dump a pandas DataFrame which contains column name as "name" to mysql table
I am trying to dump my crawled data to mysql using pandas and to_sql.

I am approaching in two ways
1>

```<code>{# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import MySQLdb
from sqlalchemy import create_engine
import os
from pandas.io import sql
import MySQLdb

columns_list= ['persons','c_number','name']
df = pd.DataFrame()
file_name = "/home/*****/****/data.xlsx"
data = pd.read_excel(file_name)
df = df.append(data)
df.columns = columns_list
engine=create_engine('mysql+mysqldb://root:root@localhost:3306/database_name?charset=utf8&use_unicode=1', echo=False)
con = MySQLdb.connect(host="localhost",user="user_name",passwd="password",                db="database_name")
df.to_sql(con=con, name='table_name',if_exists='replace',flavor='mysql')}
</code>```

Here I am getting TypeError: to_sql() got multiple values for keyword argument 'name' error

2>

```<code>import numpy as np
import pandas as pd
import MySQLdb
from sqlalchemy import create_engine
import os

columns_list= ['persons','c_number','name']
df = pd.DataFrame()
file_name = "data.xlsx"
data = pd.read_excel(file_name)
df = df.append(data)
df_n = pd.DataFrame()
df = df_n.append(df_new)
df = np.array_split(df, 100)
for x in range(len(df_new)):
    print x
    engine = create_engine('mysql+mysqldb://user_name:password@localhost:3306/database_name?charset=utf8&use_unicode=1', echo=False)
    df[x].to_sql(name='table_name', con=engine, if_exists = 'append', index=False)
    engine.dispose()
</code>```

This way I am able to dump the data but name field I am getting Null in all records.

Is there a way to dump the data using column name "name"

答:
I think you have a typo there since you have written df inside the to_sql method, try:
df.to_sql(con=con, name='table_name',if_exists='replace',flavor='mysql')

Body:
I am trying to dump my crawled data to mysql using pandas and to_sql.

I am approaching in two ways
1>

{# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import MySQLdb
from sqlalchemy import create_engine
import os
from pandas.io import sql
import MySQLdb

columns_list= ['persons','c_number','name']
df = pd.DataFrame()
file_name = "/home/*****/****/data.xlsx"
data = pd.read_excel(file_name)
df = df.append(data)
df.columns = columns_list
engine=create_engine('mysql+mysqldb://root:root@localhost:3306/database_name?charset=utf8&use_unicode=1', echo=False)
con = MySQLdb.connect(host="localhost",user="user_name",passwd="password",                db="database_name")
df.to_sql(con=con, name='table_name',if_exists='replace',flavor='mysql')}

Here I am getting TypeError: to_sql() got multiple values for keyword argument 'name' error

2>

import numpy as np
import pandas as pd
import MySQLdb
from sqlalchemy import create_engine
import os

columns_list= ['persons','c_number','name']
df = pd.DataFrame()
file_name = "data.xlsx"
data = pd.read_excel(file_name)
df = df.append(data)
df_n = pd.DataFrame()
df = df_n.append(df_new)
df = np.array_split(df, 100)
for x in range(len(df_new)):
    print x
    engine = create_engine('mysql+mysqldb://user_name:password@localhost:3306/database_name?charset=utf8&use_unicode=1', echo=False)
    df[x].to_sql(name='table_name', con=engine, if_exists = 'append', index=False)
    engine.dispose()

This way I am able to dump the data but name field I am getting Null in all records.

Is there a way to dump the data using column name "name"


问:
ToggleButton image does not maintain aspect ratio
The two toggle buttons don't maintain aspect ratio. How can I make it a square? It shouldn't fill the width but just wrap it's content.

```<code>            <LinearLayout
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_marginTop="24dp"
                android:orientation="horizontal">

                <ToggleButton
                    android:id="@+id/btn1"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_weight="1"
                    android:textOff=""
                    android:scaleType="centerCrop"
                    android:textOn=""
                    android:layout_margin="8dp"
                    android:background="@drawable/feedback_btn_selector"
                    />

                <ToggleButton
                    android:id="@+id/btn2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_weight="1"
                    android:scaleType="centerCrop"
                    android:layout_margin="8dp"
                    android:background="@drawable/feedback_btn_selector" />
            </LinearLayout>
</code>```

feedback_btn_selector

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_pressed="true" android:drawable="@drawable/btn_average" />
    <item android:state_pressed="true" android:drawable="@drawable/btn_average"/>
    <item android:state_checked="true" android:drawable="@drawable/btn_average"/>
    <item android:drawable="@drawable/btn_average_selected"/>
</selector>
</code>```

drawable-xhdpi:

答:
Try this code : </p>

```<code> <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:orientation="horizontal">

        <ToggleButton
            android:id="@+id/btn1"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:textOff=""
            android:scaleType="centerCrop"
            android:textOn=""
            android:layout_margin="8dp"
            android:background="@drawable/feedback_btn_selector"
            />

        <ToggleButton
            android:id="@+id/btn2"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:scaleType="centerCrop"
            android:layout_margin="8dp"
            android:background="@drawable/feedback_btn_selector" />
    </LinearLayout>
</code>```

Body:
The two toggle buttons don't maintain aspect ratio. How can I make it a square? It shouldn't fill the width but just wrap it's content.

            <LinearLayout
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_marginTop="24dp"
                android:orientation="horizontal">

                <ToggleButton
                    android:id="@+id/btn1"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_weight="1"
                    android:textOff=""
                    android:scaleType="centerCrop"
                    android:textOn=""
                    android:layout_margin="8dp"
                    android:background="@drawable/feedback_btn_selector"
                    />

                <ToggleButton
                    android:id="@+id/btn2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_weight="1"
                    android:scaleType="centerCrop"
                    android:layout_margin="8dp"
                    android:background="@drawable/feedback_btn_selector" />
            </LinearLayout>

feedback_btn_selector

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_pressed="true" android:drawable="@drawable/btn_average" />
    <item android:state_pressed="true" android:drawable="@drawable/btn_average"/>
    <item android:state_checked="true" android:drawable="@drawable/btn_average"/>
    <item android:drawable="@drawable/btn_average_selected"/>
</selector>

drawable-xhdpi:

Body:
Try this code :

 <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:orientation="horizontal">

        <ToggleButton
            android:id="@+id/btn1"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:textOff=""
            android:scaleType="centerCrop"
            android:textOn=""
            android:layout_margin="8dp"
            android:background="@drawable/feedback_btn_selector"
            />

        <ToggleButton
            android:id="@+id/btn2"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:scaleType="centerCrop"
            android:layout_margin="8dp"
            android:background="@drawable/feedback_btn_selector" />
    </LinearLayout>


问:
SQL/ASP - Invalid column name 'Email'
i am having trouble adding stuff into the Email column. I can add stuff into the Username column but for some reason i get the following error:

```<code>Microsoft OLE DB Provider for SQL Server error '80040e14'
Invalid column name 'Email'.
</code>```

When I use this code:

```<code>Set rstSimple = cnnSimple.Execute("insert into SALT (Email, Username, FirstName, LastName, ActivationCode, TransactionID, ClientID) VALUES ('" & Request.QueryString("payer_email") & "','" & Request.QueryString("payer_email") & "','" & Request.QueryString("first_name") & "','" & Request.QueryString("last_name") & "','" & Request.QueryString("hash") & "','" & Request.QueryString("txn_id") & "','" & Request.QueryString("client_id") & "')")
</code>```

Can somebody please help me?

Thank you

答:
I just encountered a similar problem today... reading values off the MSSQL database, the "Email" column  is coming up blank/null in my ASP program.

But checking the table using SQL Enterprise Manager shows there is data in the "Email" column.

I couldn't find anything wrong with my code and I'm running out of ideas. Just for the heck of it, I tried to rename the field "Email" to something else, like "UserEmail". And voila!!!! My code is working again.

So try renaming your column "Email" to something else. I did some search and couldn't find anything that says "Email" is a reserved word in MSSQL and that you can't use "Email" for column names.

Title: SQL/ASP - Invalid column name 'Email'

Body:
i am having trouble adding stuff into the Email column. I can add stuff into the Username column but for some reason i get the following error:

Microsoft OLE DB Provider for SQL Server error '80040e14'
Invalid column name 'Email'.

When I use this code:

Set rstSimple = cnnSimple.Execute("insert into SALT (Email, Username, FirstName, LastName, ActivationCode, TransactionID, ClientID) VALUES ('" & Request.QueryString("payer_email") & "','" & Request.QueryString("payer_email") & "','" & Request.QueryString("first_name") & "','" & Request.QueryString("last_name") & "','" & Request.QueryString("hash") & "','" & Request.QueryString("txn_id") & "','" & Request.QueryString("client_id") & "')")

Can somebody please help me?

Thank you