问:
FileDownloader at the android it is showing no errors but the download does not start
I am trying to download a simple .pdf file I have tried logs but no errors and nothing. I tried to debug but the same till yesterday it worked like charm but not today, I didn't change nothing at this part of the code.
I am based at this question and answer at SO.

https://stackoverflow.com/a/24748227/9560126

Below is the code.

Sometimes at the LogCat it shows me only like message something like this.

com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:251) FileDownloader.downloadFile

at this line of code.

```<code>inputStream = urlConnection.getInputStream();
</code>```

The code of Url connection.

urlConnection.getResponseCode()

It is returning 405

MainActivity.java

```<code>String newEntry = "http://www.axmag.com/download/pdfurl-guide.pdf";
new DownloadFile().execute(newEntry, "maven.pdf");

  private static class DownloadFile extends AsyncTask<String, Void, Void>{

    @Override
    protected Void doInBackground(String... strings) {
        String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
        String fileName = strings[1];  // -> maven.pdf
        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        File folder = new File(extStorageDirectory, "testthreepdf");
        folder.mkdir();

        File pdfFile = new File(folder, fileName);

        try{
            pdfFile.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        FileDownloader.downloadFile(fileUrl, pdfFile);
        return null;
    }
}
</code>```

FileDownloader.java

```<code>public class FileDownloader {
private static final int  MEGABYTE = 1024 * 1024;

public static void downloadFile(String fileUrl, File directory){
    try {

        URL url = new URL(fileUrl);
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();

        InputStream inputStream;
        inputStream = urlConnection.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(directory);
        int totalSize = urlConnection.getContentLength();

        byte[] buffer = new byte[MEGABYTE];
        int bufferLength = 0;
        while((bufferLength = inputStream.read(buffer))>0 ){
            fileOutputStream.write(buffer, 0, bufferLength);
        }
        fileOutputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
 }
}
</code>```

AndroidManifest.XML

```<code><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
</code>```

答:
The solution is as below, this should fix your problem. There are changes related to API 28 Android Permissions which made your old code obsolete

Access Screen

Output

Code Snapshot

AndroidManifest.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zackdawood">

    <uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:networkSecurityConfig="@xml/network_security_config">
        <provider
            android:name=".GenericFileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/external_files"/>
        </provider>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

GenericFileProvider.java

```<code>package com.zackdawood;

import android.support.v4.content.FileProvider;

public class GenericFileProvider extends FileProvider {
}
</code>```

FileDownloader.java

```<code>package com.zackdawood;

import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {

    private static final String TAG = "FileDownloader";

    private static final int MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory) {
        try {
            Log.v(TAG, "downloadFile() invoked ");
            Log.v(TAG, "downloadFile() fileUrl " + fileUrl);
            Log.v(TAG, "downloadFile() directory " + directory);

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
            Log.v(TAG, "downloadFile() completed ");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        }
    }
}
</code>```

MainActivity.java

```<code>package com.zackdawood;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private static boolean hasPermissions(Context context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.v(TAG, "onCreate() Method invoked ");

        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);

    }

    public void request(View view) {

        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);

    }

    public void view(View view) {
        Log.v(TAG, "view() Method invoked ");

        if (!hasPermissions(MainActivity.this, PERMISSIONS)) {

            Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");

            Toast t = Toast.makeText(getApplicationContext(), "You don't have read access !", Toast.LENGTH_LONG);
            t.show();

        } else {
            File d = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);  // -> filename = maven.pdf
            File pdfFile = new File(d, "maven.pdf");

            Log.v(TAG, "view() Method pdfFile " + pdfFile.getAbsolutePath());

            Uri path = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", pdfFile);

            Log.v(TAG, "view() Method path " + path);

            Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
            pdfIntent.setDataAndType(path, "application/pdf");
            pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            try {
                startActivity(pdfIntent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
            }
        }
        Log.v(TAG, "view() Method completed ");

    }

    public void download(View view) {
        Log.v(TAG, "download() Method invoked ");

        if (!hasPermissions(MainActivity.this, PERMISSIONS)) {

            Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");

            Toast t = Toast.makeText(getApplicationContext(), "You don't have write access !", Toast.LENGTH_LONG);
            t.show();

        } else {
            Log.v(TAG, "download() Method HAVE PERMISSIONS ");

            //new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf");
            new DownloadFile().execute("http://www.axmag.com/download/pdfurl-guide.pdf", "maven.pdf");

        }

        Log.v(TAG, "download() Method completed ");

    }

    private class DownloadFile extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... strings) {
            Log.v(TAG, "doInBackground() Method invoked ");

            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

            File pdfFile = new File(folder, fileName);
            Log.v(TAG, "doInBackground() pdfFile invoked " + pdfFile.getAbsolutePath());
            Log.v(TAG, "doInBackground() pdfFile invoked " + pdfFile.getAbsoluteFile());

            try {
                pdfFile.createNewFile();
                Log.v(TAG, "doInBackground() file created" + pdfFile);

            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "doInBackground() error" + e.getMessage());
                Log.e(TAG, "doInBackground() error" + e.getStackTrace());

            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            Log.v(TAG, "doInBackground() file download completed");

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

strings.xml

```<code><resources>
    <string name="app_name">DemoInternalDownload</string>
    <string name="action_settings">Settings</string>
    <string name="file_view">File View</string>
    <string name="file_download">File Download</string>
    <string name="file_request">Request Access Again</string>

</resources>
</code>```

external_files.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>
</code>```

network_security_config.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">maven.apache.org</domain>
        <domain includeSubdomains="true">www.axmag.com</domain>
    </domain-config>
</network-security-config>
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="200px"
            android:onClick="download"
            android:text="@string/file_download" />

        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="200px"
            android:onClick="view"
            android:text="@string/file_view" />

        <Button
            android:id="@+id/button5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="200px"
            android:onClick="request"
            android:text="@string/file_request" />
    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>
</code>```

build.gradle

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

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.zackdawood"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code>```

Body:
I am trying to download a simple .pdf file I have tried logs but no errors and nothing. I tried to debug but the same till yesterday it worked like charm but not today, I didn't change nothing at this part of the code.
I am based at this question and answer at SO.

https://stackoverflow.com/a/24748227/9560126

Below is the code.

Sometimes at the LogCat it shows me only like message something like this.

com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:251) FileDownloader.downloadFile

at this line of code.

inputStream = urlConnection.getInputStream();

The code of Url connection.

urlConnection.getResponseCode()

It is returning 405

MainActivity.java

String newEntry = "http://www.axmag.com/download/pdfurl-guide.pdf";
new DownloadFile().execute(newEntry, "maven.pdf");

  private static class DownloadFile extends AsyncTask<String, Void, Void>{

    @Override
    protected Void doInBackground(String... strings) {
        String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
        String fileName = strings[1];  // -> maven.pdf
        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        File folder = new File(extStorageDirectory, "testthreepdf");
        folder.mkdir();

        File pdfFile = new File(folder, fileName);

        try{
            pdfFile.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        FileDownloader.downloadFile(fileUrl, pdfFile);
        return null;
    }
}

FileDownloader.java

public class FileDownloader {
private static final int  MEGABYTE = 1024 * 1024;

public static void downloadFile(String fileUrl, File directory){
    try {

        URL url = new URL(fileUrl);
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();

        InputStream inputStream;
        inputStream = urlConnection.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(directory);
        int totalSize = urlConnection.getContentLength();

        byte[] buffer = new byte[MEGABYTE];
        int bufferLength = 0;
        while((bufferLength = inputStream.read(buffer))>0 ){
            fileOutputStream.write(buffer, 0, bufferLength);
        }
        fileOutputStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
 }
}

AndroidManifest.XML

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

Body:
The solution is as below, this should fix your problem. There are changes related to API 28 Android Permissions which made your old code obsolete

Access Screen

Output

Code Snapshot

AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zackdawood">

    <uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:networkSecurityConfig="@xml/network_security_config">
        <provider
            android:name=".GenericFileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/external_files"/>
        </provider>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

GenericFileProvider.java

package com.zackdawood;

import android.support.v4.content.FileProvider;

public class GenericFileProvider extends FileProvider {
}

FileDownloader.java

package com.zackdawood;

import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileDownloader {

    private static final String TAG = "FileDownloader";

    private static final int MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory) {
        try {
            Log.v(TAG, "downloadFile() invoked ");
            Log.v(TAG, "downloadFile() fileUrl " + fileUrl);
            Log.v(TAG, "downloadFile() directory " + directory);

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
            Log.v(TAG, "downloadFile() completed ");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "downloadFile() error" + e.getMessage());
            Log.e(TAG, "downloadFile() error" + e.getStackTrace());
        }
    }
}

MainActivity.java

package com.zackdawood;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final String[] PERMISSIONS = {android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private static boolean hasPermissions(Context context, String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.v(TAG, "onCreate() Method invoked ");

        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);

    }

    public void request(View view) {

        ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, 112);

    }

    public void view(View view) {
        Log.v(TAG, "view() Method invoked ");

        if (!hasPermissions(MainActivity.this, PERMISSIONS)) {

            Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");

            Toast t = Toast.makeText(getApplicationContext(), "You don't have read access !", Toast.LENGTH_LONG);
            t.show();

        } else {
            File d = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);  // -> filename = maven.pdf
            File pdfFile = new File(d, "maven.pdf");

            Log.v(TAG, "view() Method pdfFile " + pdfFile.getAbsolutePath());

            Uri path = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", pdfFile);

            Log.v(TAG, "view() Method path " + path);

            Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
            pdfIntent.setDataAndType(path, "application/pdf");
            pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            try {
                startActivity(pdfIntent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(MainActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
            }
        }
        Log.v(TAG, "view() Method completed ");

    }

    public void download(View view) {
        Log.v(TAG, "download() Method invoked ");

        if (!hasPermissions(MainActivity.this, PERMISSIONS)) {

            Log.v(TAG, "download() Method DON'T HAVE PERMISSIONS ");

            Toast t = Toast.makeText(getApplicationContext(), "You don't have write access !", Toast.LENGTH_LONG);
            t.show();

        } else {
            Log.v(TAG, "download() Method HAVE PERMISSIONS ");

            //new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf");
            new DownloadFile().execute("http://www.axmag.com/download/pdfurl-guide.pdf", "maven.pdf");

        }

        Log.v(TAG, "download() Method completed ");

    }

    private class DownloadFile extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... strings) {
            Log.v(TAG, "doInBackground() Method invoked ");

            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
            String fileName = strings[1];  // -> maven.pdf
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

            File pdfFile = new File(folder, fileName);
            Log.v(TAG, "doInBackground() pdfFile invoked " + pdfFile.getAbsolutePath());
            Log.v(TAG, "doInBackground() pdfFile invoked " + pdfFile.getAbsoluteFile());

            try {
                pdfFile.createNewFile();
                Log.v(TAG, "doInBackground() file created" + pdfFile);

            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "doInBackground() error" + e.getMessage());
                Log.e(TAG, "doInBackground() error" + e.getStackTrace());

            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            Log.v(TAG, "doInBackground() file download completed");

            return null;
        }
    }
}

strings.xml

<resources>
    <string name="app_name">DemoInternalDownload</string>
    <string name="action_settings">Settings</string>
    <string name="file_view">File View</string>
    <string name="file_download">File Download</string>
    <string name="file_request">Request Access Again</string>

</resources>

external_files.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">maven.apache.org</domain>
        <domain includeSubdomains="true">www.axmag.com</domain>
    </domain-config>
</network-security-config>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="200px"
            android:onClick="download"
            android:text="@string/file_download" />

        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="200px"
            android:onClick="view"
            android:text="@string/file_view" />

        <Button
            android:id="@+id/button5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="200px"
            android:onClick="request"
            android:text="@string/file_request" />
    </LinearLayout>

</android.support.design.widget.CoordinatorLayout>

build.gradle

 apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.zackdawood"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}


来源: stackexchange

问:
problem in executing if-else loop inside a try catch block
On button click event it is not entering if loop but directly entering else loop.
Output is always the same that is 1.

There is a text field called secret share and a button.
when the secret share field is null we want to execute if loop
and when it is not null we want to execute else loop.
but it is always executing else loop only.

```<code>private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
    // TODO add your handling code here:

    if(jTextField_getSecretShare3.getText()== null)
    {
        JOptionPane.showMessageDialog(this, "0");
    }
    else
    {
        JOptionPane.showMessageDialog(this, "1");
    }
}
</code>```

答:
getText is inherted from JTextComponent, and it never returns null. If you want to check for an empty JTextField, use isEmpty (or, depending on your use case, isBlank):

```<code>if (jTextField_getSecretShare3.getText().isEmpty())
{
    JOptionPane.showMessageDialog(this, "0");
}
else
{
    JOptionPane.showMessageDialog(this, "1");
}
</code>```

Note that you could do that in a single statement using the conditional operator (? :):

```<code>JOptionPane.showMessageDialog(this, jTextField_getSecretShare3.getText().isEmpty() ? "0" : "1");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
On button click event it is not entering if loop but directly entering else loop.
Output is always the same that is 1.

There is a text field called secret share and a button.
when the secret share field is null we want to execute if loop
and when it is not null we want to execute else loop.
but it is always executing else loop only.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
    // TODO add your handling code here:

    if(jTextField_getSecretShare3.getText()== null)
    {
        JOptionPane.showMessageDialog(this, "0");
    }
    else
    {
        JOptionPane.showMessageDialog(this, "1");
    }
}

Body:
getText is inherted from JTextComponent, and it never returns null. If you want to check for an empty JTextField, use isEmpty (or, depending on your use case, isBlank):

if (jTextField_getSecretShare3.getText().isEmpty())
{
    JOptionPane.showMessageDialog(this, "0");
}
else
{
    JOptionPane.showMessageDialog(this, "1");
}

Note that you could do that in a single statement using the conditional operator (? :):

JOptionPane.showMessageDialog(this, jTextField_getSecretShare3.getText().isEmpty() ? "0" : "1");


问:
Java Selenium Chrome driver - Disable image loading
I am trying to run chrome driver without loading any images for obvious reasons.

i found a piece of code online but i think it's outdated

```<code>HashMap<String, Object> images = new HashMap<String, Object>();
images.put("images", 2);

HashMap<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_settings", images);

ChromeOptions options =new ChromeOptions();
options.setExperimentalOption("prefs", prefs);

DesiredCapabilities chromeCaps = DesiredCapabilities.chrome();
chromeCaps.setCapability(ChromeOptions.CAPABILITY, options);

driver = new ChromeDriver(chromeCaps);
</code>```

does not work at all..

any help would be greatly appriciated

答:
With Selenium 4 alpha 1, you can also use CDP for filtering URL's:

```<code>    ChromeOptions options = new ChromeOptions();

    ChromeDriver driver = new ChromeDriver(options);

    driver.getDevTools().createSession();

    driver.getDevTools().send(new Command<>("Network.enable", ImmutableMap.of()));
    driver.getDevTools().send(new Command<>("Network.setBlockedURLs", ImmutableMap.of("urls", ImmutableList.of("*://*/*.bmp","*://*/*.gif","*://*/*.png"))));

    driver.get("https://apache.org");

    driver.quit();
</code>```

In the next Alpha version, the interface will be MUCH more user friendly.

Maven dependency:

```<code>    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.0.0-alpha-1</version>
    </dependency>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run chrome driver without loading any images for obvious reasons.

i found a piece of code online but i think it's outdated

HashMap<String, Object> images = new HashMap<String, Object>();
images.put("images", 2);

HashMap<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_settings", images);

ChromeOptions options =new ChromeOptions();
options.setExperimentalOption("prefs", prefs);

DesiredCapabilities chromeCaps = DesiredCapabilities.chrome();
chromeCaps.setCapability(ChromeOptions.CAPABILITY, options);

driver = new ChromeDriver(chromeCaps);

does not work at all..

any help would be greatly appriciated

Body:
With Selenium 4 alpha 1, you can also use CDP for filtering URL's:

    ChromeOptions options = new ChromeOptions();

    ChromeDriver driver = new ChromeDriver(options);

    driver.getDevTools().createSession();

    driver.getDevTools().send(new Command<>("Network.enable", ImmutableMap.of()));
    driver.getDevTools().send(new Command<>("Network.setBlockedURLs", ImmutableMap.of("urls", ImmutableList.of("*://*/*.bmp","*://*/*.gif","*://*/*.png"))));

    driver.get("https://apache.org");

    driver.quit();

In the next Alpha version, the interface will be MUCH more user friendly.

Maven dependency:

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.0.0-alpha-1</version>
    </dependency>


问:
Can anybody help me with this? I am just a beginner
```<code>Select
    m.style_id,
    sum(p.production_qty) Cutting
From
    Master_Data m
Left Join
    production_data p on P.Style_ID = M.Style_ID
where
    p.production_process = 'Cutting',

    sum(p.production_qty) Induction
From
    Master_Data m
Left Join
    production_data p on P.Style_ID = M.Style_ID
where
    p.production_process = 'Induction',
group by
    m.style_id
</code>```

How to get result of two different select statements?

答:
Depending on what you want the result set to look like, you can use aggregation:</p>

```<code>Select p.production_process, m.style_id,
       sum(p.production_qty) Cutting
From Master_Data m left join
     production_data p
     on p.Style_ID = m.Style_ID and
        p.production_process in ('Cutting', 'Induction')
group by p.production_process, m.style_id;
</code>```

Body:
Select
    m.style_id,
    sum(p.production_qty) Cutting
From
    Master_Data m
Left Join
    production_data p on P.Style_ID = M.Style_ID
where
    p.production_process = 'Cutting',

    sum(p.production_qty) Induction
From
    Master_Data m
Left Join
    production_data p on P.Style_ID = M.Style_ID
where
    p.production_process = 'Induction',
group by
    m.style_id

How to get result of two different select statements?

Body:
Depending on what you want the result set to look like, you can use aggregation:

Select p.production_process, m.style_id,
       sum(p.production_qty) Cutting
From Master_Data m left join
     production_data p
     on p.Style_ID = m.Style_ID and
        p.production_process in ('Cutting', 'Induction')
group by p.production_process, m.style_id;


问:
Can I pass custom data in the HTTP header?
I have a whole bunch of web services each with several web methods. The consumers of these services are varied and many. I want to augment each of these web methods with an extra optional parameter (Int64 or Int32) but adding new methods with this extra (optional parameter) is a lot of work and getting the clients to use the new methods will be even more time consuming.

So I was wondering if I could allow the clients that wanted to take advantage of the new feature that this param provides could pass this Int in the HTTP header or some other way.

So the first question is can I pass an int in the HTTP header? If so, how would one do that in C#/ASP.NET?

Otherwise, what other suggestions do you have for tackling this problem?

答: You can, but this defeats the whole purpose of using webservices in the first place. Similar to the saying that each formula in a popular science books reduces the audience to a half, each quick hack increasing the complexity of the interface will mean a lot of trouble in the future.</p>

OwnerDisplayName: Guy

ContentLicense: CC BY-SA 2.5


问:
NHibernate SaveOrUpdate Child Collection Not Updated With Identity Ids
I am clearly missing something (hopefully obvious), and I have had no luck with Google so far.

I have a Parent-Child relationship mapped as follows

Simplified Parent Map

```<code>  public sealed class ParentMap : ClassMap<ParentEntity>
  {
    public ParentMap()
    {
      Table("Parent");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.ServeralNotNullableProperties).Not.Nullable();

      HasMany(x => x.Children).KeyColumn("ChildId")
                              .Inverse()
                              .LazyLoad()
                              .Cascade
                              .AllDeleteOrphan();

      References(x => x.SomeUnrelatedLookupColumn).Column("LookupColumnId").Not.Nullable();
    }
  }
</code>```

Simplified Child Map

```<code>  public sealed class ChildMap : ClassMap<ChildEntity>
  {
    public ChildMap()
    {
      Table("Child");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.MoreNotNullableProperties).Not.Nullable();

      References(x => x.Parent).Column("ParentId").Not.Nullable();
    }
  }
</code>```

Simplified Service Method Steps

I then have a service method that retrieves Parent and adds a new Child via some domain method. The underlying NHibernate code boils down to:

1) Session Opened on WCF AfterReceiveRequest (IDispatchMessageInspector)

```<code>_sessionFactory.OpenSession();
</code>```

2) Retrieve existing instance of parent via .Query

```<code>_session.Query<ParentEntity>()
        .Where(item => item.Id == parentId)
        .Fetch(item => item.SomeLookupColumn)
        .First();
</code>```

3) Add new 'Child' entity to 'Parent' via domain object method such as...

```<code>public ChildEntity CreateChild()
{
  var child = new ChildEntity{ Parent = this };

  Children.Add(child);

  return child;
}
</code>```

4) Ultimately calls SaveOrUpdate on 'Parent' entity.

```<code> // ChildEntity Id is 0
 _session.SaveOrUpdate(parentEntity)
 // Expect ChildEntity Id to NOT be 0
</code>```

Note: Use of SaveOrUpdate Does persist changes to database; use of Merge results in TransientObjectException mentioned below.

5) Finally, transaction committed on WCF BeforeSendReply (IDispatchMessageInspector)

```<code> _session.Commit();
</code>```

The Problem

Typically when an entity is saved, after the call to SaveOrUpdate, the Id of said entity refects the Identity generated by the INSERT statement. However, when I add a new child entity to an existing parent, the associated entity in Children does not get assigned an Id. I need to pass this Id back to the caller so subsequent calls result in UPDATES and not additional INSERTS.

Why is NHibernate not updating the underlying entity?
Do I explicitly have to call SaveOrUpdate on the child (that sucks if that is the case)?

Any thoughts on the matter greatly appreciated. Thanks!

EDIT
I should note, that the new child entity IS being saved as expected; I just don't get back the Id assigned.

UPDATE
Tried switching to .Merge(~) as suggested by Michael Buen below; resulting in a TransientObjectException telling me to explicitly save my modified child entity before calling merge. I also experimented with .Persist(~) to no avail. Any additional insight greatly appreciated.

object is an unsaved transient instance - save the transient instance before merging: My.NameSpace.ChildEntity

答: You could call session.Flush(), which performs the inserts on the database. This is not ideal because of the impact to performance.

Body:
I am clearly missing something (hopefully obvious), and I have had no luck with Google so far.

I have a Parent-Child relationship mapped as follows

Simplified Parent Map

  public sealed class ParentMap : ClassMap<ParentEntity>
  {
    public ParentMap()
    {
      Table("Parent");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.ServeralNotNullableProperties).Not.Nullable();

      HasMany(x => x.Children).KeyColumn("ChildId")
                              .Inverse()
                              .LazyLoad()
                              .Cascade
                              .AllDeleteOrphan();

      References(x => x.SomeUnrelatedLookupColumn).Column("LookupColumnId").Not.Nullable();
    }
  }

Simplified Child Map

  public sealed class ChildMap : ClassMap<ChildEntity>
  {
    public ChildMap()
    {
      Table("Child");
      Component(x => x.Thumbprint);
      Id(x => x.Id).GeneratedBy.Identity();

      Map(x => x.MoreNotNullableProperties).Not.Nullable();

      References(x => x.Parent).Column("ParentId").Not.Nullable();
    }
  }

Simplified Service Method Steps

I then have a service method that retrieves Parent and adds a new Child via some domain method. The underlying NHibernate code boils down to:

1) Session Opened on WCF AfterReceiveRequest (IDispatchMessageInspector)

_sessionFactory.OpenSession();

2) Retrieve existing instance of parent via .Query

_session.Query<ParentEntity>()
        .Where(item => item.Id == parentId)
        .Fetch(item => item.SomeLookupColumn)
        .First();

3) Add new 'Child' entity to 'Parent' via domain object method such as...

public ChildEntity CreateChild()
{
  var child = new ChildEntity{ Parent = this };

  Children.Add(child);

  return child;
}

4) Ultimately calls SaveOrUpdate on 'Parent' entity.

 // ChildEntity Id is 0
 _session.SaveOrUpdate(parentEntity)
 // Expect ChildEntity Id to NOT be 0

Note: Use of SaveOrUpdate Does persist changes to database; use of Merge results in TransientObjectException mentioned below.

5) Finally, transaction committed on WCF BeforeSendReply (IDispatchMessageInspector)

 _session.Commit();

The Problem

Typically when an entity is saved, after the call to SaveOrUpdate, the Id of said entity refects the Identity generated by the INSERT statement. However, when I add a new child entity to an existing parent, the associated entity in Children does not get assigned an Id. I need to pass this Id back to the caller so subsequent calls result in UPDATES and not additional INSERTS.

Why is NHibernate not updating the underlying entity?
Do I explicitly have to call SaveOrUpdate on the child (that sucks if that is the case)?

Any thoughts on the matter greatly appreciated. Thanks!

EDIT
I should note, that the new child entity IS being saved as expected; I just don't get back the Id assigned.

UPDATE
Tried switching to .Merge(~) as suggested by Michael Buen below; resulting in a TransientObjectException telling me to explicitly save my modified child entity before calling merge. I also experimented with .Persist(~) to no avail. Any additional insight greatly appreciated.

object is an unsaved transient instance - save the transient instance before merging: My.NameSpace.ChildEntity


问:
Is gschemas.compiled architecture specific (can I ship it with my python library)?
I'm working on a python library / app that uses Gtk.

Part of my build process uses glib-compile-schemas to create gschemas.compiled.

If I include gschemas.compiled in my library, will this break things, if somebody tries to use my library on something like ARM or 32 bit intel ?

(I would compile this as a post-install thing, but that seems to unsupported in setuptools which I am using).

答:
This isn't a definitive answer, but I verified the file is the same for two different architectures build for a package and they are the same.

(The debian i386 and arm64 packages for enchant).

These were chosen because of the different bit width (32 vs 64), and differing architectures.

If somebody writes a more definitive answer, I'll still accept that.


问:
How do I change the background of a site with a button?
I'm trying to coding a site where I need to change the background with a button, but I can't...

I created a button that changes the color of the background while clicking a button but after I added an image as a background, it doesn't want to change the color background (obviously)...

 // creating a variable for the bg of my site

 // using this variable

            <button onclick="changeColor(); backgroundHiding();" class="lightbutton">Turn On/Off the lights </button>

 // creating the button that interact with the two js functions

```

<p>I expected that it works but... huh... no
It works sometimes, like 1 time every 100 times, I don't know why...
If someone could help me, I would really appreciate it!</p>

```https://stackblitz.com/edit/typescript-ppvsvl?embed=1&file=index.html
```

答: Try my project setBackgroundCanvas it allows for jpegs, if your using npm https://www.npmjs.com/package/element-functions-set_background_canvas</p>

Body:
I'm trying to coding a site where I need to change the background with a button, but I can't...

I created a button that changes the color of the background while clicking a button but after I added an image as a background, it doesn't want to change the color background (obviously)...

 // creating a variable for the bg of my site

 // using this variable

            <button onclick="changeColor(); backgroundHiding();" class="lightbutton">Turn On/Off the lights </button>

 // creating the button that interact with the two js functions

I expected that it works but... huh... no
It works sometimes, like 1 time every 100 times, I don't know why...
If someone could help me, I would really appreciate it!

https://stackblitz.com/edit/typescript-ppvsvl?embed=1&file=index.html


问:
How to fix clang error: symbol(s) not found for architecture arm64
I been trying to build an app through Xcode and I keep getting this error: symbol(s) not found for architecture arm64. I just built another app with the same setup using unity 2018.3.2.f1 and I did not get this issue.

I tried to go through my unity project to see if any duplicate files were generated, but no luck.

Xcode Error:

ld: warning: arm64 function not 4-byte aligned: _unwind_tester from /Users/derrickdandin/Desktop/Jumpy_Animal_Friends - iOS/Jumpy_Jump_Friends_iOS/Libraries/libiPhone-lib.a(unwind_test_arm64.o)
  Undefined symbols for architecture arm64:
    "_VideoPlayerPluginGetCurrentSeekPercent", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginGetCurrentSeekPercent_m33BEF11BEC3ECF2CA7749FDEB8053842617D5263 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginGetCurrentSeekPercent_m33BEF11BEC3ECF2CA7749FDEB8053842617D5263)
    "_VideoPlayerPluginSetAudioTrack", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginSetAudioTrack_m3B5D1193719F527FE2B4191D359CA7CC415B869C in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginSetAudioTrack_m3B5D1193719F527FE2B4191D359CA7CC415B869C)
    "_VideoPlayerPluginSetSpeed", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginSetSpeed_m544F96C52FD70D09738A3EB448DF5FEF3499D365 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginSetSpeed_m544F96C52FD70D09738A3EB448DF5FEF3499D365)
    "_VideoPlayerPluginFinish", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginFinish_mA49DFCE2D3998099D5B6BA6071D83CDA59F0C65E in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginFinish_mA49DFCE2D3998099D5B6BA6071D83CDA59F0C65E)
    "_VideoPlayerPluginSetTexture", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginSetTexture_mFA4886828CE828667D4C37ABC4F4077848251AD0 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginSetTexture_mFA4886828CE828667D4C37ABC4F4077848251AD0)
    "_VideoPlayerPluginStopVideo", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginStopVideo_m12AD66699F6E4976AF0A73A9BEEA15A3B19C4BC7 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginStopVideo_m12AD66699F6E4976AF0A73A9BEEA15A3B19C4BC7)
    "_VideoPlayerPluginCurTimeSeconds", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginCurTimeSeconds_m06A7AFEA2189163B334238B75674A76F9B4D6845 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginCurTimeSeconds_m06A7AFEA2189163B334238B75674A76F9B4D6845)
    "_VideoPlayerPluginSeekToVideo", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginSeekToVideo_mE8CC13E1AF6EE2D83DEE456CE70F21D9763DDDCC in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginSeekToVideo_mE8CC13E1AF6EE2D83DEE456CE70F21D9763DDDCC)
    "_VideoPlayerPluginRewindVideo", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginRewindVideo_mA26C3B76B74B103A4A43813EFFEB66DF1C91C2E1 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginRewindVideo_mA26C3B76B74B103A4A43813EFFEB66DF1C91C2E1)
    "_VideoPlayerPluginResumeVideo", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginResumeVideo_m7D33CEAE27D87DA22B1B3364FB9C456EE58D2DD7 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginResumeVideo_m7D33CEAE27D87DA22B1B3364FB9C456EE58D2DD7)
    "_VideoPlayerPluginSetVolume", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginSetVolume_m16B65D08C90C128FD82A8D6A9F0CD6190C7B3ECE in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginSetVolume_m16B65D08C90C128FD82A8D6A9F0CD6190C7B3ECE)
    "_VideoPlayerPluginError", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginError_m19CDF508403F3828DF714032DFFADA280BFD0107 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginError_m19CDF508403F3828DF714032DFFADA280BFD0107)
    "_VideoPlayerPluginIsPlaying", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginIsPlaying_m57B48F3CC9EBD56D2B151FF3C44679BE160D626C in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginIsPlaying_m57B48F3CC9EBD56D2B151FF3C44679BE160D626C)
    "_VideoPlayerPluginGetAudioTrack", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginGetAudioTrack_m102B7410AAC4851718AD27C380AF78610E7D29CA in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginGetAudioTrack_m102B7410AAC4851718AD27C380AF78610E7D29CA)
    "_VideoPlayerPluginDurationSeconds", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginDurationSeconds_mBA1A824E1A9FCFA82ACAEA3B987E446618366E89 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginDurationSeconds_mBA1A824E1A9FCFA82ACAEA3B987E446618366E89)
    "_VideoPlayerPluginPlayVideo", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginPlayVideo_m21557D326D89BB4038C78162FBF4BE333357D13F in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginPlayVideo_m21557D326D89BB4038C78162FBF4BE333357D13F)
    "_VideoPlayerPluginCurFrameTexture", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginCurFrameTexture_m6E9884E2FBFBA0EECB1502F4348E8CF0EBB045EE in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginCurFrameTexture_m6E9884E2FBFBA0EECB1502F4348E8CF0EBB045EE)
    "_VideoPlayerPluginLoadVideo", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginLoadVideo_m9BBB66F654483B414D09FF6CD3EF0B324F209CA5 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginLoadVideo_m9BBB66F654483B414D09FF6CD3EF0B324F209CA5)
    "_VideoPlayerPluginPlayerReady", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginPlayerReady_m1BBFA30E280506830C6B7CABB5719B80D2A5BD17 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginPlayerReady_m1BBFA30E280506830C6B7CABB5719B80D2A5BD17)
    "_VideoPlayerPluginPauseVideo", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginPauseVideo_m365AED7AE6922CE4D3BF11BA3A3AB3E45BA55D2E in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginPauseVideo_m365AED7AE6922CE4D3BF11BA3A3AB3E45BA55D2E)
    "_VideoPlayerPluginExtents", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginExtents_m02D4C687310EB53549AC6B13591894CC76048D92 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginExtents_m02D4C687310EB53549AC6B13591894CC76048D92)
    "_VideoPlayerPluginDestroyInstance", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginDestroyInstance_m404DBB6565D1BF7FD1F82F5D6A2E4CC7D1A8B065 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginDestroyInstance_m404DBB6565D1BF7FD1F82F5D6A2E4CC7D1A8B065)
    "_VideoPlayerPluginCanOutputToTexture", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginCanOutputToTexture_m28EF7A2669AF7786E79594C48D0A7293EF7AD1B1 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginCanOutputToTexture_m28EF7A2669AF7786E79594C48D0A7293EF7AD1B1)
    "_VideoPlayerPluginSetLoop", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginSetLoop_m198D76AA47FE3D5DE4362DA6BD83D2ABA3C6EFF3 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginSetLoop_m198D76AA47FE3D5DE4362DA6BD83D2ABA3C6EFF3)
    "_VideoPlayerPluginCreateInstance", referenced from:
        _MediaPlayerCtrl_VideoPlayerPluginCreateInstance_m180D5B72D5B6CD5515C4B129CC6E05392AD145F4 in Bulk_Assembly-CSharp_8.o
       (maybe you meant: _MediaPlayerCtrl_VideoPlayerPluginCreateInstance_m180D5B72D5B6CD5515C4B129CC6E05392AD145F4)
  ld: symbol(s) not found for architecture arm64
  clang: error: linker command failed with exit code 1 (use -v to see invocation)

ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

答: I figured it out. I made sure my project plugins folder was clear of any lingering old files, which there were old plugins that were still in there.</p>


问:
Automated builds in monotouch
I am currently trying to implement a one-click build solution (without having to start the monodevelop IDE) for my monotouch projects, where i could specify provisioning profiles and code signing certificates. I searched popular build tools like nant, ant and maven, but none seems to support monotouch. Has anyone tried something similar ?</p>

答: You tried teamcity?  Might be worth you having a look at this thread Buildserver for MonoTouch upon OS X? </p>

Title: Automated builds in monotouch


问:
How Can I Release memory after deleting a variable in python?
I'm Working on a big dataset that consist of float numbers, I can't load all of samples together because of memory limitation and I have to split them to parts and load one part and train my network after that delete it and do this for every part.

my problem is how can i delete the trained part of data and load another

Simple command del my_var doesn't release memory.

after that I tried %reset_selective "my var"  in jupyter-notebook and gc.collect() Even though I can't access to that variable anymore but still the memory doesn't released.

python3

答:
Python uses reference counting for memory management. When a variable goes out of scope (or is deleted explicitly as you are doing), the reference count of the object it points to is decremented by 1. Once the reference count reaches 0, the object is garbage collected (though you can't rely on the exact moment this happens). Your problem is likely that either you still have a name pointing to the objects in question or you may perhaps be deleting a copy of the data.

You'll need to provide a specific code example to get more specific help.


问:
Display month of sale and number of sales done in that month sorted in descending order of sales
Display month of sale and number of sales done in that month sorted in descending order of sales.

I have used the extract function  to extract month from date but it gives month number not the full name of the month

```<code>select extract(month from sldate) as month, count(sid) as number_sale from sale
 group by sldate
order by sid desc
</code>```

this is  the table

Sale Table

```<code>SALEID  SID SLDATE
1001    1   01-JAN-14
1002    5   02-JAN-14
1003    4   01-FEB-14
1004    1   01-MAR-14
1005    2   01-FEB-14
1006    1   01-JUN-15
</code>```

Expected Result

```<code>MONTH        NUMBER_SALE
February    2
January         2
March           1
June            1
</code>```

答:
This answers the original question tagged with MySql.

Instead of extracting just the month, you need to combine it with the year, because you don't want to mix sales of the same month in different years, so use year_month and then use monthname() to get the month's name:

```<code>select
  monthname(concat(extract(year_month from sldate), '01')) as month,
  count(sid) as number_sale
from sale
group by month
order by number_sale desc
</code>```

See the demo.

Results:

```<code>| month    | number_sale |
| -------- | ----------- |
| February | 2           |
| January  | 2           |
| March    | 1           |
| June     | 1           |
</code>```

Body:
Display month of sale and number of sales done in that month sorted in descending order of sales.

I have used the extract function  to extract month from date but it gives month number not the full name of the month

select extract(month from sldate) as month, count(sid) as number_sale from sale
 group by sldate
order by sid desc

this is  the table

Sale Table

SALEID  SID SLDATE
1001    1   01-JAN-14
1002    5   02-JAN-14
1003    4   01-FEB-14
1004    1   01-MAR-14
1005    2   01-FEB-14
1006    1   01-JUN-15

Expected Result

MONTH        NUMBER_SALE
February    2
January         2
March           1
June            1

Body:
This answers the original question tagged with MySql.

Instead of extracting just the month, you need to combine it with the year, because you don't want to mix sales of the same month in different years, so use year_month and then use monthname() to get the month's name:

select
  monthname(concat(extract(year_month from sldate), '01')) as month,
  count(sid) as number_sale
from sale
group by month
order by number_sale desc

See the demo.

Results:

| month    | number_sale |
| -------- | ----------- |
| February | 2           |
| January  | 2           |
| March    | 1           |
| June     | 1           |


问:
Validate input box is disabled in table rows - SAP UI5
I have a table with a column that has 3 buttons and one input box. Update, Save, Input box and Cancel. When we first enter the page, table is loaded with input box for all the rows as disabled. Only one button - Update is visible at that time (at each row). Once you click on Update, Input box becomes enabled (for that row), Update is hidden, save and cancel buttons are made visible. If either save or cancel is pressed, both buttons are hidden, again input box is disabled and Update is made visible. This is to ensure user enters the value in the input box and saves it properly.

Issue: if I click on update, and enter some random value. At this point if I save good, but if I dont save and under the table is a button to post data to backend, if I click that, the value I entered is passed to backend. I want to ensure, every row is validated to see that user has either saved/cancel and the input box is disabled (meaning the value entered is correct and final). How should I loop through this?

View.xml

        <HBox alignItems="Center">
            <Button text="Update" visible="{path:'model>', formatter:'.updateBtnVisibility'}" press="openQtyInputBox"/>
            <Button text="Save" visible="{= !${model>qtyEditable}}" press="qtySave"/>
            <Input visible="{path:'model>', formatter:'.inputValidation'}" type="Number" enabled="{!${model>qtyEditable}}" value="{path: 'model>QtyToReceive', type: 'sap.ui.model.type.Integer', constraints : {minimum: 0}}"/>
            <core:Icon src="sap-icon://reset" tooltip="Cancel" press="cancelQtyInput" visible="{= !${model>qtyEditable}}"/>
        </HBox>

```

答:
It looks like you already store the input state in your model using qtyEditable. You can use this and Array.filter to loop through the contexts of the table rows:

```<code>validateRows: function() {
    var rowContexts = this.getView().byId("your-table-id").getBinding("rows").getContexts();

    if (rowContexts.filter(function (context) {
        return context.getProperty("qtyEditable");
    }).length === 0) {
        // all rows are saved
    } else {
        // at least one row is still in edit mode
    }
}
</code>```

Body:
It looks like you already store the input state in your model using qtyEditable. You can use this and Array.filter to loop through the contexts of the table rows:

validateRows: function() {
    var rowContexts = this.getView().byId("your-table-id").getBinding("rows").getContexts();

    if (rowContexts.filter(function (context) {
        return context.getProperty("qtyEditable");
    }).length === 0) {
        // all rows are saved
    } else {
        // at least one row is still in edit mode
    }
}


问:
SWRevealViewController hiding navigationbar for my front view controller
I have Reveal View controller which has rear and front view, rear view is my side menu, The problem is when i tap on menu items from side menu it shows the destination view controller but navigation bar is not showing. Please help me. I'm new on iOS.
Here is my storyboard picture:
https://imgur.com/a/PbDygKO

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    itemIndex = indexPath.row
    self.revealViewController().revealToggle(animated: true)
    performSegue(withIdentifier: "webview", sender: nil)
}
</code>```

Here is on Prepare function

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let navigationController = segue.destination as? UINavigationController, let progressWebViewController = navigationController.topViewController as? ProgressWebViewController else {
        return
    }

    switch itemIndex {
    case 1:
        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let newViewController = storyBoard.instantiateViewController(withIdentifier: "aboutus") as! AboutUsController
        self.present(newViewController, animated: true, completion: nil)
        break

    case 2:
        loadURL(progressWebViewController: progressWebViewController ,url: "https://google.com", title: "Event Planning")

    case 3:
        loadURL(progressWebViewController: progressWebViewController ,url: "https://google.com", title: "NCC Checklist")

    default:
        print("Unknown segue \(itemIndex)")
    }
}
</code>```

答:
It is because of this line:
self.present(newViewController, animated: true, completion: nil)

When you present a viewController it has a modal behavior and has no navigationController

so if you need navigationController on that you should use pushViewController instead

like this : self.navigationController.pushViewController(newViewController, animated: true)

Body:
I have Reveal View controller which has rear and front view, rear view is my side menu, The problem is when i tap on menu items from side menu it shows the destination view controller but navigation bar is not showing. Please help me. I'm new on iOS.
Here is my storyboard picture:
https://imgur.com/a/PbDygKO

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    itemIndex = indexPath.row
    self.revealViewController().revealToggle(animated: true)
    performSegue(withIdentifier: "webview", sender: nil)
}

Here is on Prepare function

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let navigationController = segue.destination as? UINavigationController, let progressWebViewController = navigationController.topViewController as? ProgressWebViewController else {
        return
    }

    switch itemIndex {
    case 1:
        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let newViewController = storyBoard.instantiateViewController(withIdentifier: "aboutus") as! AboutUsController
        self.present(newViewController, animated: true, completion: nil)
        break

    case 2:
        loadURL(progressWebViewController: progressWebViewController ,url: "https://google.com", title: "Event Planning")

    case 3:
        loadURL(progressWebViewController: progressWebViewController ,url: "https://google.com", title: "NCC Checklist")

    default:
        print("Unknown segue \(itemIndex)")
    }
}


问:
android/java replace string to bold or some color in webview in html
i have a string ticker..
ticker="hdfc:123:-1.90 tcc:231:+1.3 as continue to hundreds of

ticker will get from the server. i just want to bold the name... so help me to find my solution.....

here is my code...

```<code>tiker = TickerConnection.getInstance().Ticker();

    WebView mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);String summary = "<html><body><MARQUEE>"+tiker+"</MARQUEE></body></html>";
mWebView.loadData(summary, "text/html", "utf-8");
</code>```

答:
hey following is ur solution... u jst have to add tag

```<code>tiker = TickerConnection.getInstance().Ticker();

    WebView mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);String summary = "<html><body><MARQUEE><b>"+tiker+"</b></MARQUEE></body></html>";
mWebView.loadData(summary, "text/html", "utf-8");
</code>```

Body:
i have a string ticker..
ticker="hdfc:123:-1.90 tcc:231:+1.3 as continue to hundreds of

ticker will get from the server. i just want to bold the name... so help me to find my solution.....

here is my code...

tiker = TickerConnection.getInstance().Ticker();

    WebView mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);String summary = "<MARQUEE>"+tiker+"</MARQUEE>";
mWebView.loadData(summary, "text/html", "utf-8");

Body:
hey following is ur solution... u jst have to add tag <b>

tiker = TickerConnection.getInstance().Ticker();

    WebView mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);String summary = "<html><body><MARQUEE><b>"+tiker+"</b></MARQUEE></body></html>";
mWebView.loadData(summary, "text/html", "utf-8");


问:
Unit test a non returnable function which randomly generates numbers
Am new in unit testing, I have a function which doesn't return anything and generates numbers randomly from a certain number to another,  I read about the mocking library but it's still confusing to me, how can I unit test this function.

What I want to test

Testing if numbers are generated between 1000 and 8876.

Checking the positions of different numbers with a 4 -digit values are not equal to each other. e.g 1234, this number is allowed because it has no repetitions. but 1123 is not allowed because it has a number repeated in different positions. That's what the while loop is doing.

I tried to read similar questions e.g link 1  link 2 but I couldn't connect to this scenario

```<code>def num(self):

                    random = randint(1000, 8876)

                    random = list(map(int, str(random)))

                    while random[0] == random[1] or random[0] == random[2] or random[0] == random[3] or random[1] == random[2] or random[1] == random[3] or random[2] == random[3]:

                            random = randint(1000, 8876)

                            random = list(map(int, str(random)))

                    num = ""

                    self.num = int(num.join(map(str,random)))
</code>```

答:
split this up into two parts, one part which generates a random number and one part which checks that the number satisfies your rules.

something like:

```<code>number = generateNumber(1000, 8876) // this is where you do the random generation
verifyNumber(number) // this is another method where you check the rules
//do whatever else after this.
</code>```

All you have to do now is test your business rules, you can throw whatever numbers you want at your second method, without depending on anything random.

you can't test randomness and there's no point testing library methods. Test your rules, by eliminating the things that you cannot control.

Body:
Am new in unit testing, I have a function which doesn't return anything and generates numbers randomly from a certain number to another,  I read about the mocking library but it's still confusing to me, how can I unit test this function.

What I want to test

Testing if numbers are generated between 1000 and 8876.

Checking the positions of different numbers with a 4 -digit values are not equal to each other. e.g 1234, this number is allowed because it has no repetitions. but 1123 is not allowed because it has a number repeated in different positions. That's what the while loop is doing.

I tried to read similar questions e.g link 1  link 2 but I couldn't connect to this scenario

def num(self):

                    random = randint(1000, 8876)

                    random = list(map(int, str(random)))

                    while random[0] == random[1] or random[0] == random[2] or random[0] == random[3] or random[1] == random[2] or random[1] == random[3] or random[2] == random[3]:

                            random = randint(1000, 8876)

                            random = list(map(int, str(random)))

                    num = ""

                    self.num = int(num.join(map(str,random)))

Body:
split this up into two parts, one part which generates a random number and one part which checks that the number satisfies your rules.

something like:

number = generateNumber(1000, 8876) // this is where you do the random generation
verifyNumber(number) // this is another method where you check the rules
//do whatever else after this.

All you have to do now is test your business rules, you can throw whatever numbers you want at your second method, without depending on anything random.

you can't test randomness and there's no point testing library methods. Test your rules, by eliminating the things that you cannot control.


问:
valgrind : Opening several suppression files at once
I have a script which executes my unit tests using valgrind. Now the script became big, because I have maybe 10 suppression files (one per library), and it is possible that I will have to add more suppressions files.

Now instead of having a line like this :

```<code>MEMCHECK_OPTIONS="--tool=memcheck -q -v --num-callers=24 --leak-check=full --show-below-main=no --undef-value-errors=yes --leak-resolution=high --show-reachable=yes --error-limit=no --xml=yes --suppressions=$SUPPRESSION_FILES_DIR/suppression_stdlib.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_cg.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_glut.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_xlib.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_glibc.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_glib.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_qt.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_sdl.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_magick.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_sqlite.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_ld.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_selinux.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_opengl.supp"
</code>```

I tried doing like this:

```<code>MEMCHECK_OPTIONS="--tool=memcheck -q -v --num-callers=24 --leak-check=full --show-below-main=no --undef-value-errors=yes --leak-resolution=high --show-reachable=yes --error-limit=no --xml=yes --suppressions=$SUPPRESSION_FILES_DIR/*.supp"
</code>```

but valgrind needs a filename (doesn't accept the asterix).

Since I am doing this in a bash script, can someone tell me what is the easiest way to form that line?

I thought about listing all files in the suppression directory, then iterating over that list, and adding --suppressions= prefix.

EDIT

I forgot to ask. This is what I have so far :

```<code>ALL_SUPPRESION_FILES=`ls $SUPPRESSION_FILES_DIR/*.supp`
</code>```

but I can not find how to transfer that into an array. Can someone help?

答:
For those who still facing this problem - have a look at Valgrind Suppression File Howto.

When valgrind runs its default tool, Memcheck, it automatically tries to read a file called $PREFIX/lib/valgrind/default.supp ($PREFIX will normally be /usr). However you can make it use additional suppression files of your choice by adding --suppressions= to your command-line invocation. You can repeat this up to 100 times, which should be sufficient for most situations ;)

Rather than having to type this each time, it's more sensible to write it to an rc file. Each time it runs, valgrind looks for options in files called ~/.valgrindrc and ./.valgrindrc. [...]

Create the files if they don't already exist. So I now have a ~/.valgrindrc containing:

```<code>--memcheck:leak-check=full
--show-reachable=yes
--suppressions=/file/path/file1.supp
--suppressions=/file/path/file2.suppth/file2.supp
</code>```

To check that valgrind is actually using the suppression files, run it with the -v option. The list of suppression files read is near the beginning of the output.

Body:
I have a script which executes my unit tests using valgrind. Now the script became big, because I have maybe 10 suppression files (one per library), and it is possible that I will have to add more suppressions files.

Now instead of having a line like this :

MEMCHECK_OPTIONS="--tool=memcheck -q -v --num-callers=24 --leak-check=full --show-below-main=no --undef-value-errors=yes --leak-resolution=high --show-reachable=yes --error-limit=no --xml=yes --suppressions=$SUPPRESSION_FILES_DIR/suppression_stdlib.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_cg.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_glut.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_xlib.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_glibc.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_glib.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_qt.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_sdl.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_magick.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_sqlite.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_ld.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_selinux.supp --suppressions=$SUPPRESSION_FILES_DIR/suppression_opengl.supp"

I tried doing like this:

MEMCHECK_OPTIONS="--tool=memcheck -q -v --num-callers=24 --leak-check=full --show-below-main=no --undef-value-errors=yes --leak-resolution=high --show-reachable=yes --error-limit=no --xml=yes --suppressions=$SUPPRESSION_FILES_DIR/*.supp"

but valgrind needs a filename (doesn't accept the asterix).

Since I am doing this in a bash script, can someone tell me what is the easiest way to form that line?

I thought about listing all files in the suppression directory, then iterating over that list, and adding --suppressions= prefix.

EDIT

I forgot to ask. This is what I have so far :

ALL_SUPPRESION_FILES=`ls $SUPPRESSION_FILES_DIR/*.supp`

but I can not find how to transfer that into an array. Can someone help?

Body:
For those who still facing this problem - have a look at Valgrind Suppression File Howto.

When valgrind runs its default tool, Memcheck, it automatically tries to read a file called $PREFIX/lib/valgrind/default.supp ($PREFIX will normally be /usr). However you can make it use additional suppression files of your choice by adding --suppressions= to your command-line invocation. You can repeat this up to 100 times, which should be sufficient for most situations ;)

Rather than having to type this each time, it's more sensible to write it to an rc file. Each time it runs, valgrind looks for options in files called ~/.valgrindrc and ./.valgrindrc. [...]

Create the files if they don't already exist. So I now have a ~/.valgrindrc containing:

--memcheck:leak-check=full
--show-reachable=yes
--suppressions=/file/path/file1.supp
--suppressions=/file/path/file2.suppth/file2.supp

To check that valgrind is actually using the suppression files, run it with the -v option. The list of suppression files read is near the beginning of the output.


问:
How to do periodic polling/query to database in every 5 sec in background in ruby on rails
I have a ruby on rails application which sends push notifications based on new records created in database in every 5 seconds. Is there any way apart from CRON jobs to do polling/query in DB to check for new records.

My current code implementation is running CRON evey minute which sleeps for 5 seconds, but this approach taking huge memory consumption.

```<code>schedule.rb #whenever gem file

 every 1.minute do
  runner "DailyNotificationChecker.send_notifications"
end
</code>```

*
    ### below code calls method process_notes every 5 sec

```<code>    def self.send_notifications
        expiry_time = Time.now + 57
        while (Time.now < expiry_time)
            if RUN_SCHEDULER == "true" || RUN_SCHEDULER == true
              process_notes  #calls method mentioned below
            end
          sleep 5 #seconds
        end
      end

 ### below code check for new records and sends notification

    def self.process_notes
      notes = nil
      time = Benchmark.measure do
        Note.uncached do
          notes = Note.where("(created_at > DATE_SUB(now(), INTERVAL 2 minute)) AND `notes`.`processed` = 0")
          if notes.present?
            note_ids = notes.collect{|x| x.id}
            RealtimeNotifier.new.delay.perform(note_ids,NOTE_CREATED,TEMP_USER_NOTE)
          end
        end
      end
    end
</code>```

This code snippet is working but not an optimised solution. Is there a better way to achieve this.

答:
MySQL allows you to setup a trigger that calls a user defined function (written in C or C++), other databases might have a similar functionality. From there you can replace the current running process with a bash script in which you place the command(s) to run. I can't give you an example, since I never needed this. But this might point you in the right direction.

Have a look at the following pages:

MySQL Adding a New User-Defined Function

man 3 exec (you might need man 2 fork to first split of a new process here is an example)

How to Create and Use Bash Scripts (trigger rake command here)

Applying this solution would change your poll based solution into a push based solution.

Body:
I have a ruby on rails application which sends push notifications based on new records created in database in every 5 seconds. Is there any way apart from CRON jobs to do polling/query in DB to check for new records.

My current code implementation is running CRON evey minute which sleeps for 5 seconds, but this approach taking huge memory consumption.

schedule.rb #whenever gem file

 every 1.minute do
  runner "DailyNotificationChecker.send_notifications"
end

*
    ### below code calls method process_notes every 5 sec

    def self.send_notifications
        expiry_time = Time.now + 57
        while (Time.now < expiry_time)
            if RUN_SCHEDULER == "true" || RUN_SCHEDULER == true
              process_notes  #calls method mentioned below
            end
          sleep 5 #seconds
        end
      end

 ### below code check for new records and sends notification

    def self.process_notes
      notes = nil
      time = Benchmark.measure do
        Note.uncached do
          notes = Note.where("(created_at > DATE_SUB(now(), INTERVAL 2 minute)) AND `notes`.`processed` = 0")
          if notes.present?
            note_ids = notes.collect{|x| x.id}
            RealtimeNotifier.new.delay.perform(note_ids,NOTE_CREATED,TEMP_USER_NOTE)
          end
        end
      end
    end

This code snippet is working but not an optimised solution. Is there a better way to achieve this.


问:
Split a string into several lists
So I am trying to convert a reverse polish mathematical expression that is presented as a list into a formula. I am trying to do this by splitting the expression into smaller sums and then combining them

This is the code I have so far

```<code>import re
expression = [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']
polish_expression = " ".join([str(i) for i in expression])

numbers  = re.split ("(\D\s)",polish_expression)

print(numbers)
</code>```

but the output is:
['15 7 1 1 ', '+ ', '', '- ', '', '/ ', '3 ', '* ', '2 1 1 ', '+ ', '', '+ ', '-']

Can I get the desired output using regex (something along the lines of):
[[15,7,1,1],["+","-","/"],[3],["*"],[2,1,1],["+","+","-"]]

Edit:

```<code>import re
expression = [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']
polish_expression = "".join([str(i) for i in expression])
numbers  = filter(None, re.split ("(\d+)",polish_expression))
print(list(numbers))
</code>```

Gets close but the numbers all appear a single string
['15711', '+-/', '3', '*', '211', '++-']

答:
Using regex, the following code can produce the desired results

```<code>polish_expression = ' '.join(map(str, expression))
split_output = re.split(r'((?:\d+ )+)', polish_expression)
# ['', '15 7 1 1 ', '+ - / ', '3 ', '* ', '2 1 1 ', '+ + -']
stripped_output = [s.strip() for s in split_output if s]
# ['15 7 1 1', '+ - /', '3', '*', '2 1 1', '+ + -']
string_list_output = [s.split(' ') for s in stripped_output]
# [['15', '7', '1', '1'], ['+', '-', '/'], ['3'], ['*'], ['2', '1', '1'], ['+', '+', '-']]
desired_output = [list(map(int, item)) if item[0].isdigit() else item for item in string_op]
# [[15, 7, 1, 1], ['+', '-', '/'], [3], ['*'], [2, 1, 1], ['+', '+', '-']]
</code>```

A simple non-regex solution would be:

If your expression list is a mix of str and int types as given in the question, the following code can be used:

```<code>output = [[expression[0]]]

for item in expression[1:]:
    if type(item) == type(output[op_index][0]):
        output[op_index].append(item)
    else:
        output.append([item])
        op_index += 1

print(output)
# [[15, 7, 1, 1], ['+', '-', '/'], [3], ['*'], [2, 1, 1], ['+', '+', '-']]
</code>```

If they're all str, then you should be able to use str.isdigit() to differentiate.

Title: Split a string into several lists

Body:
So I am trying to convert a reverse polish mathematical expression that is presented as a list into a formula. I am trying to do this by splitting the expression into smaller sums and then combining them

This is the code I have so far

import re
expression = [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']
polish_expression = " ".join([str(i) for i in expression])

numbers  = re.split ("(\D\s)",polish_expression)

print(numbers)

but the output is:
['15 7 1 1 ', '+ ', '', '- ', '', '/ ', '3 ', '* ', '2 1 1 ', '+ ', '', '+ ', '-']

Can I get the desired output using regex (something along the lines of):
[[15,7,1,1],["+","-","/"],[3],["*"],[2,1,1],["+","+","-"]]

Edit:

import re
expression = [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-']
polish_expression = "".join([str(i) for i in expression])
numbers  = filter(None, re.split ("(\d+)",polish_expression))
print(list(numbers))

Gets close but the numbers all appear a single string
['15711', '+-/', '3', '*', '211', '++-']

Body:
Using regex, the following code can produce the desired results

polish_expression = ' '.join(map(str, expression))
split_output = re.split(r'((?:\d+ )+)', polish_expression)
# ['', '15 7 1 1 ', '+ - / ', '3 ', '* ', '2 1 1 ', '+ + -']
stripped_output = [s.strip() for s in split_output if s]
# ['15 7 1 1', '+ - /', '3', '*', '2 1 1', '+ + -']
string_list_output = [s.split(' ') for s in stripped_output]
# [['15', '7', '1', '1'], ['+', '-', '/'], ['3'], ['*'], ['2', '1', '1'], ['+', '+', '-']]
desired_output = [list(map(int, item)) if item[0].isdigit() else item for item in string_op]
# [[15, 7, 1, 1], ['+', '-', '/'], [3], ['*'], [2, 1, 1], ['+', '+', '-']]

A simple non-regex solution would be:

If your expression list is a mix of str and int types as given in the question, the following code can be used:

output = [[expression[0]]]

for item in expression[1:]:
    if type(item) == type(output[op_index][0]):
        output[op_index].append(item)
    else:
        output.append([item])
        op_index += 1

print(output)
# [[15, 7, 1, 1], ['+', '-', '/'], [3], ['*'], [2, 1, 1], ['+', '+', '-']]

If they're all str, then you should be able to use str.isdigit() to differentiate.


问:
Minikube expose MySQL running on localhost as service
I have minikube version v0.17.1 running on my machine. I want to simulate the environment I will have in AWS, where my MySQL instance will be outside of my Kubernetes cluster.

Basically, how can I expose my local MySQL instance running on my machine to the Kubernetes cluster running via minikube?

答:
Option 1 - use a headless service without selectors

Because this service has no selector, the corresponding Endpoints object will not be created. You can manually map the service to your own specific endpoints (See doc).

```<code>kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  ports:
  - port: 80
    targetPort: 8080
---
kind: Endpoints
apiVersion: v1
metadata:
  name: my-service
subsets:
- addresses:
  - ip: 10.0.2.2
  ports:
  - port: 8080
</code>```

Option 2 - use ExternalName service

```<code>kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  type: ExternalName
  externalName: minikube.host
</code>```

The only caveat is that it needs to be able to resolve minikube.host. Simply add this line to the etc/hosts file should do it.

```<code>10.0.2.2        minikube.host
</code>```

ExternalName doesn't support port mapping at the moment.

Another note: The IP 10.0.2.2 is known to work with Virtual Box only (see SO).
For xhyve, try replacing that with 192.168.99.1 (see GitHub issue and issue). A demo GitHub.

Body:
Option 1 - use a headless service without selectors

Because this service has no selector, the corresponding Endpoints object will not be created. You can manually map the service to your own specific endpoints (See doc).

kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  ports:
  - port: 80
    targetPort: 8080
---
kind: Endpoints
apiVersion: v1
metadata:
  name: my-service
subsets:
- addresses:
  - ip: 10.0.2.2
  ports:
  - port: 8080

Option 2 - use ExternalName service

kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  type: ExternalName
  externalName: minikube.host

The only caveat is that it needs to be able to resolve minikube.host. Simply add this line to the etc/hosts file should do it.

10.0.2.2        minikube.host

ExternalName doesn't support port mapping at the moment.

Another note: The IP 10.0.2.2 is known to work with Virtual Box only (see SO).
For xhyve, try replacing that with 192.168.99.1 (see GitHub issue and issue). A demo GitHub.


问:
Swift - Unable to open file in target Xcode 10
I am trying to run Aplication which I have downloaded from GitHub.

When I run get error unable to open file in target, I have Xcode 10.

I already searched for solution and get this one.

I had the same problem, but in Xcode 6.1.1 - what fixed it for me was to change the configuration file setting to None for the two Pods-related targets, then run pod install again.

The configuration file setting is found by selecting the project (not the target) and then the Info tab.

But cant find configuration file location.

Here is the error picture:
https://i.stack.imgur.com/Ql3M5.png

答:
I tried below and error went away !!

project name - SwiftExample

Went to Pods -> Info -> Configurations -> Debug
Change to None for Pods-SwiftExample

Code compiles even after setting it back to original.


问:
invalidate only works in custom view
so i created a view called "drawable view"

```<code> class DrawableView extends View{
        Context mContext;

        int touches=0,k,Xoffs,clicks=0;

  double x_1 = 0,x_2=0;

        private float mLastTouchX, mLastTouchY;

        public DrawableView(Context context) {
        super(context);
        mContext = context;
        }

....
    @Override
    protected void onDraw(Canvas canvas){

        Paint myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

canvas.drawColor(Color.BLUE);
myPaint.setColor(Color.WHITE);

canvas.drawCircle(200, 100, 20, myPaint);

    }

..... more code....

}
</code>```

and it can only be invalidated within the ondraw command! ie: calling "invalidate();" at the end of the ondraw command causes it to loop.

I have tried many times to call g_draw.invalidate(); or g_draw.postInvalidate(); (g_draw is the name of the created Drawable View)from other classes and even the main activity class and it doesnt work. why and how can i fix it?

thanks

答:
If you want continious onDraw invoking try doing it in another thread. Create a thread, and from its run method try doing postInvalidate.

It always worked for me.

Another thing is that when you draw a circle once, next time wont make any difference - it will look the same.

Title: invalidate only works in custom view

Body:
so i created a view called "drawable view"

 class DrawableView extends View{
        Context mContext;

        int touches=0,k,Xoffs,clicks=0;

  double x_1 = 0,x_2=0;

        private float mLastTouchX, mLastTouchY;

        public DrawableView(Context context) {
        super(context);
        mContext = context;
        }

....
    @Override
    protected void onDraw(Canvas canvas){

        Paint myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

canvas.drawColor(Color.BLUE);
myPaint.setColor(Color.WHITE);

canvas.drawCircle(200, 100, 20, myPaint);

    }

..... more code....

}

and it can only be invalidated within the ondraw command! ie: calling "invalidate();" at the end of the ondraw command causes it to loop.

I have tried many times to call g_draw.invalidate(); or g_draw.postInvalidate(); (g_draw is the name of the created Drawable View)from other classes and even the main activity class and it doesnt work. why and how can i fix it?

thanks


问:
A program that's supposed to find out whether a number is prime or not isn't working as expected
I'm trying to make a program which will find if a number is prime or not with a very simple formula: divide the number(x) by 4. see if any number from 1 to x/4 divides perfectly by x. If not, x will be prime.

The program currently shows me the result from dividing x by every number from 1 to x/4. I want to do this: If there's a number that divides perfectly, print that x is not prime and end the program. Or if there's no numbers that divide by x, just say that x is prime and end the program.

I tried using booleans but then it showed every number as prime, which it should not do since the program doesn't know yet that x can be perfectly divided by 1 but will still be prime.

```<code>value = int(input("Type a number: "))

# prime = True

if value.__class__ == int:
    x = value / 4
    list = list(range(1, int(x) + 1))
    for number in list:
        y = value / number

        while y >= 0:
            y -= 1
            if y == 0:
                print(f"{value} is not prime")
                # print("yes")
                # y == -1
            elif 0 < y < 1:
                print(f"{value} is prime")
                # print("no")
    # if prime:
    #     print(f"{value} is prime")
    # else:
    #     print(f"{value} is not prime")
</code>```

答:
Your first logic is wrong. You need to check up to math.sqrt(x)

```<code>>>> import math
>>> [a/4 < math.sqrt(a) for a in range(100)]
[False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False]
</code>```

This will technically work beyond x=15 but then you'll be checking more numbers than you need to
You can see this by looking at the graphs https://www.desmos.com/calculator/dybweqs6lk

Body:
I'm trying to make a program which will find if a number is prime or not with a very simple formula: divide the number(x) by 4. see if any number from 1 to x/4 divides perfectly by x. If not, x will be prime.

The program currently shows me the result from dividing x by every number from 1 to x/4. I want to do this: If there's a number that divides perfectly, print that x is not prime and end the program. Or if there's no numbers that divide by x, just say that x is prime and end the program.

I tried using booleans but then it showed every number as prime, which it should not do since the program doesn't know yet that x can be perfectly divided by 1 but will still be prime.

value = int(input("Type a number: "))

# prime = True

if value.__class__ == int:
    x = value / 4
    list = list(range(1, int(x) + 1))
    for number in list:
        y = value / number

        while y >= 0:
            y -= 1
            if y == 0:
                print(f"{value} is not prime")
                # print("yes")
                # y == -1
            elif 0 < y < 1:
                print(f"{value} is prime")
                # print("no")
    # if prime:
    #     print(f"{value} is prime")
    # else:
    #     print(f"{value} is not prime")

Body:
Your first logic is wrong. You need to check up to math.sqrt(x)

>>> import math
>>> [a/4 < math.sqrt(a) for a in range(100)]
[False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False]

This will technically work beyond x=15 but then you'll be checking more numbers than you need to
You can see this by looking at the graphs https://www.desmos.com/calculator/dybweqs6lk


问:
How can I open file location to show a file?
I am making video player app. And I want to add option like, when user taps,it opens default file manager to show this video file's location.

Here is sample from Windows OS

Any help would be appreciated !

答:
You can do this by this method.</p>

```<code>public void open_Folder(String location)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
     + File.separator+ location + File.separator);
intent.setDataAndType(uri, "set your data type");
startActivity(Intent.createChooser(intent, "Select file manager app."));
}
</code>```

Body:
You can do this by this method.

public void open_Folder(String location)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
     + File.separator+ location + File.separator);
intent.setDataAndType(uri, "set your data type");
startActivity(Intent.createChooser(intent, "Select file manager app."));
}