问:
Android firebase getting null
I'm using Firebase to save my data. I'm trying to separate Firebase methods and my methods on the activity. For example i have created class that called "FirebaseMethodsHelper" and there i want to write all the Firebase methods.
For example, "getAllUsers" method that should return in list all the users.
The only problem i have that it does not working.

I dont know what im doing wrong, so if you guys please can help me.

Fragment

```<code>  public class MyPlayListFragment extends Fragment {
    private FirebaseDatabase refToVideos;
    private FirebaseUser currentUser;
    private ArrayList<Video> videosList;
    private VideoViewAdapter adapter;
    private RecyclerView rvVideos;
    private List<Video> checkList;

public MyPlayListFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_my_play_list, container, false);
    rvVideos = (RecyclerView)v.findViewById(R.id.rvVideos);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    videosList = new ArrayList<>();
    refToVideos = FirebaseDatabase.getInstance();
    currentUser = FirebaseAuth.getInstance().getCurrentUser();

    FirebaseMethodsHelper fmh = new FirebaseMethodsHelper();

    checkList = fmh.getAllVideosFromDB(currentUser);
    if(checkList != null)
    Log.d("checkList",checkList.toString());
</code>```

FirebaseMethodHelper Class

```<code>   public class FirebaseMethodsHelper {
private FirebaseDatabase databaseRef;
private ArrayList<User> usersList;
private ArrayList<Video> videosList;

   public List<Video> getAllVideosFromDB(FirebaseUser currentUser){
        databaseRef = FirebaseDatabase.getInstance();
        databaseRef.getReference(Params.VIDEOS).child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    videosList.add(snapshot.getValue(Video.class));
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

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

I dont know why, but it always return null.

答:
This is a classic problem with asynchronous web APIs: you cannot return something now that hasn't been loaded yet.

Firebase Database (and most modern web APIs) data is loaded asynchronously, since it may take some time. Instead of waiting for the data (which would lead to Application Not Responding dialogs for your users), your main application code continues while the data is loaded on a secondary thread. Then when the data is available, your onDataChange() method is called and can use the data.

This changes the flow of your app. The easiest way to see this is by placing a few log statements:

```<code>public List<Video> getAllVideosFromDB(FirebaseUser currentUser){
    databaseRef = FirebaseDatabase.getInstance();
    System.out.println("Before attaching listener");
    databaseRef.getReference(Params.VIDEOS).child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            System.out.println("Got data");
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore errors
        }
    });
    System.out.println("After attaching listener");
}
</code>```

Running this code will print the following sequence:

Before attaching listener

After attaching listener

Got data

This is probably not what you expected, but explains precisely why the array is empty when you return it.

The initial response for most developers is to try and "fix" this asynchronous behavior. I recommend against that: the web is asynchronous, and the sooner you accept that, the sooner you can learn how to become productive with modern web APIs.

I've found it easiest to reframe problems for this asynchronous paradigm. Instead of saying "First get all videos, then log them", I frame the problem as "Start getting all videos. When the videos are loaded, log them".

This means that any code that requires the video must be inside onDataChange() (or called from inside there). E.g.:

```<code>public List<Video> getAllVideosFromDB(FirebaseUser currentUser){
    databaseRef = FirebaseDatabase.getInstance();
    databaseRef.getReference(Params.VIDEOS).child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                videosList.add(snapshot.getValue(Video.class));
            }
            if (videosList != null) {
                Log.d("checkList",videosList.toString());
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore errors
        }
    });

}
</code>```

As I said, this is a common problem for developers who haven't dealt with asynchronous APIs before. As such, there have been quite some questions on the topic already, and I recommend you check them out too:

Setting Singleton property value in Firebase Listener

Handle data returned by an Async task (Firebase) (showing how to define and pass in your own callback)

Firebase - Android - fetchProvidersForEmail - Why are all the calls asynchronous? (with lots more links to other similar questions)

Title: Android firebase getting null

Body:
I'm using Firebase to save my data. I'm trying to separate Firebase methods and my methods on the activity. For example i have created class that called "FirebaseMethodsHelper" and there i want to write all the Firebase methods.
For example, "getAllUsers" method that should return in list all the users.
The only problem i have that it does not working.

I dont know what im doing wrong, so if you guys please can help me.

Fragment

  public class MyPlayListFragment extends Fragment {
    private FirebaseDatabase refToVideos;
    private FirebaseUser currentUser;
    private ArrayList<Video> videosList;
    private VideoViewAdapter adapter;
    private RecyclerView rvVideos;
    private List<Video> checkList;

public MyPlayListFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_my_play_list, container, false);
    rvVideos = (RecyclerView)v.findViewById(R.id.rvVideos);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    videosList = new ArrayList<>();
    refToVideos = FirebaseDatabase.getInstance();
    currentUser = FirebaseAuth.getInstance().getCurrentUser();

    FirebaseMethodsHelper fmh = new FirebaseMethodsHelper();

    checkList = fmh.getAllVideosFromDB(currentUser);
    if(checkList != null)
    Log.d("checkList",checkList.toString());

FirebaseMethodHelper Class

   public class FirebaseMethodsHelper {
private FirebaseDatabase databaseRef;
private ArrayList<User> usersList;
private ArrayList<Video> videosList;

   public List<Video> getAllVideosFromDB(FirebaseUser currentUser){
        databaseRef = FirebaseDatabase.getInstance();
        databaseRef.getReference(Params.VIDEOS).child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    videosList.add(snapshot.getValue(Video.class));
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    return videosList;
  }
 }

I dont know why, but it always return null.

Body:
This is a classic problem with asynchronous web APIs: you cannot return something now that hasn't been loaded yet.

Firebase Database (and most modern web APIs) data is loaded asynchronously, since it may take some time. Instead of waiting for the data (which would lead to Application Not Responding dialogs for your users), your main application code continues while the data is loaded on a secondary thread. Then when the data is available, your onDataChange() method is called and can use the data.

This changes the flow of your app. The easiest way to see this is by placing a few log statements:

public List<Video> getAllVideosFromDB(FirebaseUser currentUser){
    databaseRef = FirebaseDatabase.getInstance();
    System.out.println("Before attaching listener");
    databaseRef.getReference(Params.VIDEOS).child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            System.out.println("Got data");
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore errors
        }
    });
    System.out.println("After attaching listener");
}

Running this code will print the following sequence:

Before attaching listener

After attaching listener

Got data

This is probably not what you expected, but explains precisely why the array is empty when you return it.

The initial response for most developers is to try and "fix" this asynchronous behavior. I recommend against that: the web is asynchronous, and the sooner you accept that, the sooner you can learn how to become productive with modern web APIs.

I've found it easiest to reframe problems for this asynchronous paradigm. Instead of saying "First get all videos, then log them", I frame the problem as "Start getting all videos. When the videos are loaded, log them".

This means that any code that requires the video must be inside onDataChange() (or called from inside there). E.g.:

public List<Video> getAllVideosFromDB(FirebaseUser currentUser){
    databaseRef = FirebaseDatabase.getInstance();
    databaseRef.getReference(Params.VIDEOS).child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                videosList.add(snapshot.getValue(Video.class));
            }
            if (videosList != null) {
                Log.d("checkList",videosList.toString());
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore errors
        }
    });

}

As I said, this is a common problem for developers who haven't dealt with asynchronous APIs before. As such, there have been quite some questions on the topic already, and I recommend you check them out too:

Setting Singleton property value in Firebase Listener

Handle data returned by an Async task (Firebase) (showing how to define and pass in your own callback)

Firebase - Android - fetchProvidersForEmail - Why are all the calls asynchronous? (with lots more links to other similar questions)


来源: stackexchange

问:
Generate PDF with selenium chrome driver
To generate PDF from a HTML file, I want to use selenium Chrome driver.

I tried it with command line :

```<code>chrome.exe --headless --disable-gpu --print-to-pdf   file:///C:invoiceTemplate2.html
</code>```

and it works perfectly, So I wanted to do that with JAVA and here's my code :

```<code>System.setProperty("webdriver.chrome.driver", "C:/work/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--disable-gpu", "--print-to-pdf",
            "file:///C:/invoiceTemplate2.html");
WebDriver driver = new ChromeDriver(options);
driver.quit();
</code>```

The server is started with no problem, but chrome is opened with multiple tabs with the arguments I specified in Options.

Any solution to this ? thx.

答:
You have to do two things.

First: Make a screenshot using selenium.

Second: Convert that screenshot using any pdf tool, like itext. Here I am showing a complete example of how to do this.

Step 1: Download the jar of itext from here and add the jar file to your build path.

Step 2: Add this code to your project.

```<code>ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--print-to-pdf");

WebDriver driver = new ChromeDriver(options);
driver.get("file:///C:/invoiceTemplate2.html");

try {
    File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenshot, new File("screenshot.png"));
    Document document = new Document(PageSize.A4, 20, 20, 20, 20);
    PdfWriter.getInstance(document, new FileOutputStream("webaspdf.pdf"));
    document.open();
    Image image = Image.getInstance("screenshot.png");
    document.add(image);
    document.close();
}
catch (Exception e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
}
</code>```

Note: To use the mentioned itext package, add the required imports to your code.

```<code>import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
To generate PDF from a HTML file, I want to use selenium Chrome driver.

I tried it with command line :

chrome.exe --headless --disable-gpu --print-to-pdf   file:///C:invoiceTemplate2.html

and it works perfectly, So I wanted to do that with JAVA and here's my code :

System.setProperty("webdriver.chrome.driver", "C:/work/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--disable-gpu", "--print-to-pdf",
            "file:///C:/invoiceTemplate2.html");
WebDriver driver = new ChromeDriver(options);
driver.quit();

The server is started with no problem, but chrome is opened with multiple tabs with the arguments I specified in Options.

Any solution to this ? thx.

Body:
You have to do two things.

First: Make a screenshot using selenium.

Second: Convert that screenshot using any pdf tool, like itext. Here I am showing a complete example of how to do this.

Step 1: Download the jar of itext from here and add the jar file to your build path.

Step 2: Add this code to your project.

ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--print-to-pdf");

WebDriver driver = new ChromeDriver(options);
driver.get("file:///C:/invoiceTemplate2.html");

try {
    File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(screenshot, new File("screenshot.png"));
    Document document = new Document(PageSize.A4, 20, 20, 20, 20);
    PdfWriter.getInstance(document, new FileOutputStream("webaspdf.pdf"));
    document.open();
    Image image = Image.getInstance("screenshot.png");
    document.add(image);
    document.close();
}
catch (Exception e2) {
    // TODO Auto-generated catch block
    e2.printStackTrace();
}

Note: To use the mentioned itext package, add the required imports to your code.

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

ContentLicense: CC BY-SA 4.0


问:
Unable to merge dex with androidTestImplementation
I get an unable to merge dex exception when i try to run my android test together with uiAutomation.

```<code>androidTestImplementation ('com.google.android:android-test:4.1.1.4')
</code>```

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebugAndroidTest'.
  java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

However, if I change from androidTestImplementation to testCompile everything is working fine. I would be happy if someone could explain me the different behaviour between androidTestImplementation and testCompile. Secondly, how I can add this dependecy with androidTestImplementation.

```<code>buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

allprojects {
    repositories {
        maven {
            url 'https://maven.google.com'
        }

    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '4.1'
}

android {
    compileSdkVersion 27
    buildToolsVersion '26.0.2'

    dexOptions {
        javaMaxHeapSize "4g"
    }

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 27

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled = true

        vectorDrawables.useSupportLibrary = true
generatedDensities = []
    }

    // This is handled for you by the 2.0+ Gradle Plugin
    aaptOptions {
        additionalParameters "--no-version-vectors"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    buildTypes {
        debug {
            debuggable true
            shrinkResources false
            versionNameSuffix "-debug"
            minifyEnabled false

//            minifyEnabled true
//            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.txt'
//            testProguardFiles file ('test-proguard-rules.pro')
        }
        release {
            debuggable true
            minifyEnabled true
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.txt'

        }
        staging {
            // Specifies a sorted list of fallback build types that the
            // plugin should try to use when a dependency does not include a
            // "staging" build type. You may specify as many fallbacks as you
            // like, and the plugin selects the first build type that's
            // available in the dependency.
            matchingFallbacks = ['debug', 'qa', 'release']
        }

    }

    dependencies {
        compile fileTree(include: ['*.jar'], dir: 'libs')

        def playVersion = '11.6.2'
        compile 'com.j256.ormlite:ormlite-core:4.48'
        compile 'com.j256.ormlite:ormlite-android:4.48'
        compile 'com.squareup.picasso:picasso:2.5.2'

        implementation 'com.android.support:appcompat-v7:27.0.2'
        compile 'com.roomorama:caldroid:3.0.1'
        compile 'com.google.android.gms:play-services-location:' + playVersion
        compile 'com.google.android.gms:play-services-ads:' + playVersion

        compile 'com.google.android.gms:play-services-analytics:' + playVersion
        compile 'com.google.guava:guava:18.0'
        compile 'com.google.code.gson:gson:2.5'
        compile 'org.apache.commons:commons-lang3:3.4'
        compile 'org.apache.commons:commons-collections4:4.1'
        compile 'com.android.support:design:27.0.2'
        compile 'joda-time:joda-time:2.9.3'
        compile 'org.joda:joda-convert:1.8.1'
        compile group: 'com.github.chrisbanes.photoview', name: 'library', version: '1.2.4'
        compile 'com.android.support:multidex:1.0.2'

        compile 'com.amazonaws:aws-android-sdk-core:2.4.2'
        compile 'com.amazonaws:aws-android-sdk-s3:2.4.2'
        compile 'com.amazonaws:aws-android-sdk-ddb:2.4.2'
        compile 'com.google.android.gms:play-services-auth:' + playVersion

        // https://mvnrepository.com/artifact/org.simpleframework/simple-xml
        compile('org.simpleframework:simple-xml:2.7.1') {
            exclude group: 'xpp3', module: 'xpp3'
            exclude group: 'stax', module: 'stax-api'
            exclude group: 'stax', module: 'stax'
        }

        compile group: 'commons-codec', name: 'commons-codec', version: '1.3'
        compile project(':volley')
        compile project(':SimpleDTGHub')

        implementation "android.arch.lifecycle:runtime:1.0.3"
        implementation "android.arch.lifecycle:extensions:1.0.0"

        androidTestImplementation 'com.android.support:support-annotations:27.0.2'

        androidTestImplementation 'junit:junit:4.12'
        androidTestImplementation('org.robolectric:robolectric:2.4') {
            exclude group: 'commons-logging', module: 'commons-logging'
            exclude group: 'org.apache.httpcomponents', module: 'httpclient'
        }

        androidTestImplementation('com.google.android:android-test:4.1.1.4') {
            exclude group: 'org.apache.httpcomponents', module: 'httpclient'
            exclude group: 'junit', module: 'junit'
        }

        androidTestImplementation "com.android.support.test:runner:1.0.1"
        androidTestImplementation "com.android.support.test.espresso:espresso-core:3.0.1"
        androidTestImplementation 'com.android.support.test.espresso:espresso-intents:3.0.1'

    }

    android {
        packagingOptions {
            exclude 'LICENSE.txt'
            exclude 'META-INF/DEPENDENCIES.txt'
            exclude 'META-INF/LICENSE.txt'
            exclude 'META-INF/NOTICE.txt'
            exclude 'META-INF/NOTICE'
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/DEPENDENCIES'
            exclude 'META-INF/notice.txt'
            exclude 'META-INF/license.txt'
            exclude 'META-INF/dependencies.txt'
            exclude 'META-INF/inputList.txt'
            exclude 'META-INF/inputList'
            exclude 'META-INF/jersey-module-version'

        }
    }

}
repositories {
    mavenCentral()
}
dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}
</code>```

Full gradle Output:

```<code>Executing tasks: [:MyApp:assembleDebug, :MyApp:assembleDebugAndroidTest]

Configuration 'compile' in project ':MyApp' is deprecated. Use 'implementation' instead.
Configuration 'compile' in project ':SimpleDTGHub' is deprecated. Use 'implementation' instead.
Configuration 'testCompile' in project ':volley' is deprecated. Use 'testImplementation' instead.
:MyApp:preBuild UP-TO-DATE
:SimpleDTGHub:preBuild UP-TO-DATE
:SimpleDTGHub:preDebugBuild UP-TO-DATE
:SimpleDTGHub:checkDebugManifest UP-TO-DATE
:SimpleDTGHub:processDebugManifest UP-TO-DATE
:volley:preBuild UP-TO-DATE
:volley:preDebugBuild UP-TO-DATE
:volley:checkDebugManifest UP-TO-DATE
:volley:processDebugManifest UP-TO-DATE
:MyApp:preDebugBuild UP-TO-DATE
:SimpleDTGHub:compileDebugAidl UP-TO-DATE
:volley:compileDebugAidl UP-TO-DATE
:MyApp:compileDebugAidl UP-TO-DATE
:SimpleDTGHub:packageDebugRenderscript NO-SOURCE
:volley:packageDebugRenderscript NO-SOURCE
:MyApp:compileDebugRenderscript UP-TO-DATE
:MyApp:checkDebugManifest UP-TO-DATE
:MyApp:generateDebugBuildConfig UP-TO-DATE
:MyApp:generateDebugResValues UP-TO-DATE
:MyApp:generateDebugResources UP-TO-DATE
:SimpleDTGHub:compileDebugRenderscript UP-TO-DATE
:SimpleDTGHub:generateDebugResValues UP-TO-DATE
:SimpleDTGHub:generateDebugResources UP-TO-DATE
:SimpleDTGHub:packageDebugResources UP-TO-DATE
:volley:compileDebugRenderscript UP-TO-DATE
:volley:generateDebugResValues UP-TO-DATE
:volley:generateDebugResources UP-TO-DATE
:volley:packageDebugResources UP-TO-DATE
:MyApp:mergeDebugResources UP-TO-DATE
:MyApp:createDebugCompatibleScreenManifests UP-TO-DATE
:MyApp:processDebugManifest UP-TO-DATE
:MyApp:splitsDiscoveryTaskDebug UP-TO-DATE
:SimpleDTGHub:platformAttrExtractor UP-TO-DATE
:SimpleDTGHub:processDebugResources UP-TO-DATE
:volley:platformAttrExtractor UP-TO-DATE
:volley:processDebugResources UP-TO-DATE
:MyApp:processDebugResources UP-TO-DATE
:SimpleDTGHub:generateDebugBuildConfig UP-TO-DATE
:SimpleDTGHub:compileDebugKotlin UP-TO-DATE
:SimpleDTGHub:prepareLintJar UP-TO-DATE
:SimpleDTGHub:generateDebugSources UP-TO-DATE
:SimpleDTGHub:javaPreCompileDebug UP-TO-DATE
:SimpleDTGHub:compileDebugJavaWithJavac UP-TO-DATE
:SimpleDTGHub:processDebugJavaRes NO-SOURCE
:SimpleDTGHub:transformClassesAndResourcesWithPrepareIntermediateJarsForDebug UP-TO-DATE
:volley:generateDebugBuildConfig UP-TO-DATE
:volley:prepareLintJar UP-TO-DATE
:volley:generateDebugSources UP-TO-DATE
:volley:javaPreCompileDebug UP-TO-DATE
:volley:compileDebugJavaWithJavac UP-TO-DATE
:volley:processDebugJavaRes NO-SOURCE
:volley:transformClassesAndResourcesWithPrepareIntermediateJarsForDebug UP-TO-DATE
:MyApp:compileDebugKotlin
:MyApp:prepareLintJar UP-TO-DATE
:MyApp:generateDebugSources UP-TO-DATE
:MyApp:javaPreCompileDebug
:MyApp:compileDebugJavaWithJavac
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
:MyApp:compileDebugNdk NO-SOURCE
:MyApp:compileDebugSources
:MyApp:mergeDebugShaders UP-TO-DATE
:MyApp:compileDebugShaders UP-TO-DATE
:MyApp:generateDebugAssets UP-TO-DATE
:SimpleDTGHub:mergeDebugShaders UP-TO-DATE
:SimpleDTGHub:compileDebugShaders UP-TO-DATE
:SimpleDTGHub:generateDebugAssets UP-TO-DATE
:SimpleDTGHub:mergeDebugAssets UP-TO-DATE
:volley:mergeDebugShaders UP-TO-DATE
:volley:compileDebugShaders UP-TO-DATE
:volley:generateDebugAssets UP-TO-DATE
:volley:mergeDebugAssets UP-TO-DATE
:MyApp:mergeDebugAssets UP-TO-DATE
:MyApp:transformClassesWithStackFramesFixerForDebug UP-TO-DATE
:MyApp:transformClassesWithDesugarForDebug UP-TO-DATE
:MyApp:transformClassesWithDexBuilderForDebug UP-TO-DATE
:MyApp:transformDexArchiveWithExternalLibsDexMergerForDebug UP-TO-DATE
:MyApp:transformDexArchiveWithDexMergerForDebug UP-TO-DATE
:MyApp:mergeDebugJniLibFolders UP-TO-DATE
:SimpleDTGHub:compileDebugNdk NO-SOURCE
:SimpleDTGHub:mergeDebugJniLibFolders UP-TO-DATE
:SimpleDTGHub:transformNativeLibsWithMergeJniLibsForDebug UP-TO-DATE
:SimpleDTGHub:transformNativeLibsWithIntermediateJniLibsForDebug UP-TO-DATE
:volley:compileDebugNdk NO-SOURCE
:volley:mergeDebugJniLibFolders UP-TO-DATE
:volley:transformNativeLibsWithMergeJniLibsForDebug UP-TO-DATE
:volley:transformNativeLibsWithIntermediateJniLibsForDebug UP-TO-DATE
:MyApp:transformNativeLibsWithMergeJniLibsForDebug UP-TO-DATE
:MyApp:processDebugJavaRes NO-SOURCE
:MyApp:transformResourcesWithMergeJavaResForDebug UP-TO-DATE
:MyApp:validateSigningDebug
:MyApp:packageDebug UP-TO-DATE
:MyApp:assembleDebug
:MyApp:bundleAppClassesDebug UP-TO-DATE
:MyApp:preDebugAndroidTestBuild
:MyApp:compileDebugAndroidTestAidl UP-TO-DATE
:MyApp:processDebugAndroidTestManifest UP-TO-DATE
:MyApp:compileDebugAndroidTestRenderscript UP-TO-DATE
:MyApp:generateDebugAndroidTestBuildConfig UP-TO-DATE
:MyApp:generateDebugAndroidTestResValues UP-TO-DATE
:MyApp:generateDebugAndroidTestResources UP-TO-DATE
:MyApp:mergeDebugAndroidTestResources UP-TO-DATE
:MyApp:splitsDiscoveryTaskDebugAndroidTest UP-TO-DATE
:MyApp:processDebugAndroidTestResources UP-TO-DATE
:MyApp:compileDebugAndroidTestKotlin
:MyApp:generateDebugAndroidTestSources UP-TO-DATE
:MyApp:javaPreCompileDebugAndroidTest
:MyApp:compileDebugAndroidTestJavaWithJavac
:MyApp:compileDebugAndroidTestNdk NO-SOURCE
:MyApp:compileDebugAndroidTestSources
:MyApp:mergeDebugAndroidTestShaders UP-TO-DATE
:MyApp:compileDebugAndroidTestShaders UP-TO-DATE
:MyApp:generateDebugAndroidTestAssets UP-TO-DATE
:MyApp:mergeDebugAndroidTestAssets UP-TO-DATE
:MyApp:transformClassesWithStackFramesFixerForDebugAndroidTest UP-TO-DATE
:MyApp:transformClassesWithDesugarForDebugAndroidTest UP-TO-DATE
:MyApp:transformClassesWithDexBuilderForDebugAndroidTest UP-TO-DATE
:MyApp:transformDexArchiveWithExternalLibsDexMergerForDebugAndroidTest FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':MyApp:transformDexArchiveWithExternalLibsDexMergerForDebugAndroidTest'.
> java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 7s

87 actionable tasks: 9 executed, 78 up-to-date
</code>```

答:
The root cause was an conflict of the XmlPullParserException class. This class is part of the xxp3 dependency and part of org.simpleframework.simplexml.

```<code>+--- com.google.android:android-test:4.1.1.4
|    +--- com.google.android:android:4.1.1.4
|    |    +--- commons-logging:commons-logging:1.1.1
|    |    +--- org.apache.httpcomponents:httpclient:4.0.1
|    |    |    +--- org.apache.httpcomponents:httpcore:4.0.1
|    |    |    +--- commons-logging:commons-logging:1.1.1
|    |    |    \--- commons-codec:commons-codec:1.3
|    |    +--- org.khronos:opengl-api:gl1.1-android-2.1_r1
|    |    +--- xerces:xmlParserAPIs:2.6.2
|    |    +--- xpp3:xpp3:1.1.4c
</code>```

To solve this issue I had to exclude the dependecy from com.google.android:android-test.

```<code> androidTestImplementation('com.google.android:android-test:4.1.1.4'){
            exclude group: 'xpp3'
        }
</code>```

Body:
I get an unable to merge dex exception when i try to run my android test together with uiAutomation.

androidTestImplementation ('com.google.android:android-test:4.1.1.4')

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebugAndroidTest'.
  java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

However, if I change from androidTestImplementation to testCompile everything is working fine. I would be happy if someone could explain me the different behaviour between androidTestImplementation and testCompile. Secondly, how I can add this dependecy with androidTestImplementation.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

allprojects {
    repositories {
        maven {
            url 'https://maven.google.com'
        }

    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '4.1'
}

android {
    compileSdkVersion 27
    buildToolsVersion '26.0.2'

    dexOptions {
        javaMaxHeapSize "4g"
    }

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 27

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled = true

        vectorDrawables.useSupportLibrary = true
generatedDensities = []
    }

    // This is handled for you by the 2.0+ Gradle Plugin
    aaptOptions {
        additionalParameters "--no-version-vectors"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    buildTypes {
        debug {
            debuggable true
            shrinkResources false
            versionNameSuffix "-debug"
            minifyEnabled false

//            minifyEnabled true
//            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.txt'
//            testProguardFiles file ('test-proguard-rules.pro')
        }
        release {
            debuggable true
            minifyEnabled true
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.txt'

        }
        staging {
            // Specifies a sorted list of fallback build types that the
            // plugin should try to use when a dependency does not include a
            // "staging" build type. You may specify as many fallbacks as you
            // like, and the plugin selects the first build type that's
            // available in the dependency.
            matchingFallbacks = ['debug', 'qa', 'release']
        }

    }

    dependencies {
        compile fileTree(include: ['*.jar'], dir: 'libs')

        def playVersion = '11.6.2'
        compile 'com.j256.ormlite:ormlite-core:4.48'
        compile 'com.j256.ormlite:ormlite-android:4.48'
        compile 'com.squareup.picasso:picasso:2.5.2'

        implementation 'com.android.support:appcompat-v7:27.0.2'
        compile 'com.roomorama:caldroid:3.0.1'
        compile 'com.google.android.gms:play-services-location:' + playVersion
        compile 'com.google.android.gms:play-services-ads:' + playVersion

        compile 'com.google.android.gms:play-services-analytics:' + playVersion
        compile 'com.google.guava:guava:18.0'
        compile 'com.google.code.gson:gson:2.5'
        compile 'org.apache.commons:commons-lang3:3.4'
        compile 'org.apache.commons:commons-collections4:4.1'
        compile 'com.android.support:design:27.0.2'
        compile 'joda-time:joda-time:2.9.3'
        compile 'org.joda:joda-convert:1.8.1'
        compile group: 'com.github.chrisbanes.photoview', name: 'library', version: '1.2.4'
        compile 'com.android.support:multidex:1.0.2'

        compile 'com.amazonaws:aws-android-sdk-core:2.4.2'
        compile 'com.amazonaws:aws-android-sdk-s3:2.4.2'
        compile 'com.amazonaws:aws-android-sdk-ddb:2.4.2'
        compile 'com.google.android.gms:play-services-auth:' + playVersion

        // https://mvnrepository.com/artifact/org.simpleframework/simple-xml
        compile('org.simpleframework:simple-xml:2.7.1') {
            exclude group: 'xpp3', module: 'xpp3'
            exclude group: 'stax', module: 'stax-api'
            exclude group: 'stax', module: 'stax'
        }

        compile group: 'commons-codec', name: 'commons-codec', version: '1.3'
        compile project(':volley')
        compile project(':SimpleDTGHub')

        implementation "android.arch.lifecycle:runtime:1.0.3"
        implementation "android.arch.lifecycle:extensions:1.0.0"

        androidTestImplementation 'com.android.support:support-annotations:27.0.2'

        androidTestImplementation 'junit:junit:4.12'
        androidTestImplementation('org.robolectric:robolectric:2.4') {
            exclude group: 'commons-logging', module: 'commons-logging'
            exclude group: 'org.apache.httpcomponents', module: 'httpclient'
        }

        androidTestImplementation('com.google.android:android-test:4.1.1.4') {
            exclude group: 'org.apache.httpcomponents', module: 'httpclient'
            exclude group: 'junit', module: 'junit'
        }

        androidTestImplementation "com.android.support.test:runner:1.0.1"
        androidTestImplementation "com.android.support.test.espresso:espresso-core:3.0.1"
        androidTestImplementation 'com.android.support.test.espresso:espresso-intents:3.0.1'

    }

    android {
        packagingOptions {
            exclude 'LICENSE.txt'
            exclude 'META-INF/DEPENDENCIES.txt'
            exclude 'META-INF/LICENSE.txt'
            exclude 'META-INF/NOTICE.txt'
            exclude 'META-INF/NOTICE'
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/DEPENDENCIES'
            exclude 'META-INF/notice.txt'
            exclude 'META-INF/license.txt'
            exclude 'META-INF/dependencies.txt'
            exclude 'META-INF/inputList.txt'
            exclude 'META-INF/inputList'
            exclude 'META-INF/jersey-module-version'

        }
    }

}
repositories {
    mavenCentral()
}
dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}

Full gradle Output:

Executing tasks: [:MyApp:assembleDebug, :MyApp:assembleDebugAndroidTest]

Configuration 'compile' in project ':MyApp' is deprecated. Use 'implementation' instead.
Configuration 'compile' in project ':SimpleDTGHub' is deprecated. Use 'implementation' instead.
Configuration 'testCompile' in project ':volley' is deprecated. Use 'testImplementation' instead.
:MyApp:preBuild UP-TO-DATE
:SimpleDTGHub:preBuild UP-TO-DATE
:SimpleDTGHub:preDebugBuild UP-TO-DATE
:SimpleDTGHub:checkDebugManifest UP-TO-DATE
:SimpleDTGHub:processDebugManifest UP-TO-DATE
:volley:preBuild UP-TO-DATE
:volley:preDebugBuild UP-TO-DATE
:volley:checkDebugManifest UP-TO-DATE
:volley:processDebugManifest UP-TO-DATE
:MyApp:preDebugBuild UP-TO-DATE
:SimpleDTGHub:compileDebugAidl UP-TO-DATE
:volley:compileDebugAidl UP-TO-DATE
:MyApp:compileDebugAidl UP-TO-DATE
:SimpleDTGHub:packageDebugRenderscript NO-SOURCE
:volley:packageDebugRenderscript NO-SOURCE
:MyApp:compileDebugRenderscript UP-TO-DATE
:MyApp:checkDebugManifest UP-TO-DATE
:MyApp:generateDebugBuildConfig UP-TO-DATE
:MyApp:generateDebugResValues UP-TO-DATE
:MyApp:generateDebugResources UP-TO-DATE
:SimpleDTGHub:compileDebugRenderscript UP-TO-DATE
:SimpleDTGHub:generateDebugResValues UP-TO-DATE
:SimpleDTGHub:generateDebugResources UP-TO-DATE
:SimpleDTGHub:packageDebugResources UP-TO-DATE
:volley:compileDebugRenderscript UP-TO-DATE
:volley:generateDebugResValues UP-TO-DATE
:volley:generateDebugResources UP-TO-DATE
:volley:packageDebugResources UP-TO-DATE
:MyApp:mergeDebugResources UP-TO-DATE
:MyApp:createDebugCompatibleScreenManifests UP-TO-DATE
:MyApp:processDebugManifest UP-TO-DATE
:MyApp:splitsDiscoveryTaskDebug UP-TO-DATE
:SimpleDTGHub:platformAttrExtractor UP-TO-DATE
:SimpleDTGHub:processDebugResources UP-TO-DATE
:volley:platformAttrExtractor UP-TO-DATE
:volley:processDebugResources UP-TO-DATE
:MyApp:processDebugResources UP-TO-DATE
:SimpleDTGHub:generateDebugBuildConfig UP-TO-DATE
:SimpleDTGHub:compileDebugKotlin UP-TO-DATE
:SimpleDTGHub:prepareLintJar UP-TO-DATE
:SimpleDTGHub:generateDebugSources UP-TO-DATE
:SimpleDTGHub:javaPreCompileDebug UP-TO-DATE
:SimpleDTGHub:compileDebugJavaWithJavac UP-TO-DATE
:SimpleDTGHub:processDebugJavaRes NO-SOURCE
:SimpleDTGHub:transformClassesAndResourcesWithPrepareIntermediateJarsForDebug UP-TO-DATE
:volley:generateDebugBuildConfig UP-TO-DATE
:volley:prepareLintJar UP-TO-DATE
:volley:generateDebugSources UP-TO-DATE
:volley:javaPreCompileDebug UP-TO-DATE
:volley:compileDebugJavaWithJavac UP-TO-DATE
:volley:processDebugJavaRes NO-SOURCE
:volley:transformClassesAndResourcesWithPrepareIntermediateJarsForDebug UP-TO-DATE
:MyApp:compileDebugKotlin
:MyApp:prepareLintJar UP-TO-DATE
:MyApp:generateDebugSources UP-TO-DATE
:MyApp:javaPreCompileDebug
:MyApp:compileDebugJavaWithJavac
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
:MyApp:compileDebugNdk NO-SOURCE
:MyApp:compileDebugSources
:MyApp:mergeDebugShaders UP-TO-DATE
:MyApp:compileDebugShaders UP-TO-DATE
:MyApp:generateDebugAssets UP-TO-DATE
:SimpleDTGHub:mergeDebugShaders UP-TO-DATE
:SimpleDTGHub:compileDebugShaders UP-TO-DATE
:SimpleDTGHub:generateDebugAssets UP-TO-DATE
:SimpleDTGHub:mergeDebugAssets UP-TO-DATE
:volley:mergeDebugShaders UP-TO-DATE
:volley:compileDebugShaders UP-TO-DATE
:volley:generateDebugAssets UP-TO-DATE
:volley:mergeDebugAssets UP-TO-DATE
:MyApp:mergeDebugAssets UP-TO-DATE
:MyApp:transformClassesWithStackFramesFixerForDebug UP-TO-DATE
:MyApp:transformClassesWithDesugarForDebug UP-TO-DATE
:MyApp:transformClassesWithDexBuilderForDebug UP-TO-DATE
:MyApp:transformDexArchiveWithExternalLibsDexMergerForDebug UP-TO-DATE
:MyApp:transformDexArchiveWithDexMergerForDebug UP-TO-DATE
:MyApp:mergeDebugJniLibFolders UP-TO-DATE
:SimpleDTGHub:compileDebugNdk NO-SOURCE
:SimpleDTGHub:mergeDebugJniLibFolders UP-TO-DATE
:SimpleDTGHub:transformNativeLibsWithMergeJniLibsForDebug UP-TO-DATE
:SimpleDTGHub:transformNativeLibsWithIntermediateJniLibsForDebug UP-TO-DATE
:volley:compileDebugNdk NO-SOURCE
:volley:mergeDebugJniLibFolders UP-TO-DATE
:volley:transformNativeLibsWithMergeJniLibsForDebug UP-TO-DATE
:volley:transformNativeLibsWithIntermediateJniLibsForDebug UP-TO-DATE
:MyApp:transformNativeLibsWithMergeJniLibsForDebug UP-TO-DATE
:MyApp:processDebugJavaRes NO-SOURCE
:MyApp:transformResourcesWithMergeJavaResForDebug UP-TO-DATE
:MyApp:validateSigningDebug
:MyApp:packageDebug UP-TO-DATE
:MyApp:assembleDebug
:MyApp:bundleAppClassesDebug UP-TO-DATE
:MyApp:preDebugAndroidTestBuild
:MyApp:compileDebugAndroidTestAidl UP-TO-DATE
:MyApp:processDebugAndroidTestManifest UP-TO-DATE
:MyApp:compileDebugAndroidTestRenderscript UP-TO-DATE
:MyApp:generateDebugAndroidTestBuildConfig UP-TO-DATE
:MyApp:generateDebugAndroidTestResValues UP-TO-DATE
:MyApp:generateDebugAndroidTestResources UP-TO-DATE
:MyApp:mergeDebugAndroidTestResources UP-TO-DATE
:MyApp:splitsDiscoveryTaskDebugAndroidTest UP-TO-DATE
:MyApp:processDebugAndroidTestResources UP-TO-DATE
:MyApp:compileDebugAndroidTestKotlin
:MyApp:generateDebugAndroidTestSources UP-TO-DATE
:MyApp:javaPreCompileDebugAndroidTest
:MyApp:compileDebugAndroidTestJavaWithJavac
:MyApp:compileDebugAndroidTestNdk NO-SOURCE
:MyApp:compileDebugAndroidTestSources
:MyApp:mergeDebugAndroidTestShaders UP-TO-DATE
:MyApp:compileDebugAndroidTestShaders UP-TO-DATE
:MyApp:generateDebugAndroidTestAssets UP-TO-DATE
:MyApp:mergeDebugAndroidTestAssets UP-TO-DATE
:MyApp:transformClassesWithStackFramesFixerForDebugAndroidTest UP-TO-DATE
:MyApp:transformClassesWithDesugarForDebugAndroidTest UP-TO-DATE
:MyApp:transformClassesWithDexBuilderForDebugAndroidTest UP-TO-DATE
:MyApp:transformDexArchiveWithExternalLibsDexMergerForDebugAndroidTest FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':MyApp:transformDexArchiveWithExternalLibsDexMergerForDebugAndroidTest'.
> java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 7s

87 actionable tasks: 9 executed, 78 up-to-date

Body:
The root cause was an conflict of the XmlPullParserException class. This class is part of the xxp3 dependency and part of org.simpleframework.simplexml.

+--- com.google.android:android-test:4.1.1.4
|    +--- com.google.android:android:4.1.1.4
|    |    +--- commons-logging:commons-logging:1.1.1
|    |    +--- org.apache.httpcomponents:httpclient:4.0.1
|    |    |    +--- org.apache.httpcomponents:httpcore:4.0.1
|    |    |    +--- commons-logging:commons-logging:1.1.1
|    |    |    \--- commons-codec:commons-codec:1.3
|    |    +--- org.khronos:opengl-api:gl1.1-android-2.1_r1
|    |    +--- xerces:xmlParserAPIs:2.6.2
|    |    +--- xpp3:xpp3:1.1.4c

To solve this issue I had to exclude the dependecy from com.google.android:android-test.

 androidTestImplementation('com.google.android:android-test:4.1.1.4'){
            exclude group: 'xpp3'
        }


问:
RPC semantics of gRPC
I am trying the find out what RPC semantics the gRPC library provides? Is it at-most once? Does it guarantee that an RPC call made by a client is not executed more than once on a server? I couldn't find this explicitly mentioned anywhere in the docs.

From what I understand, gRPC channels have an exponential back-off based retry mechanism of re-initiating TCP connections after transient failures. So, if a server fails after executing an RPC call but before responding, and later comes back up, a client RPC may end up getting executed twice.

Can someone throw more light on this?

答:
From what I understand, gRPC channels have an exponential back-off based retry mechanism of re-initiating TCP connections after transient failures.

I think, that GRPC clients are pretty flexible, and you can try to disable retry attempts with https://godoc.org/google.golang.org/grpc#FailOnNonTempDialError

Though you'll have to care about retries on your own.

Title: RPC semantics of gRPC


问:
Is it better practice to maintain specialised log tables or calculate number of entries with each sql
I've been looking through some open source projects such as SMF forums etc and noticed that it incorporates specialised log tables that store just what seems like counts of boards, member, topics and even search results.

Currently in my projects I don't use such tables at all and instead make use of SQL_CALC_ROWS or COUNT in order to get total number of entries for a search query etc. I'm assuming that this is a bit of an over head on its own and was wondering if using log tables are an effective solution or is it vice versa.

Likewise I also have used the same method in a web application which could do with a speed boost. What are the overheads in executing specialised sql queries using GROUP_CONCAT, COUNT etc as opposed to setting up a program to automatically update a numeric count in a certain table when required.

For example if on one page I need to show statistics like number of members, number of classifeds entry and last active users - I normally execute a SQL_CALC_ROWS + FOUND_ROWS in mysql.

答: I agree with Mark, if tables are large enough it can be really slow to count every time. Depending on how up to date stats you want you can chose from some approaches. Like update stats everyday, than stats wont be accurate all the time but its probably least costly option. Another possibility is recalculate stats when you are changing dataset. But if there are lots of inserts/deletes this might get slow.</p>

ContentLicense: CC BY-SA 2.5


答:
It is returning null because the list videosList has not been initialized yet. Also, your approach for returning the list in your method is wrong. The firebase call is asynchronous, and thus you can't control when the data will be available, so almost everytime your method will return null(if the list has not been initialized) or empty list(in-case you initialized it).

A solution would be to use interface callback, this will return the list of videos to your fragment as desired:

```<code>public interface FirebaseCallback {
    void listVideos(ArrayList<Video> videos);
}
</code>```

This method will be called from your FirebaseMethodHelper class:

```<code>public void getAllVideosFromDB(FirebaseUser currentUser, FirebaseCallback callback){
    databaseRef = FirebaseDatabase.getInstance();
    databaseRef.getReference(Params.VIDEOS).child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ArrayList<Video> videosList = new ArrayList<>();

            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                videosList.add(snapshot.getValue(Video.class));
            }

            callback.listVideos(videosList);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
</code>```

And from your fragment, you implement the interface and pass this to the method like so:

```<code>public class MyPlayListFragment extends Fragment implements FirebaseCallback  {
    private FirebaseDatabase refToVideos;
    private FirebaseUser currentUser;
    private ArrayList<Video> videosList;
    private VideoViewAdapter adapter;
    private RecyclerView rvVideos;
    private List<Video> checkList;

public MyPlayListFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_my_play_list, container, false);
    rvVideos = (RecyclerView)v.findViewById(R.id.rvVideos);

    return v;
}
@Override
public void listVideos(ArrayList<Video> videos) {
    //do what you want with the videos
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    videosList = new ArrayList<>();
    refToVideos = FirebaseDatabase.getInstance();
    currentUser = FirebaseAuth.getInstance().getCurrentUser();

    FirebaseMethodsHelper fmh = new FirebaseMethodsHelper();

    checkList = fmh.getAllVideosFromDB(currentUser, this);
    if(checkList != null)
    Log.d("checkList",checkList.toString());
</code>```

Title: Android firebase getting null

Body:
It is returning null because the list videosList has not been initialized yet. Also, your approach for returning the list in your method is wrong. The firebase call is asynchronous, and thus you can't control when the data will be available, so almost everytime your method will return null(if the list has not been initialized) or empty list(in-case you initialized it).

A solution would be to use interface callback, this will return the list of videos to your fragment as desired:

public interface FirebaseCallback {
    void listVideos(ArrayList<Video> videos);
}

This method will be called from your FirebaseMethodHelper class:

public void getAllVideosFromDB(FirebaseUser currentUser, FirebaseCallback callback){
    databaseRef = FirebaseDatabase.getInstance();
    databaseRef.getReference(Params.VIDEOS).child(currentUser.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            ArrayList<Video> videosList = new ArrayList<>();

            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                videosList.add(snapshot.getValue(Video.class));
            }

            callback.listVideos(videosList);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

And from your fragment, you implement the interface and pass this to the method like so:

public class MyPlayListFragment extends Fragment implements FirebaseCallback  {
    private FirebaseDatabase refToVideos;
    private FirebaseUser currentUser;
    private ArrayList<Video> videosList;
    private VideoViewAdapter adapter;
    private RecyclerView rvVideos;
    private List<Video> checkList;

public MyPlayListFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_my_play_list, container, false);
    rvVideos = (RecyclerView)v.findViewById(R.id.rvVideos);

    return v;
}
@Override
public void listVideos(ArrayList<Video> videos) {
    //do what you want with the videos
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    videosList = new ArrayList<>();
    refToVideos = FirebaseDatabase.getInstance();
    currentUser = FirebaseAuth.getInstance().getCurrentUser();

    FirebaseMethodsHelper fmh = new FirebaseMethodsHelper();

    checkList = fmh.getAllVideosFromDB(currentUser, this);
    if(checkList != null)
    Log.d("checkList",checkList.toString());


问:
F# - Apply Function To Two Arrays Of Different Lengths
I am trying to apply a function to two arrays of different lengths but the result is not matching my expectations. I need to reuse elements of the second array (similar to R) to complete the expression:

```<code>module SOQN =

open System

let first = [|2; 3; 5; 7; 11|]
let second = [|13; 17; 19|]

let result =
    [for i in [0..first.Length-1] do
        for j in [0..second.Length-1] do
            yield (first.[i] * second.[j])]

printfn "Result: %A" result

// Actual Result: [|26; 34; 38; 39; 51; 57; 65; 85; 95; 91; 119; 133; 143; 187; 209|]
// Expected Result: [|26; 51; 95; 91; 187|]
</code>```

What am I missing?

答:
I guess you looking for something like this</p>

```<code>let result =
    Array.mapi
        (fun i v -> second.[i % second.Length] * v) first
</code>```

Body:
I am trying to apply a function to two arrays of different lengths but the result is not matching my expectations. I need to reuse elements of the second array (similar to R) to complete the expression:

module SOQN =

open System

let first = [|2; 3; 5; 7; 11|]
let second = [|13; 17; 19|]

let result =
    [for i in [0..first.Length-1] do
        for j in [0..second.Length-1] do
            yield (first.[i] * second.[j])]

printfn "Result: %A" result

// Actual Result: [|26; 34; 38; 39; 51; 57; 65; 85; 95; 91; 119; 133; 143; 187; 209|]
// Expected Result: [|26; 51; 95; 91; 187|]

What am I missing?

Body:
I guess you looking for something like this

let result =
    Array.mapi
        (fun i v -> second.[i % second.Length] * v) first


问:
Seting list in hibernate native query does not work
I am new to Hibernate and based upon the documentation for native query, I expected following code to execute.

```<code>public boolean markStatusById(List<Integer> list, String newStatus) throws Exception {
        boolean statusUpdated = false;
        try {
            entityManager.createQuery("UPDATE MyTableEntity SET status = :newStatus WHERE my_table_id in (?1)",
                    MyTableEntity .class)
                    .setParameter(newStatus, newStatus)
                    .setParameter(1, list);
            statusUpdated = true;
        } catch (IllegalArgumentException | TransactionRequiredException e) {
            throw new Exception(CLASS_NAME,"markStatusById", e);
        }
        return statusUpdated;
    }
</code>```

However, for some reason, this does not work.

What is the correct way to achieve what is intended in above query. One of My Reference

答:
Once you define your query, you need to run it.
For an update use:

```<code>int updateCount = entityManager.executeUpdate();
</code>```

A small tip on the side is, before you set the statusUpdated, you would want to check whether updateCount is > 0.

And one more tip based on the JPA recommendations, when you want to run a DML query (UPDATE / DELETE) it is advised to run that operation is a separate transaction. In your case, if you are using spring for example would be to set the propagation level on that method to REQUIRES_NEW:

```<code>@Transactional(propagation=Propagation.REQUIRES_NEW)
public boolean markStatusById(List<Integer> list, String newStatus)
</code>```

this is due to the fact that those kind of queries ommit the persistence context which is not updated.

Body:
I am new to Hibernate and based upon the documentation for native query, I expected following code to execute.

public boolean markStatusById(List<Integer> list, String newStatus) throws Exception {
        boolean statusUpdated = false;
        try {
            entityManager.createQuery("UPDATE MyTableEntity SET status = :newStatus WHERE my_table_id in (?1)",
                    MyTableEntity .class)
                    .setParameter(newStatus, newStatus)
                    .setParameter(1, list);
            statusUpdated = true;
        } catch (IllegalArgumentException | TransactionRequiredException e) {
            throw new Exception(CLASS_NAME,"markStatusById", e);
        }
        return statusUpdated;
    }

However, for some reason, this does not work.

What is the correct way to achieve what is intended in above query. One of My Reference

Body:
Once you define your query, you need to run it.
For an update use:

int updateCount = entityManager.executeUpdate();

A small tip on the side is, before you set the statusUpdated, you would want to check whether updateCount is > 0.

And one more tip based on the JPA recommendations, when you want to run a DML query (UPDATE / DELETE) it is advised to run that operation is a separate transaction. In your case, if you are using spring for example would be to set the propagation level on that method to REQUIRES_NEW:

@Transactional(propagation=Propagation.REQUIRES_NEW)
public boolean markStatusById(List<Integer> list, String newStatus)

this is due to the fact that those kind of queries ommit the persistence context which is not updated.


问:
When does docker-compose build a local image and when does it pull from docker hub?
Following the tutorial of docker compose. Let's say you have a Dockerfile for your app and docker-compose.yml for its services.

Dockerfile

```<code>FROM ruby:2.3.3
...
COPY . /myapp
</code>```

docker-compose.yml

```<code>version: '3'
services:
  db:
    image: postgres
  web:
    build: .
    image: dre-hh/myapp
    volumes:
      - .:/myapp

    depends_on:
      - db
</code>```

While developing you would like to build the app from the local filesystem with docker-compose. Then later you could upload the app docker image to docker hub.

Do you need separted overridable configurations if you want to choose between building from local system or from docker hub? Or is it possible
somehow else as one can specify both build and image options on the yaml file?

答:
When using build: with image:, the image name is simply to let you choose which name that docker-compose will tag the image as.
To push images, you should use a different config / build workflow, as lvonet mentioned

Body:
Following the tutorial of docker compose. Let's say you have a Dockerfile for your app and docker-compose.yml for its services.

Dockerfile

FROM ruby:2.3.3
...
COPY . /myapp

docker-compose.yml

version: '3'
services:
  db:
    image: postgres
  web:
    build: .
    image: dre-hh/myapp
    volumes:
      - .:/myapp

    depends_on:
      - db

While developing you would like to build the app from the local filesystem with docker-compose. Then later you could upload the app docker image to docker hub.

Do you need separted overridable configurations if you want to choose between building from local system or from docker hub? Or is it possible
somehow else as one can specify both build and image options on the yaml file?


问:
my add form is not showing
I am developing Zend Framework App.

In my indexcontroller view views/scripts/index/index.phtml

```<code><p><a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'add'));?>">Add new album</a></p>
</code>```

in my browser is is outputting me only url path so it is not going to the add action.
Here it is my add action in IndexController.php

```<code> public function addAction()
    {
        // action body
        $form = new Application_Form_User();
        $form->submit->setLabel('Add');
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $artist = $form->getValue('artist');
                $title = $form->getValue('title');
                $albums = new Application_Model_DbTable_Albums();
                $albums->addUser($artist, $title);
                $this->_helper->redirector('index');
            } else {
                $form->populate($formData);
            }
        }
    }
</code>```

and my add.phtml is

```<code><?php
$this->title = "Add new album";
$this->headTitle($this->title);
echo $this->form ;
?>
</code>```

why it is not going to add action. please suggest
Edit More Info

and i am using this pdf to build the app http://akrabat.com/wp-content/uploads/Getting-Started-with-Zend-Framework.pdf

In page No. 9
I am not getting where to put this line and is these lines are necessary or not ?

```<code>$view = new Zend_View();
$view->setScriptPath('/path/to/scripts');
echo $view->render('script.php');
</code>```

and i haven't set the layout and CSS .but my listing from Database is coming but my add Dction is not working ? Please suggest why

答:
Enable error reporting in your bootstrap or anywhere for that matter:

```<code>error_reporting(E_ALL);
ini_set('display_errors', true);
</code>```

Or check your php error logs and post here what error message you got

Title: my add form is not showing

Body:
I am developing Zend Framework App.

In my indexcontroller view views/scripts/index/index.phtml

<a href="<?php echo $this->url(array('controller'=>'index',
'action'=>'add'));?>">Add new album

in my browser is is outputting me only url path so it is not going to the add action.
Here it is my add action in IndexController.php

 public function addAction()
    {
        // action body
        $form = new Application_Form_User();
        $form->submit->setLabel('Add');
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                $artist = $form->getValue('artist');
                $title = $form->getValue('title');
                $albums = new Application_Model_DbTable_Albums();
                $albums->addUser($artist, $title);
                $this->_helper->redirector('index');
            } else {
                $form->populate($formData);
            }
        }
    }

and my add.phtml is

<?php
$this->title = "Add new album";
$this->headTitle($this->title);
echo $this->form ;
?>

why it is not going to add action. please suggest
Edit More Info

and i am using this pdf to build the app http://akrabat.com/wp-content/uploads/Getting-Started-with-Zend-Framework.pdf

In page No. 9
I am not getting where to put this line and is these lines are necessary or not ?

$view = new Zend_View();
$view->setScriptPath('/path/to/scripts');
echo $view->render('script.php');

and i haven't set the layout and CSS .but my listing from Database is coming but my add Dction is not working ? Please suggest why

Body:
Enable error reporting in your bootstrap or anywhere for that matter:

error_reporting(E_ALL);
ini_set('display_errors', true);

Or check your php error logs and post here what error message you got


问:
Should I keep the proportion of categories when executing an stratification?
I have 30,000 phrases categorized by sentiment.

I'm gonna use Naive Bayes.

Here's the proportion (sentiment -> number of phrases).

```<code>anger           98
boredom        157
empty          659
enthusiasm     522
fun           1088
happiness     2986
hate          1187
love          2068
neutral       6340
relief        1021
sadness       4828
surprise      1613
worry         7433
</code>```

So, I have to split my dataset into train/test to execute my model, etc, right?

Should I keep the proportion of the categories when executing the stratification?

I mean, if I pick 30% for the test sample, should I keep 30% of each sentiment instead of 30% of the whole dataset?

I guess yes, but I would like to have a more experienced opinion.

And how would you do that? Anyone here know a better way of doing that instead of executing a python loop, testing which sentiment, calculate 30%, put in a dictionary etc?

Is there any Pandas trick to stratify by a category feature, keeping the proportion?

答:
Should I keep the proportion of the categories when executing the stratification?

You seem a little confused regarding the terminology; the very definition of stratification (or stratified sampling) is exactly to maintain the proportions, otherwise it is simple random sampling.

if I pick 30% for the test sample, should I keep 30% of each sentiment instead of 30% of the whole dataset?

They are not contradictory, are they? If you keep 30% of each category, won't you end up with the 30% of your initial set?

Is there any Pandas trick to stratify by a category feature, keeping the proportion?

Don't know about pandas, but scikit-learn (which I guess you are going to use next) model_selection.train_test_split includes such a stratify option:

```<code>from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    stratify=y,
                                                    test_size=0.3)
</code>```

Body:
I have 30,000 phrases categorized by sentiment.

I'm gonna use Naive Bayes.

Here's the proportion (sentiment -> number of phrases).

anger           98
boredom        157
empty          659
enthusiasm     522
fun           1088
happiness     2986
hate          1187
love          2068
neutral       6340
relief        1021
sadness       4828
surprise      1613
worry         7433

So, I have to split my dataset into train/test to execute my model, etc, right?

Should I keep the proportion of the categories when executing the stratification?

I mean, if I pick 30% for the test sample, should I keep 30% of each sentiment instead of 30% of the whole dataset?

I guess yes, but I would like to have a more experienced opinion.

And how would you do that? Anyone here know a better way of doing that instead of executing a python loop, testing which sentiment, calculate 30%, put in a dictionary etc?

Is there any Pandas trick to stratify by a category feature, keeping the proportion?

Body:
Should I keep the proportion of the categories when executing the stratification?

You seem a little confused regarding the terminology; the very definition of stratification (or stratified sampling) is exactly to maintain the proportions, otherwise it is simple random sampling.

if I pick 30% for the test sample, should I keep 30% of each sentiment instead of 30% of the whole dataset?

They are not contradictory, are they? If you keep 30% of each category, won't you end up with the 30% of your initial set?

Is there any Pandas trick to stratify by a category feature, keeping the proportion?

Don't know about pandas, but scikit-learn (which I guess you are going to use next) model_selection.train_test_split includes such a stratify option:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    stratify=y,
                                                    test_size=0.3)


问:
Computing difference between averages by group and logical values using dplyr
Does anyone know of a way to use dplyr to compute the difference between averages for some_var == TRUE and some_var == FALSE, grouped by a third variable?

For example, given the following example dataframe:

```<code>library('dplyr')

dat <- iris %>%
     mutate(wide=Sepal.Width > 3) %>%
     group_by(Species, wide) %>%
     summarize(mean_width=mean(Sepal.Width))

dat

# A tibble: 6 x 3
# Groups:   Species [?]
     Species  wide mean_width
      <fctr> <lgl>      <dbl>
1     setosa FALSE   2.900000
2     setosa  TRUE   3.528571
3 versicolor FALSE   2.688095
4 versicolor  TRUE   3.200000
5  virginica FALSE   2.800000
6  virginica  TRUE   3.311765
</code>```

Does anyone know of a way to derive a new data frame with the differences for wide == TRUE and wide == FALSE, by Species?

This can be done using several statements:

```<code>false_vals <- dat %>% filter(wide==FALSE)
true_vals <- dat %>% filter(wide==TRUE)

diff <- data.frame(Species=unique(dat$Species), diff=true_vals$mean_width - false_vals$mean_width)

> diff
     Species      diff
1     setosa 0.6285714
2 versicolor 0.5119048
3  virginica 0.5117647
</code>```

However, this seems like something that should be achievable directly with dplyr.

Any ideas?

答:
Using spread() from  tidyr package:

```<code>library(tidyr)

iris %>% mutate(wide=Sepal.Width > 3) %>%
        group_by(Species, wide) %>%
        summarize(mean_width=mean(Sepal.Width)) %>%
        spread(wide, mean_width) %>%
        summarise(diff = `TRUE` - `FALSE`)
#     Species      diff
#1     setosa 0.6285714
#2 versicolor 0.5119048
#3  virginica 0.5117647
</code>```

Body:
Does anyone know of a way to use dplyr to compute the difference between averages for some_var == TRUE and some_var == FALSE, grouped by a third variable?

For example, given the following example dataframe:

library('dplyr')

dat <- iris %>%
     mutate(wide=Sepal.Width > 3) %>%
     group_by(Species, wide) %>%
     summarize(mean_width=mean(Sepal.Width))

dat

# A tibble: 6 x 3
# Groups:   Species [?]
     Species  wide mean_width
      <fctr> <lgl>      <dbl>
1     setosa FALSE   2.900000
2     setosa  TRUE   3.528571
3 versicolor FALSE   2.688095
4 versicolor  TRUE   3.200000
5  virginica FALSE   2.800000
6  virginica  TRUE   3.311765

Does anyone know of a way to derive a new data frame with the differences for wide == TRUE and wide == FALSE, by Species?

This can be done using several statements:

false_vals <- dat %>% filter(wide==FALSE)
true_vals <- dat %>% filter(wide==TRUE)

diff <- data.frame(Species=unique(dat$Species), diff=true_vals$mean_width - false_vals$mean_width)

> diff
     Species      diff
1     setosa 0.6285714
2 versicolor 0.5119048
3  virginica 0.5117647

However, this seems like something that should be achievable directly with dplyr.

Any ideas?

Body:
Using spread() from  tidyr package:

library(tidyr)

iris %>% mutate(wide=Sepal.Width > 3) %>%
        group_by(Species, wide) %>%
        summarize(mean_width=mean(Sepal.Width)) %>%
        spread(wide, mean_width) %>%
        summarise(diff = `TRUE` - `FALSE`)
#     Species      diff
#1     setosa 0.6285714
#2 versicolor 0.5119048
#3  virginica 0.5117647


问:
Number which occurs only once in the array

Possible Duplicate:

  Finding a single number in a list

Given an array of numbers, except for one number all the others, occur
twice. What should be the algorithm to find that number which occurs only once in the
array?

Example

```<code>a[1..n] = [1,2,3,4,3,1,2]
</code>```

should return 4

答:
If you have quantities which cannot be reasonably xored (Big Integers or numbers represented as Strings, for example), an alternate approach which is also O(n) time, (but O(n) space rather than O(1) space) would be to simply use a hash table.  The algorithm looks like:

```<code>Create a hash table of the same size as the list
For every item in the list:
     If item is a key in hash table
         then remove item from hash table
         else add item to hash table with nominal value
At the end, there should be exactly one item in the hash table
</code>```

I would do, C or C++ code, but neither of them have hash tables built in.  (Don't ask me why C++ doesn't have a hash table in the STL, but does have a hash map based on a red-black tree, because I have no idea what they were thinking.)  And, unfortunately, I don't have a C# compiler handy to test for syntax errors, so I'm giving you Java code.  It's pretty similar, though.

```<code>import java.util.Hashtable;
import java.util.List;

class FindUnique {
    public static <T> T findUnique(List<T> list) {
        Hashtable<T,Character> ht = new Hashtable<T,Character>(list.size());
        for (T item : list) {
            if (ht.containsKey(item)) {
                ht.remove(item);
            } else {
                ht.put(item,'x');
            }
        }
        return ht.keys().nextElement();
    }
}
</code>```

Body:
Possible Duplicate:

  Finding a single number in a list

Given an array of numbers, except for one number all the others, occur
twice. What should be the algorithm to find that number which occurs only once in the
array?

Example

a[1..n] = [1,2,3,4,3,1,2]

should return 4

Body:
If you have quantities which cannot be reasonably xored (Big Integers or numbers represented as Strings, for example), an alternate approach which is also O(n) time, (but O(n) space rather than O(1) space) would be to simply use a hash table.  The algorithm looks like:

Create a hash table of the same size as the list
For every item in the list:
     If item is a key in hash table
         then remove item from hash table
         else add item to hash table with nominal value
At the end, there should be exactly one item in the hash table

I would do, C or C++ code, but neither of them have hash tables built in.  (Don't ask me why C++ doesn't have a hash table in the STL, but does have a hash map based on a red-black tree, because I have no idea what they were thinking.)  And, unfortunately, I don't have a C# compiler handy to test for syntax errors, so I'm giving you Java code.  It's pretty similar, though.

import java.util.Hashtable;
import java.util.List;

class FindUnique {
    public static <T> T findUnique(List<T> list) {
        Hashtable<T,Character> ht = new Hashtable<T,Character>(list.size());
        for (T item : list) {
            if (ht.containsKey(item)) {
                ht.remove(item);
            } else {
                ht.put(item,'x');
            }
        }
        return ht.keys().nextElement();
    }
}


问:
Floating Div Causing Trouble
I seem to have gotten into a peculiar problem with a floating div. The example of the div is at this website

What i am unable to accomplish is to convert the menu contained in the div into a responsive stackable burger menu.

I'll really appreciate your help on this.

Best wishes,
Sumit

答:
You hide the large menu, and show the stackable burger, on small screen. This can be done by using just CSS.

Mobile first, so basically:

```<code>.largeMenuDiv { display: none }

@media ( min-width: 480px ) {

    .largeMenuDiv    { display: block; }
    .stackableBurger { display: none; }

}
</code>```

Of course you can JavaScript the menu to morph on different screen sizes, but it's more complicated IMO.

Title: Floating Div Causing Trouble

Body:
You hide the large menu, and show the stackable burger, on small screen. This can be done by using just CSS.

Mobile first, so basically:

.largeMenuDiv { display: none }

@media ( min-width: 480px ) {

    .largeMenuDiv    { display: block; }
    .stackableBurger { display: none; }

}

Of course you can JavaScript the menu to morph on different screen sizes, but it's more complicated IMO.


问:
Convert an object to datetime in python
I have a dataframe like the one below.  How can I transform the reviewTime column to date format?  Currently, the reviewTime is an object.

```<code> overall    reviewTime
 6          10 19,2013
 5          06 18, 2014
 4          05 5, 2013
</code>```

overall           1682 non-null object
reviewTime        1682 non-null object

答:
You can use following code:

```<code>import datetime

a='12 19,2013' #sample input

a=a.split()
a[1]=a[1].split(',')
b=[]
b.append(int(a[0]))
b.append(int(a[1][0]))
b.append(int(a[1][1]))

t=datetime.date(b[2],b[0],b[1])

print(t)
</code>```

Result:

```<code>2013-12-19
</code>```

Title: Convert an object to datetime in python

Body:
I have a dataframe like the one below.  How can I transform the reviewTime column to date format?  Currently, the reviewTime is an object.

 overall    reviewTime
 6          10 19,2013
 5          06 18, 2014
 4          05 5, 2013

overall           1682 non-null object
reviewTime        1682 non-null object

Body:
You can use following code:

import datetime

a='12 19,2013' #sample input

a=a.split()
a[1]=a[1].split(',')
b=[]
b.append(int(a[0]))
b.append(int(a[1][0]))
b.append(int(a[1][1]))

t=datetime.date(b[2],b[0],b[1])

print(t)

Result:

2013-12-19


问:
How do I enforce readonlyness of ref readonly in C# 7.2?
I want to write a method returning ref a ref readonly as described: "The feature allows a member to return variables by reference without exposing them to mutations."

Unfortunately, my code compiles and does such a mutation. How do I make sure it cannot be modified? It is readonly for good reasons. I expect a compiler error. Should I doe something in addition? 200 is modified to 201. I do not want that.

```<code>internal class TryClass
{
    private static int _result = 0;

    public static ref readonly int Multiply(int a, int b)
    {
        _result = a * b;
        return ref _result;
    }
}

internal class Program
{
    private static void Main(string[] args)
    {
        int x = 10;
        int y = 20;
        var rez = TryClass.Multiply(x, y);
        rez++;
        Console.WriteLine(rez);
        Console.ReadLine();
    }
}
</code>```

答:
Based on the comments. This is is the solution. I get the compiler error I expect: "Severity    Code    Description Project File    Line    Suppression State
Error   CS8329  Cannot use method 'TryClass.Multiply(int, int)' as a ref or out value because it is a readonly variable"</p>

```<code>internal class Program
{
    private static void Main(string[] args)
    {
        int x = 10;
        int y = 20;
        ref readonly var rez = ref TryClass.Multiply(x, y);
        rez++;
        Console.WriteLine(rez);
        TryClass.DoAfter();
        Console.ReadLine();
    }
}
</code>```

Body:
I want to write a method returning ref a ref readonly as described: "The feature allows a member to return variables by reference without exposing them to mutations."

Unfortunately, my code compiles and does such a mutation. How do I make sure it cannot be modified? It is readonly for good reasons. I expect a compiler error. Should I doe something in addition? 200 is modified to 201. I do not want that.

internal class TryClass
{
    private static int _result = 0;

    public static ref readonly int Multiply(int a, int b)
    {
        _result = a * b;
        return ref _result;
    }
}

internal class Program
{
    private static void Main(string[] args)
    {
        int x = 10;
        int y = 20;
        var rez = TryClass.Multiply(x, y);
        rez++;
        Console.WriteLine(rez);
        Console.ReadLine();
    }
}

Body:
Based on the comments. This is is the solution. I get the compiler error I expect: "Severity    Code    Description Project File    Line    Suppression State
Error   CS8329  Cannot use method 'TryClass.Multiply(int, int)' as a ref or out value because it is a readonly variable"

internal class Program
{
    private static void Main(string[] args)
    {
        int x = 10;
        int y = 20;
        ref readonly var rez = ref TryClass.Multiply(x, y);
        rez++;
        Console.WriteLine(rez);
        TryClass.DoAfter();
        Console.ReadLine();
    }
}


答:
Replace all , and spaces by '', then use pd.to_datetime with format specified i.e

```<code>df['reviewTimeclean'] = pd.to_datetime(df['reviewTime'].str.replace('[,\s]',''),format='%m%d%Y')

# Also pd.to_datetime(df['reviewTime'].str.replace('[^\d]',''),format='%m%d%Y')

    overall   reviewTime reviewTimeclean
0        6   10 19,2013      2013-10-19
1        5  06 18, 2014      2014-06-18
2        4   05 5, 2013      2013-05-05
</code>```

Title: Convert an object to datetime in python

Body:
Replace all , and spaces by '', then use pd.to_datetime with format specified i.e

df['reviewTimeclean'] = pd.to_datetime(df['reviewTime'].str.replace('[,\s]',''),format='%m%d%Y')

# Also pd.to_datetime(df['reviewTime'].str.replace('[^\d]',''),format='%m%d%Y')

    overall   reviewTime reviewTimeclean
0        6   10 19,2013      2013-10-19
1        5  06 18, 2014      2014-06-18
2        4   05 5, 2013      2013-05-05


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

data = {'overall': {0: 6, 1: 5, 2: 4},
        'reviewTime': {0: '10 19,2013', 1: '06 18, 2014', 2: '05 5, 2013'}}

df = pd.DataFrame(data)

# Clean
df.reviewTime = df.reviewTime.apply(lambda x: ' '.join(i.strip() for i in x.split(",")))

# To_datetime and apply (commented out)
df.reviewTime = pd.to_datetime(df.reviewTime)
#df.reviewTime = df.reviewTime.apply(lambda x: datetime.datetime.strptime(x,"%m %d %Y"))

print(df)
</code>```

Returns:

```<code>   overall reviewTime
0        6 2013-10-19
1        5 2014-06-18
2        4 2013-05-05
</code>```

Title: Convert an object to datetime in python

Body:
import pandas as pd
import datetime

data = {'overall': {0: 6, 1: 5, 2: 4},
        'reviewTime': {0: '10 19,2013', 1: '06 18, 2014', 2: '05 5, 2013'}}

df = pd.DataFrame(data)

# Clean
df.reviewTime = df.reviewTime.apply(lambda x: ' '.join(i.strip() for i in x.split(",")))

# To_datetime and apply (commented out)
df.reviewTime = pd.to_datetime(df.reviewTime)
#df.reviewTime = df.reviewTime.apply(lambda x: datetime.datetime.strptime(x,"%m %d %Y"))

print(df)

Returns:

   overall reviewTime
0        6 2013-10-19
1        5 2014-06-18
2        4 2013-05-05


问:
Python 3: destroy tkinter window after calling lambda function, without quitting the program
So, I want to close the Tkinter window when

```<code>w = Button(root, text="Tryck här för att skriva till high score lista", command=lambda :high_score(attempts, computer_word_list_for_display))
w.pack(fill=X)
</code>```

is pressed.

I have tried

```<code>w = Button(root, text="Tryck här för att skriva till high score lista", command=lambda :high_score(attempts, computer_word_list_for_display), root.destroy())
w.pack(fill=X)
</code>```

but it only gives me an error message. Any ideas?

Here is the function as a whole...

```<code>def render_game_after(attempts,computer_word_list_for_display):
    root = Tk()

    w = Label(root, text="Detta är spelmenyn. Här kommer några alternativ.", bg = "black",fg = "white")
    w.pack(fill=X)

    w = Button(root, text="Tryck här för att skriva till high score lista", command=lambda :high_score(attempts, computer_word_list_for_display))
    w.pack(fill=X)

    w = Button(root, text="Klicka här för att se ditt resultat i ett annat fönster",command= lambda:render_highscore(attempts, computer_word_list_for_display))
    w.pack(fill=X)

    w = Button(root, text="Tryck här för att avsluta spelet", command=lambda: quit())
    w.pack(fill=X)

    root.mainloop()
</code>```

答:
Better create function ie.

```<code>def on_quit(a, b):
   high_score(a, b)
   root.destroy()

w = Button(root, text="...", command=lambda:on_quit(attempts, computer_word_list_for_display))
</code>```

It will be more readable.

Body:
So, I want to close the Tkinter window when

w = Button(root, text="Tryck här för att skriva till high score lista", command=lambda :high_score(attempts, computer_word_list_for_display))
w.pack(fill=X)

is pressed.

I have tried

w = Button(root, text="Tryck här för att skriva till high score lista", command=lambda :high_score(attempts, computer_word_list_for_display), root.destroy())
w.pack(fill=X)

but it only gives me an error message. Any ideas?

Here is the function as a whole...

def render_game_after(attempts,computer_word_list_for_display):
    root = Tk()

    w = Label(root, text="Detta är spelmenyn. Här kommer några alternativ.", bg = "black",fg = "white")
    w.pack(fill=X)

    w = Button(root, text="Tryck här för att skriva till high score lista", command=lambda :high_score(attempts, computer_word_list_for_display))
    w.pack(fill=X)

    w = Button(root, text="Klicka här för att se ditt resultat i ett annat fönster",command= lambda:render_highscore(attempts, computer_word_list_for_display))
    w.pack(fill=X)

    w = Button(root, text="Tryck här för att avsluta spelet", command=lambda: quit())
    w.pack(fill=X)

    root.mainloop()

Body:
Better create function ie.

def on_quit(a, b):
   high_score(a, b)
   root.destroy()

w = Button(root, text="...", command=lambda:on_quit(attempts, computer_word_list_for_display))

It will be more readable.


问:
Visual Studio, Linq-to-Sql, designer settings?
Is there some place I can change output settings for the Visual Studio Linq-to-Sql designer? I would like to control if table names are pluralized/depluralized, add specific attributes, namespace etc. Can something of this be done without manually changing the files after they are created?</p>

答:
You can change the names of tables/entities from the Table properties in the designer. It has a Name, and a Source. The Source, of course, is the underlying database, but you can change the name to suit your needs. Other than that, I don't know of a way to specifically pluralize or depluralize items. </p>

<p>Also, don't manually edit the files output by the L2S designer - they'll just get overwritten the next time you make a change in the designer. To extend the generated classes, use partial classes. </p>

Body:
You can change the names of tables/entities from the Table properties in the designer. It has a Name, and a Source. The Source, of course, is the underlying database, but you can change the name to suit your needs. Other than that, I don't know of a way to specifically pluralize or depluralize items.

Also, don't manually edit the files output by the L2S designer - they'll just get overwritten the next time you make a change in the designer. To extend the generated classes, use partial classes.


问:
How to reproduce Apple's alert-like views
I am struggling the last couple of days to figure out if these alerts are part of UIKit or just a private custom view. I don't even know how they properly called. The UI team have asked for an alert that looks like the one appears in Apple's News and Podcast apps. See screenshots below.

答:
You can use my own StatusAlert framework written in Swift. It gives you ability to show Apple system-like alert as well as present the same alert without an image, title or message anywhere in UIView.

It is available via Cocoapods and Carthage and supports iPhone X, Safe Areas layout, iPads and allows some customizations.


问:
Add from_tuple() classmethod that allows objects to be created with a tuple?
Circle class uses a Point object as the center. A @classmethod called from_tuple is needed to allow Circle objects to be created with tuple instead of a Point as the center. This is how the output should look like for from_tuple()

I apologize for the messy codes, having two getters and one setter for center. I got really confused toward the end, knowing that center must be a tuple. Please help me with resolving the AttributeError in the getter when accessing from_tuple().

Error message is shown below

```<code>>>> center_point=3,4
>>> circle=Circle.from_tuple(center=center_point)
>>> circle
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\hole1\Desktop\ProgramIntro\shapes.py", line 54, in __repr__
    return "Circle(center=Point({0}, {1}), radius={2})".format(self.center[0],self.center[1],self.radius)
  File "C:\Users\hole1\Desktop\ProgramIntro\shapes.py", line 65, in center
    return(self._center)
AttributeError: 'Circle' object has no attribute '_center'
</code>```

The below is class Point:

```<code> import math
class Point:
    def __init__(self,x=0,y=0):
        self.x = x
        self.y = y
        self.data=[x,y]
    def __getitem__(self, index):
        return self.data[index]
    def __iter__(self):
        yield self.x
        yield self.y
    def __add__(self,other):
        return Point(self.x+other.x,self.y+other.y)
    def __mul__(self,n):
        return Point(self.x*n,self.y*n)
    def __rmul__(self,n):
        return Point(n*self.x,n*self.y)
    @classmethod
    def from_tuple (cls, self=(0,0)):
        return cls(*self)
    def loc_from_tuple(self,t=(0,0)):
        self.x=t[0]
        self.y=t[1]
    def __str__(self):
        return "Point at ({0}, {1})".format(self.x,self.y)
    def __repr__(self):
        return"Point(x={0}, y={1})".format(self.x,self.y)
</code>```

The below is class Circle.

```<code> class Circle(Point):
        def __init__(self, center=(0,0), radius=1):
            try:
                x, y = center
                super(Circle, self).__init__(x,y)
                Point.__init__(self,center)
                self.radius=radius
                self.center=center
            except (UnboundLocalError, TypeError, AttributeError) as e:
                    pass
            if not center == (0,0):
                if not isinstance(center,Point):
                    if not isinstance(center, tuple):
                        raise TypeError("The center must be a oint!")
        def __str__(self):
            return "Circle with center at ({0}, {1}) and radius {2}".format(self.center.x, self.center.y, self.radius)
        def __repr__(self):
            return "Circle(center=Point({0}, {1}), radius={2})".format(self.center[0],self.center[1],self.radius)
        @property
        def center(self):
            return self.x, self.y
        @property
        def center(self):
            return(self._center)
        @center.setter
        def center(self, center):
            if not center == (0,0):
                if not isinstance(center,Point):
                    raise TypeError("The center must be a Point!")
            self._center=center
        @property
        def radius(self):
            return self._radius
        @radius.setter
        def radius(self, radius):
            if radius<0:
                raise ValueError('The radius cannot be negative')
            self._radius=radius
        @classmethod
        def from_tuple(cls, center=(0,0),radius=1):
            return cls(center,radius)
</code>```

答:
There are a lot of things wrong with your code - from logical (i.e. why does a Circle inherit from a Point?) to structural (using undeclared instance properties) to downright weird (why are you defining your Circle.center getter twice?) - but the main culprit for the error in question is the very bad idea of capturing all exceptions just to ignore them because if you haven't done so you'd notice the error yourself.

Namely, when you call your Circle.from_tuple() class method, it in turn creates a new Circle instance and its __init__() method gets called with the passed passed center and radius (btw. why do you need Circle.from_tuple() when you're just forwarding your arguments - why not just call Circle() directly?). Given that you're passing a (3, 4) as center to it, it's as if you've effectively called: Circle.__init__(center=(3, 4)).

And there you get a slew of problems. First, you call the super.__init__() method to pass the center's x and y - fair enough, it will initiate self.x, self.y and self.data (redundant, but lets not get into it). Then for some unknown reason you attempt to call it again, using a different syntax and passing your tuple only as the first parameter, which in turn now turns self.x to have the value of center ((3, 4)). But the real problem lies when you call your Circle.center() setter passing it the same (3, 4) tuple. If you look at your method:

```<code>@center.setter
def center(self, center):
    if not center == (0, 0):
        if not isinstance(center, Point):
            raise TypeError("The center must be a Point!")
    self._center = center
</code>```

What do you think is going to happen? Given that the passed center ((3, 4)) is not (0, 0), and most definitely not an instance of Point (it's a tuple) it will raise a TypeError and self._center will never be set.

But wait, since you've decided to capture all UnboundLocalError, TypeError and AttributeError exceptions in your Circle.__init__() and just pass them through you never get informed that your center wasn't set, so when you attempt to print it out in REPL Circle.__repr__() gets called, which in turn attempts to access the undefined Circle._center and you get your nice error.

A quick & dirty solution, since you're already inheriting from Point, is to just forget about the center altogether - you already have self.x and self.y (and self.data being a list based on those) so remove any references to center and you're golden:

```<code>class Circle(Point):

    def __init__(self, center=(0, 0), radius=1):
        super(Circle, self).__init__(*center)
        self.radius = radius

    def __str__(self):
        return "Circle with center at ({0}, {1}) and radius {2}".format(self.x, self.y, self.radius)

    def __repr__(self):
        return "Circle(center=Point({0}, {1}), radius={2})".format(self.x, self.y, self.radius)

    @property
    def center(self):
        return Point(self.x, self.y)

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, radius):
        if radius < 0:
            raise ValueError('The radius cannot be negative')
        self._radius = radius
</code>```

And now you can instantiate it both with a Point or a tuple for its center.

But even better solution would be to rethink what are you trying to achieve here and, when you get stuck, to attempt good old Rubber duck debugging to capture errors such as the one in your code.

Body:
Circle class uses a Point object as the center. A @classmethod called from_tuple is needed to allow Circle objects to be created with tuple instead of a Point as the center. This is how the output should look like for from_tuple()

I apologize for the messy codes, having two getters and one setter for center. I got really confused toward the end, knowing that center must be a tuple. Please help me with resolving the AttributeError in the getter when accessing from_tuple().

Error message is shown below

>>> center_point=3,4
>>> circle=Circle.from_tuple(center=center_point)
>>> circle
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\hole1\Desktop\ProgramIntro\shapes.py", line 54, in __repr__
    return "Circle(center=Point({0}, {1}), radius={2})".format(self.center[0],self.center[1],self.radius)
  File "C:\Users\hole1\Desktop\ProgramIntro\shapes.py", line 65, in center
    return(self._center)
AttributeError: 'Circle' object has no attribute '_center'

The below is class Point:

 import math
class Point:
    def __init__(self,x=0,y=0):
        self.x = x
        self.y = y
        self.data=[x,y]
    def __getitem__(self, index):
        return self.data[index]
    def __iter__(self):
        yield self.x
        yield self.y
    def __add__(self,other):
        return Point(self.x+other.x,self.y+other.y)
    def __mul__(self,n):
        return Point(self.x*n,self.y*n)
    def __rmul__(self,n):
        return Point(n*self.x,n*self.y)
    @classmethod
    def from_tuple (cls, self=(0,0)):
        return cls(*self)
    def loc_from_tuple(self,t=(0,0)):
        self.x=t[0]
        self.y=t[1]
    def __str__(self):
        return "Point at ({0}, {1})".format(self.x,self.y)
    def __repr__(self):
        return"Point(x={0}, y={1})".format(self.x,self.y)

The below is class Circle.

 class Circle(Point):
        def __init__(self, center=(0,0), radius=1):
            try:
                x, y = center
                super(Circle, self).__init__(x,y)
                Point.__init__(self,center)
                self.radius=radius
                self.center=center
            except (UnboundLocalError, TypeError, AttributeError) as e:
                    pass
            if not center == (0,0):
                if not isinstance(center,Point):
                    if not isinstance(center, tuple):
                        raise TypeError("The center must be a oint!")
        def __str__(self):
            return "Circle with center at ({0}, {1}) and radius {2}".format(self.center.x, self.center.y, self.radius)
        def __repr__(self):
            return "Circle(center=Point({0}, {1}), radius={2})".format(self.center[0],self.center[1],self.radius)
        @property
        def center(self):
            return self.x, self.y
        @property
        def center(self):
            return(self._center)
        @center.setter
        def center(self, center):
            if not center == (0,0):
                if not isinstance(center,Point):
                    raise TypeError("The center must be a Point!")
            self._center=center
        @property
        def radius(self):
            return self._radius
        @radius.setter
        def radius(self, radius):
            if radius<0:
                raise ValueError('The radius cannot be negative')
            self._radius=radius
        @classmethod
        def from_tuple(cls, center=(0,0),radius=1):
            return cls(center,radius)

Body:
There are a lot of things wrong with your code - from logical (i.e. why does a Circle inherit from a Point?) to structural (using undeclared instance properties) to downright weird (why are you defining your Circle.center getter twice?) - but the main culprit for the error in question is the very bad idea of capturing all exceptions just to ignore them because if you haven't done so you'd notice the error yourself.

Namely, when you call your Circle.from_tuple() class method, it in turn creates a new Circle instance and its __init__() method gets called with the passed passed center and radius (btw. why do you need Circle.from_tuple() when you're just forwarding your arguments - why not just call Circle() directly?). Given that you're passing a (3, 4) as center to it, it's as if you've effectively called: Circle.__init__(center=(3, 4)).

And there you get a slew of problems. First, you call the super.__init__() method to pass the center's x and y - fair enough, it will initiate self.x, self.y and self.data (redundant, but lets not get into it). Then for some unknown reason you attempt to call it again, using a different syntax and passing your tuple only as the first parameter, which in turn now turns self.x to have the value of center ((3, 4)). But the real problem lies when you call your Circle.center() setter passing it the same (3, 4) tuple. If you look at your method:

@center.setter
def center(self, center):
    if not center == (0, 0):
        if not isinstance(center, Point):
            raise TypeError("The center must be a Point!")
    self._center = center

What do you think is going to happen? Given that the passed center ((3, 4)) is not (0, 0), and most definitely not an instance of Point (it's a tuple) it will raise a TypeError and self._center will never be set.

But wait, since you've decided to capture all UnboundLocalError, TypeError and AttributeError exceptions in your Circle.__init__() and just pass them through you never get informed that your center wasn't set, so when you attempt to print it out in REPL Circle.__repr__() gets called, which in turn attempts to access the undefined Circle._center and you get your nice error.

A quick & dirty solution, since you're already inheriting from Point, is to just forget about the center altogether - you already have self.x and self.y (and self.data being a list based on those) so remove any references to center and you're golden:

class Circle(Point):

    def __init__(self, center=(0, 0), radius=1):
        super(Circle, self).__init__(*center)
        self.radius = radius

    def __str__(self):
        return "Circle with center at ({0}, {1}) and radius {2}".format(self.x, self.y, self.radius)

    def __repr__(self):
        return "Circle(center=Point({0}, {1}), radius={2})".format(self.x, self.y, self.radius)

    @property
    def center(self):
        return Point(self.x, self.y)

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, radius):
        if radius < 0:
            raise ValueError('The radius cannot be negative')
        self._radius = radius

And now you can instantiate it both with a Point or a tuple for its center.

But even better solution would be to rethink what are you trying to achieve here and, when you get stuck, to attempt good old Rubber duck debugging to capture errors such as the one in your code.