问:
Creating a folder or file in External microSD card
I have searched everywhere for the answer to my problem and i did found a large amount of answer which should have solved my it but yet i can't solved it.

My Goal is to put a SD card with 128GB and to write files into it (csv or text).
I'm trying to open a file or a folder in my microSD card but it do not create it.
also the file is not created. I think the Path that i get from:

```<code>Environment.getExternalStorageDirectory()
</code>```

is not The SD Card Path.

here is my java code :

```<code>package com.example.thermie.test2;

import android.Manifest;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.util.Date;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.os.Environment.DIRECTORY_DCIM;
import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

// Log used as debug
        try {
            boolean mExternalStorageAvailable = false;
            boolean mExternalStorageWriteable = false;

            String state = Environment.getExternalStorageState();

            if (Environment.MEDIA_MOUNTED.equals(state)) {
                // We can read and write the media
                mExternalStorageAvailable = mExternalStorageWriteable = true;
                Toast.makeText(MainActivity.this,
                        "Read and Write", Toast.LENGTH_LONG).show();
            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                // We can only read the media
                mExternalStorageAvailable = true;
                mExternalStorageWriteable = false;
                Toast.makeText(MainActivity.this,
                        "onlyread", Toast.LENGTH_LONG).show();
            } else {
                // Something else is wrong. It may be one of many other states, but all we need
                //  to know is we can neither read nor write
                mExternalStorageAvailable = mExternalStorageWriteable = false;
             Toast.makeText(MainActivity.this,
                        "cant writer", Toast.LENGTH_LONG).show();

            }
            String sdkS =  String.valueOf(android.os.Build.VERSION.SDK_INT);
            Toast.makeText(MainActivity.this,
            sdkS, Toast.LENGTH_LONG).show();

            String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
            //create folder
            File folder = new File(dir); //folder name
            boolean result = folder.mkdirs();

            //create file
            File file = new File(dir, "filename.txt");

            if (result){
                Toast.makeText(MainActivity.this,
                        "True", Toast.LENGTH_LONG).show();

            }
            TextView textView = (TextView)findViewById(R.id.textView2);
            textView.setText(dir);
            Toast.makeText(MainActivity.this,
                    String.valueOf(state), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "Error opening Log.", e);
            Toast.makeText(MainActivity.this,
                    "not good", Toast.LENGTH_LONG).show();
        }

    }
}
</code>```

My dir is : /storage/emulated/0/myDirectory
Which is not in my SD card , it's the internal memory in an directory without any access.

my results of :

```<code>boolean result = folder.mkdirs();
</code>```

is not true. so no folder opens , i also tried :

```<code>boolean result = folder.mkdir();
</code>```

and my Toasts says:

Read and Write

23 (API)

mounted (sd mounted)

Phone galaxy s5.
andorid version 6.0.1 Marshmallow.

Here is my manifeset :

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

    package="com.example.thermie.test2">

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

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

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

</manifest>
</code>```

Hope it is detail enough.
Thanks you all.

答:
Ok This is my sloppy code and it's writing a txt file in my local storage. (xml file staied the same)</p>

```<code>package com.example.thermie.test2;

import android.Manifest;
import android.content.Context;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.R.attr.path;
import static android.os.Environment.DIRECTORY_DCIM;
import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
    private String filename = "natiFile.txt";
    private String filepath = "/storage/extSdCard";
    File myExternalFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

// Log used as debug
        try {
            boolean mExternalStorageAvailable = false;
            boolean mExternalStorageWriteable = false;

            String state = Environment.getExternalStorageState();

            if (Environment.MEDIA_MOUNTED.equals(state)) {
                // We can read and write the media
                mExternalStorageAvailable = mExternalStorageWriteable = true;
                Toast.makeText(MainActivity.this,
                        "Read and Write", Toast.LENGTH_LONG).show();
            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                // We can only read the media
                mExternalStorageAvailable = true;
                mExternalStorageWriteable = false;
                Toast.makeText(MainActivity.this,
                        "onlyread", Toast.LENGTH_LONG).show();
            } else {
                // Something else is wrong. It may be one of many other states, but all we need
                //  to know is we can neither read nor write
                mExternalStorageAvailable = mExternalStorageWriteable = false;
             Toast.makeText(MainActivity.this,
                        "cant writer", Toast.LENGTH_LONG).show();

            }
            String sdkS =  String.valueOf(android.os.Build.VERSION.SDK_INT);
            Toast.makeText(MainActivity.this,
            sdkS, Toast.LENGTH_LONG).show();

            File dir = Environment.getExternalStoragePublicDirectory(DIRECTORY_DCIM);
            final File file = new File(dir, "config.txt");

            String secStore = System.getenv("SECONDARY_STORAGE");
            File f_secs = new File(secStore);

            myExternalFile = new File(getExternalFilesDir(filepath), filename);

            String data = "gdsg";
            try {
                FileOutputStream fos = new FileOutputStream(myExternalFile);
                fos.write(data.getBytes());
                fos.close();
                Toast.makeText(MainActivity.this,
                        "great", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                e.printStackTrace();
            }

            File folder = new File(f_secs.getAbsolutePath() + "/TollCulator/");
            boolean testing = folder.mkdirs();
            if (testing){
                Toast.makeText(MainActivity.this,
                        "True", Toast.LENGTH_LONG).show();

            }
            TextView textView = (TextView)findViewById(R.id.textView2);
            textView.setText(f_secs.getPath());
            Toast.makeText(MainActivity.this,
                    String.valueOf(state), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "Error opening Log.", e);
            Toast.makeText(MainActivity.this,
                    "not good", Toast.LENGTH_LONG).show();
        }

    }
}
</code>```

Body:
I have searched everywhere for the answer to my problem and i did found a large amount of answer which should have solved my it but yet i can't solved it.

My Goal is to put a SD card with 128GB and to write files into it (csv or text).
I'm trying to open a file or a folder in my microSD card but it do not create it.
also the file is not created. I think the Path that i get from:

Environment.getExternalStorageDirectory()

is not The SD Card Path.

here is my java code :

package com.example.thermie.test2;

import android.Manifest;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.util.Date;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.os.Environment.DIRECTORY_DCIM;
import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

// Log used as debug
        try {
            boolean mExternalStorageAvailable = false;
            boolean mExternalStorageWriteable = false;

            String state = Environment.getExternalStorageState();

            if (Environment.MEDIA_MOUNTED.equals(state)) {
                // We can read and write the media
                mExternalStorageAvailable = mExternalStorageWriteable = true;
                Toast.makeText(MainActivity.this,
                        "Read and Write", Toast.LENGTH_LONG).show();
            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                // We can only read the media
                mExternalStorageAvailable = true;
                mExternalStorageWriteable = false;
                Toast.makeText(MainActivity.this,
                        "onlyread", Toast.LENGTH_LONG).show();
            } else {
                // Something else is wrong. It may be one of many other states, but all we need
                //  to know is we can neither read nor write
                mExternalStorageAvailable = mExternalStorageWriteable = false;
             Toast.makeText(MainActivity.this,
                        "cant writer", Toast.LENGTH_LONG).show();

            }
            String sdkS =  String.valueOf(android.os.Build.VERSION.SDK_INT);
            Toast.makeText(MainActivity.this,
            sdkS, Toast.LENGTH_LONG).show();

            String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
            //create folder
            File folder = new File(dir); //folder name
            boolean result = folder.mkdirs();

            //create file
            File file = new File(dir, "filename.txt");

            if (result){
                Toast.makeText(MainActivity.this,
                        "True", Toast.LENGTH_LONG).show();

            }
            TextView textView = (TextView)findViewById(R.id.textView2);
            textView.setText(dir);
            Toast.makeText(MainActivity.this,
                    String.valueOf(state), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "Error opening Log.", e);
            Toast.makeText(MainActivity.this,
                    "not good", Toast.LENGTH_LONG).show();
        }

    }
}

My dir is : /storage/emulated/0/myDirectory
Which is not in my SD card , it's the internal memory in an directory without any access.

my results of :

boolean result = folder.mkdirs();

is not true. so no folder opens , i also tried :

boolean result = folder.mkdir();

and my Toasts says:

Read and Write

23 (API)

mounted (sd mounted)

Phone galaxy s5.
andorid version 6.0.1 Marshmallow.

Here is my manifeset :

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

    package="com.example.thermie.test2">

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

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

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

</manifest>

Hope it is detail enough.
Thanks you all.

Body:
Ok This is my sloppy code and it's writing a txt file in my local storage. (xml file staied the same)

package com.example.thermie.test2;

import android.Manifest;
import android.content.Context;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.R.attr.path;
import static android.os.Environment.DIRECTORY_DCIM;
import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
    private String filename = "natiFile.txt";
    private String filepath = "/storage/extSdCard";
    File myExternalFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

// Log used as debug
        try {
            boolean mExternalStorageAvailable = false;
            boolean mExternalStorageWriteable = false;

            String state = Environment.getExternalStorageState();

            if (Environment.MEDIA_MOUNTED.equals(state)) {
                // We can read and write the media
                mExternalStorageAvailable = mExternalStorageWriteable = true;
                Toast.makeText(MainActivity.this,
                        "Read and Write", Toast.LENGTH_LONG).show();
            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                // We can only read the media
                mExternalStorageAvailable = true;
                mExternalStorageWriteable = false;
                Toast.makeText(MainActivity.this,
                        "onlyread", Toast.LENGTH_LONG).show();
            } else {
                // Something else is wrong. It may be one of many other states, but all we need
                //  to know is we can neither read nor write
                mExternalStorageAvailable = mExternalStorageWriteable = false;
             Toast.makeText(MainActivity.this,
                        "cant writer", Toast.LENGTH_LONG).show();

            }
            String sdkS =  String.valueOf(android.os.Build.VERSION.SDK_INT);
            Toast.makeText(MainActivity.this,
            sdkS, Toast.LENGTH_LONG).show();

            File dir = Environment.getExternalStoragePublicDirectory(DIRECTORY_DCIM);
            final File file = new File(dir, "config.txt");

            String secStore = System.getenv("SECONDARY_STORAGE");
            File f_secs = new File(secStore);

            myExternalFile = new File(getExternalFilesDir(filepath), filename);

            String data = "gdsg";
            try {
                FileOutputStream fos = new FileOutputStream(myExternalFile);
                fos.write(data.getBytes());
                fos.close();
                Toast.makeText(MainActivity.this,
                        "great", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                e.printStackTrace();
            }

            File folder = new File(f_secs.getAbsolutePath() + "/TollCulator/");
            boolean testing = folder.mkdirs();
            if (testing){
                Toast.makeText(MainActivity.this,
                        "True", Toast.LENGTH_LONG).show();

            }
            TextView textView = (TextView)findViewById(R.id.textView2);
            textView.setText(f_secs.getPath());
            Toast.makeText(MainActivity.this,
                    String.valueOf(state), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "Error opening Log.", e);
            Toast.makeText(MainActivity.this,
                    "not good", Toast.LENGTH_LONG).show();
        }

    }
}


来源: stackexchange

问:
Looping a macro for duplicates
I have a macro that runs through data looking for duplicate barcodes, then moves the 'oldest' duplicate (based off a date in another column) to another sheet.

Problem here is that I have multiple duplicates due to data entry error and need to run the macro at least 3 times. I would like this program to run automatically, so I need to loop this macro until there are no duplicates. I am thinking 'Do While' but would appreciate some guidance. Here is the code:

```<code>Sub DupMove() 'Moves the oldest duplicate to seperate sheet
Dim t As Single
Dim d As Object, x&, xcol As String
Dim lc&, lr&, k(), e As Range
xcol = "C"
lc = Cells.Find("*", after:=[a1], SearchDirection:=xlPrevious).Column
lr = Cells.Find("*", after:=[a1], SearchDirection:=xlPrevious).Row
ReDim k(1 To lr, 1 To 1)
Set d = CreateObject("scripting.dictionary")
For Each e In Cells(1, xcol).Resize(lr)
    If Not d.exists(e.Value) Then
        d.Add e.Value, Array(Cells(e.Row, 5), e.Row)
        k(e.Row, 1) = 1
    Else
        If d(e.Value)(0).Value < Cells(e.Row, 5).Value Then
            k(d(e.Value)(1), 1) = ""
            k(e.Row, 1) = 1
            d(e.Value)(0) = Cells(e.Row, 5)
            d(e.Value)(1) = e.Row
        End If
    End If
Next e
Cells(1, lc + 1).Resize(lr) = k
Range("A1", Cells(lr, lc + 1)).Sort Cells(1, lc + 1), 1
x = Cells(1, lc + 1).End(4).Row
Cells(x + 1, 1).Resize(lr - x, lc).Copy Sheets("Duplicates").Range("A1")
Cells(x + 1, 1).Resize(lr - x, lc).Clear
Cells(1, lc + 1).Resize(x).Clear
End Sub
</code>```

答:
here's a crude way to find duplicates. adjust to your needs. You can place this in a worksheet change event (i dont recommend) but this does find all dupes</p>

```<code>Private Sub this()

    Dim rng As Range
    Dim rCell As Range
    Dim this As String
    Dim arr(9)

    Set rng = ThisWorkbook.Sheets("Sheet1").Range("a1:a10")

    For Each rCell In rng.Cells
        this = rCell.Value
        For x = LBound(arr, 1) To UBound(arr, 1)
            If this = arr(x) Then
                rCell.Interior.ColorIndex = 7
                Exit For
            ElseIf this <> arr(x) And arr(x) = vbNullString Then
                arr(x) = this
                Exit For
            End If
        Next x
    Next rCell

End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Title: Looping a macro for duplicates

Body:
I have a macro that runs through data looking for duplicate barcodes, then moves the 'oldest' duplicate (based off a date in another column) to another sheet.

Problem here is that I have multiple duplicates due to data entry error and need to run the macro at least 3 times. I would like this program to run automatically, so I need to loop this macro until there are no duplicates. I am thinking 'Do While' but would appreciate some guidance. Here is the code:

Sub DupMove() 'Moves the oldest duplicate to seperate sheet
Dim t As Single
Dim d As Object, x&, xcol As String
Dim lc&, lr&, k(), e As Range
xcol = "C"
lc = Cells.Find("*", after:=[a1], SearchDirection:=xlPrevious).Column
lr = Cells.Find("*", after:=[a1], SearchDirection:=xlPrevious).Row
ReDim k(1 To lr, 1 To 1)
Set d = CreateObject("scripting.dictionary")
For Each e In Cells(1, xcol).Resize(lr)
    If Not d.exists(e.Value) Then
        d.Add e.Value, Array(Cells(e.Row, 5), e.Row)
        k(e.Row, 1) = 1
    Else
        If d(e.Value)(0).Value < Cells(e.Row, 5).Value Then
            k(d(e.Value)(1), 1) = ""
            k(e.Row, 1) = 1
            d(e.Value)(0) = Cells(e.Row, 5)
            d(e.Value)(1) = e.Row
        End If
    End If
Next e
Cells(1, lc + 1).Resize(lr) = k
Range("A1", Cells(lr, lc + 1)).Sort Cells(1, lc + 1), 1
x = Cells(1, lc + 1).End(4).Row
Cells(x + 1, 1).Resize(lr - x, lc).Copy Sheets("Duplicates").Range("A1")
Cells(x + 1, 1).Resize(lr - x, lc).Clear
Cells(1, lc + 1).Resize(x).Clear
End Sub

Body:
here's a crude way to find duplicates. adjust to your needs. You can place this in a worksheet change event (i dont recommend) but this does find all dupes

Private Sub this()

    Dim rng As Range
    Dim rCell As Range
    Dim this As String
    Dim arr(9)

    Set rng = ThisWorkbook.Sheets("Sheet1").Range("a1:a10")

    For Each rCell In rng.Cells
        this = rCell.Value
        For x = LBound(arr, 1) To UBound(arr, 1)
            If this = arr(x) Then
                rCell.Interior.ColorIndex = 7
                Exit For
            ElseIf this <> arr(x) And arr(x) = vbNullString Then
                arr(x) = this
                Exit For
            End If
        Next x
    Next rCell

End Sub


问:
Remaining calculation

I have a database in MS Office Access, used to manage stock. I have two types of transactions Addition = when there is a new item, removal = when items go out.

I need to add a section that will return remaining quantity in stock after I add or remove items. What would you suggest?

Note: I have many items, not one item

答:
What do you mean by 'add a section'? Calculate inventory balance when needed. Search topic 'inventory balance'. Could do an aggregate query for stock received and another for stock used then use those queries in another to calculate difference. Or consider:

SELECT [Transaction Item], Sum(IIf([Transaction Type]="Addition", [Quantity],0)) - Sum(IIf([Transaction Type]="Removal", [Quantity],0)) AS Balance GROUP BY [Transaction Item];

A running balance on form is not practical (not to mention just plain hard to do) especially if records are filtered or sorted. However, you could show the net balance of each item with DSum() domain aggregate function. Try this in the [Inventory Transactions Extended] query.

Balance: Nz(DSum("Quantity","[Inventory Transactions]","[Transaction Type]=1 AND [Transaction Item]=" & [Transaction Item]),0)-Nz(DSum("Quantity","[Inventory Transactions]","[Transaction Type]=2 AND [Transaction Item]=" & [Transaction Item]),0)

The calc will update as soon as record is committed to table. Record is committed when moving to another record, closing form, or by code to save record.

I NEVER build lookups in tables. I want to see the real values when I view tables.

Don't really need to pull [Inventory Transactions] ID field individually to define sort criteria. This is primary key index and records will sort by this field by default. So pulling in the field with the query * wildcard will produce the same sort.

Title: Remaining calculation


问:
React - handleChange of multiple inputs by one function
I have multiple inputs on the page, I'd like to handleChange by only one function which I'm doing already with this code:

```<code>    handleInputChange(event) {

        let modules = this.props.templateModules.slice()
        let inputs

        for(let i in modules) {
            inputs = modules[i].fields
        }

        for(let i in inputs){
            if(inputs[i].name === event.target.name){
                 inputs[i].value = event.target.value;
                 this.setState ({inputs});
                 break;
            }
        }
    }
</code>```

the structure of those modules (which are added dynamically on button click) from console is:

and the input fields withing each of the module:

as you can see the names unfortunately are not unique thus why my code is not working as it should be if there is more than one module on the page. I'd like to map only the fields of module currently on focus (guess that could be an option) just not sure how to do it.

Any ideas? :)

答:
Okay, so if anyone has the same issue as me, I think I found a solution to this.

Instead of handling the change of those inputs in container component which I was doing originally I separated the module rendering into a separate class so the structure looks like this at the moment...

```<code> Container Component

      -> Presentational Component

           -> Module Component (class containing the function handleChange)
</code>```

I'm not sure if that's the correct way to do it but it's the only way I could think of to make it work, and it WORKS! :)

Body:
I have multiple inputs on the page, I'd like to handleChange by only one function which I'm doing already with this code:

    handleInputChange(event) {

        let modules = this.props.templateModules.slice()
        let inputs

        for(let i in modules) {
            inputs = modules[i].fields
        }

        for(let i in inputs){
            if(inputs[i].name === event.target.name){
                 inputs[i].value = event.target.value;
                 this.setState ({inputs});
                 break;
            }
        }
    }

the structure of those modules (which are added dynamically on button click) from console is:

and the input fields withing each of the module:

as you can see the names unfortunately are not unique thus why my code is not working as it should be if there is more than one module on the page. I'd like to map only the fields of module currently on focus (guess that could be an option) just not sure how to do it.

Any ideas? :)

Body:
Okay, so if anyone has the same issue as me, I think I found a solution to this.

Instead of handling the change of those inputs in container component which I was doing originally I separated the module rendering into a separate class so the structure looks like this at the moment...

 Container Component

      -> Presentational Component

           -> Module Component (class containing the function handleChange)

I'm not sure if that's the correct way to do it but it's the only way I could think of to make it work, and it WORKS! :)


问:
Compiling GTK+ applications on windows?
I was following this thread in order to learn gtk but I cant seem to get it to compile.
I've downloaded the GTK all in one bundle and extracted it to c:\gtk (have also set bin as a path variable), but when I try gcc foo.c %VAR% it says gcc: %VAR%: No such file or directory, what am I missig here?.

this is my VAR.bat file

```<code>set VAR = -mms-bitfields -IC:/gtk/include/gtk-2.0 -IC:/gtk/lib/gtk-2.0/include -IC:/gtk/in
clude/atk-1.0 -IC:/gtk/include/cairo -IC:/gtk/include/pango-1.0 -IC:/gtk/include
/glib-2.0 -IC:/gtk/lib/glib-2.0/include -IC:/gtk/include -IC:/gtk/include/freety
pe2 -IC:/gtk/include/libpng14  -LC:/gtk/lib -lgtk-win32-2.0 -lgdk-win32-2.0 -lat
k-1.0 -lgio-2.0 -lgdk_pixbuf-2.0 -lpangowin32-1.0 -lgdi32 -lpangocairo-1.0 -lpan
go-1.0 -lcairo -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lglib-2.0 -lintl

start cmd
</code>```

and I have this in the same directory as foo.c

答:
Remove the spaces around the equals sign in the bat file:</p>

```<code>C:\Users\unwind>set a = hello

C:\Users\unwind>echo %a%
%a%

C:\Users\unwind>set a=hello

C:\Users\unwind>echo %a%
hello
</code>```

ContentLicense: CC BY-SA 2.5

Title: Compiling GTK+ applications on windows?

Body:
I was following this thread in order to learn gtk but I cant seem to get it to compile.
I've downloaded the GTK all in one bundle and extracted it to c:\gtk (have also set bin as a path variable), but when I try gcc foo.c %VAR% it says gcc: %VAR%: No such file or directory, what am I missig here?.

this is my VAR.bat file

set VAR = -mms-bitfields -IC:/gtk/include/gtk-2.0 -IC:/gtk/lib/gtk-2.0/include -IC:/gtk/in
clude/atk-1.0 -IC:/gtk/include/cairo -IC:/gtk/include/pango-1.0 -IC:/gtk/include
/glib-2.0 -IC:/gtk/lib/glib-2.0/include -IC:/gtk/include -IC:/gtk/include/freety
pe2 -IC:/gtk/include/libpng14  -LC:/gtk/lib -lgtk-win32-2.0 -lgdk-win32-2.0 -lat
k-1.0 -lgio-2.0 -lgdk_pixbuf-2.0 -lpangowin32-1.0 -lgdi32 -lpangocairo-1.0 -lpan
go-1.0 -lcairo -lgobject-2.0 -lgmodule-2.0 -lgthread-2.0 -lglib-2.0 -lintl

start cmd

and I have this in the same directory as foo.c

Body:
Remove the spaces around the equals sign in the bat file:

C:\Users\unwind>set a = hello

C:\Users\unwind>echo %a%
%a%

C:\Users\unwind>set a=hello

C:\Users\unwind>echo %a%
hello


问:
Joda time convert ISO8601 GMT to local
I have this from my server:

2017-04-07T11:00:00.000Z

How can I convert it to local time? Here is my code, but all I got is an exception:)

java.lang.IllegalArgumentException: Invalid format: "2017-04-07T11:00:00.000Z" is malformed at "Z"

```<code>DateTimeFormatter inputFormatter = DateTimeFormat
                .forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ") //yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ
                .withLocale(Locale.US);

        DateTime parsed = inputFormatter.parseDateTime(gmtDate);

        DateTimeFormatter outputFormatter = DateTimeFormat
                .forPattern("HH:mm")
                .withLocale(Locale.US)
                .withZone(DateTimeZone.getDefault());

        return outputFormatter.print(parsed);
</code>```

答:
Just change your pattern to yyyy-MM-dd'T'HH:mm:ss.SSSZ, like this:

```<code>DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
                                   .withLocale(Locale.US);
</code>```

In my case, the result of outputFormatter.print(parsed) is 08:00 (my local time, as my default timezone is America/Sao_Paulo)

Title: Joda time convert ISO8601 GMT to local

Body:
I have this from my server:

2017-04-07T11:00:00.000Z

How can I convert it to local time? Here is my code, but all I got is an exception:)

java.lang.IllegalArgumentException: Invalid format: "2017-04-07T11:00:00.000Z" is malformed at "Z"

DateTimeFormatter inputFormatter = DateTimeFormat
                .forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ") //yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ
                .withLocale(Locale.US);

        DateTime parsed = inputFormatter.parseDateTime(gmtDate);

        DateTimeFormatter outputFormatter = DateTimeFormat
                .forPattern("HH:mm")
                .withLocale(Locale.US)
                .withZone(DateTimeZone.getDefault());

        return outputFormatter.print(parsed);

Body:
Just change your pattern to yyyy-MM-dd'T'HH:mm:ss.SSSZ, like this:

DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
                                   .withLocale(Locale.US);

In my case, the result of outputFormatter.print(parsed) is 08:00 (my local time, as my default timezone is America/Sao_Paulo)


问:
Remote Partition: Why Steps not run in parallel?
I am using the Spring Batch remote partitioning. My steps are not running in parallel. Instead they run sequentially I mean the partitioned steps run sequentially. What is the root cause of the issue?

答:
I'm relatively new to Spring Batch, but I had similar problem when I first tried writing my own partitioned step.

In my case, the problem was my taskExecutor (which wasn't asynchronous).
I added a @Bean that initialized an asynTaskExecutor and chained that to my partition step. Eureka, it worked.

Here is an example:

```<code>private Step partitionStep() throws SQLException {
    return stepBuilderFactory.get("example_partitionstep")
            .partitioner(step.getName(), columnRangePartitioner(partitionColumn, tableName))
            .partitionHandler(taskExecutorPartitionHandler(step))
            .build();
}
</code>```

For the step:

```<code>private Step step() throws SQLException {
    return stepBuilderFactory.get("example_step")
            .<>chunk(1000)
            .reader(cursorItemReader(0L, 0L))
            .processor(compositeItemProcessor())
            .writer(itemWriter())
            .build();
}
</code>```

And for the TaskExecutor:

```<code>@Bean
public TaskExecutor taskExecutor() {
    SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();

    taskExecutor.setConcurrencyLimit(6);

    return taskExecutor;
}
</code>```

Body:
I'm relatively new to Spring Batch, but I had similar problem when I first tried writing my own partitioned step.

In my case, the problem was my taskExecutor (which wasn't asynchronous).
I added a @Bean that initialized an asynTaskExecutor and chained that to my partition step. Eureka, it worked.

Here is an example:

private Step partitionStep() throws SQLException {
    return stepBuilderFactory.get("example_partitionstep")
            .partitioner(step.getName(), columnRangePartitioner(partitionColumn, tableName))
            .partitionHandler(taskExecutorPartitionHandler(step))
            .build();
}

For the step:

private Step step() throws SQLException {
    return stepBuilderFactory.get("example_step")
            .<>chunk(1000)
            .reader(cursorItemReader(0L, 0L))
            .processor(compositeItemProcessor())
            .writer(itemWriter())
            .build();
}

And for the TaskExecutor:

@Bean
public TaskExecutor taskExecutor() {
    SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();

    taskExecutor.setConcurrencyLimit(6);

    return taskExecutor;
}


问:
Can Strongloop generate string uids?
I want to stop using autogenerated number ids for my models on Strongloop. Can Strongloop generate string uids like e.g. 067e6162-3b6f-4ae2-a171-2470b63dff00?

答:
You need to modify the .js file along with the .json file.
Based on the logic, you can also add a remote method and generate the uuid from node-uuid module.

I'm assuming a User model here and properties of id, name, age and creating an entry into User model.

User.json

```<code>{
    "name": "User",
    "properties": {
        "id": {
          "type": "string",
          "id": true,
          "defaultFn": "uuid",
          "required": true
        },
        "name": {
          "type": "string",
          "required": true
        },
        "age": {
          "type": "string",
          "required": true
        }
}
</code>```

User.js

```<code>var uuid = require('node-uuid');
module.exports = function(User) {
    var userObj = {};
    userObj.id = uuid();
    userObj.name = 'John';
    userObj.age = 22;
    User.create(userObj, function(err, userInstance){
        if (err) {
            console.log(err);
        } else if (userInstance) {
            console.log(userInstance);
        }
    });
}
</code>```

This will work.

Title: Can Strongloop generate string uids?

Body:
You need to modify the .js file along with the .json file.
Based on the logic, you can also add a remote method and generate the uuid from node-uuid module.

I'm assuming a User model here and properties of id, name, age and creating an entry into User model.

User.json

{
    "name": "User",
    "properties": {
        "id": {
          "type": "string",
          "id": true,
          "defaultFn": "uuid",
          "required": true
        },
        "name": {
          "type": "string",
          "required": true
        },
        "age": {
          "type": "string",
          "required": true
        }
}

User.js

var uuid = require('node-uuid');
module.exports = function(User) {
    var userObj = {};
    userObj.id = uuid();
    userObj.name = 'John';
    userObj.age = 22;
    User.create(userObj, function(err, userInstance){
        if (err) {
            console.log(err);
        } else if (userInstance) {
            console.log(userInstance);
        }
    });
}

This will work.


问:
ReactJS. How to prevent calling render() before Fetch API working in componentWillReceiveProps
I am using Fetch API in componentWillReceiveProps, but i have some problems with asynchronous. I need to prevent re-render before I will get response from my Fetch request. Now everything is working but I render works 3 times.  </p>

答:
Maintain a state variable for that, initially value of that variable will be false, once you get the response properly, change that variable to true. Use this variable to render the component.

Inside render:

```<code>render(){
    if(this.state.dataFetched){
        return (/*return component*/)
    }else{
       return <div>Loading....</div>
    }

}
</code>```

One more thing, instead of making network call in componentWillReceiveProps method, do that in componentDidMount lifecycle mthod.

componentDidMount:

componentDidMount() is invoked immediately after a component is
  mounted. Initialization that requires DOM nodes should go here. If you
  need to load data from a remote endpoint, this is a good place to
  instantiate the network request.

Body:
Maintain a state variable for that, initially value of that variable will be false, once you get the response properly, change that variable to true. Use this variable to render the component.

Inside render:

render(){
    if(this.state.dataFetched){
        return (/*return component*/)
    }else{
       return <div>Loading....</div>
    }

}

One more thing, instead of making network call in componentWillReceiveProps method, do that in componentDidMount lifecycle mthod.

componentDidMount:

componentDidMount() is invoked immediately after a component is
  mounted. Initialization that requires DOM nodes should go here. If you
  need to load data from a remote endpoint, this is a good place to
  instantiate the network request.


问:
SilverStripe - Adding 2 TreeDropdownFields, only one works
I've run into a very bizarre issue while creating 2 TreeDropdownFields for a DataObject. For some reason, only 1 of the 2 TreeDropdownFields render correctly in the SilverStripe admin. The other doesn't render as a TreeDropdownField at all but just as a label:

Here is the code:

```<code>class HomeBanner extends DataObject {

    public static $db = array(
        'SortOrder' => 'Int',
        'Title' => 'Varchar'
    );

    public static $has_one = array(
        'Image' => 'Image',
        'SecondaryImage' => 'Image',
        'FirstLink' => 'SiteTree',
        'SecondLink' => 'SiteTree'
    );

    public function getCMSFields() {
        $fields = parent::getCMSFields();
        $fields->removeFieldFromTab('Root.Main', 'PageID');
        $fields->removeFieldFromTab('Root.Main', 'SortOrder');

        $fields->addFieldToTab('Root.Main', new TreeDropdownField('FirstLinkID', 'First Link', 'SiteTree'));
        $fields->addFieldToTab('Root.Main', new TreeDropdownField('SecondLinkID', 'Second Link', 'SiteTree'));

        return $fields;
    }

    public static $summary_fields = array(
        'ID' => 'ID',
        'Title' => 'Title',
        'Thumbnail' => 'Thumbnail'
    );

    public function getThumbnail() {
        return $this->Image()->CMSThumbnail();
    }
}
</code>```

Here is what I have tried so far:

running dev/build/?flush=true

running ?flush=all and ?flush=1

logging out and logging back in after the dev/build + flushes

logging into the admin in another browser (I typically use Chrome but
logged into the site's admin on FireFox and saw the same problem)

The error logs report nothing -- they're clear

There are no errors in the console for Chrome's dev tools

Adding a third TreeDropdownField will allow the first 2 to render
properly but the third one will just show a label instead of a
TreeDropdownField

This format works, but doesn't save whatever is selected--it clears your choice as soon as you leave the page. Also, it deletes all that was saved already in the admin unless I remove it. I can't make changes or else the items saved get removed.):

$fields->addFieldToTab('Root.Main', new TreeDropdownField('SecondLink', 'Second Link', 'SiteTree', 'ID'));

Does anyone have any ideas as to why this could be happening? It doesn't seem to make sense that you can't have multiple TreeDropdownFields.

答:
Reposting as this turned out to be the answer:

The name “HomeBanner” suggests to me that there should also be a has_one pointing back to HomePage or similar? The cause of this is probably that SilverStripe is automatically trying to set one of the has_one relations to point back to the page that the banner belongs to.

Similar conflicts can also happen when using code like this:

```<code>class Page extends SiteTree {
    private static $has_many = [
        'Banners' => 'Banner'
    ];
}

class Banner extends DataObject {
    private static $has_one = [
        'Page' => 'Page',
        'LinkedPage' => 'Page'
    ];
}
</code>```

As SilverStripe doesn't know whether it should use PageID or LinkedPageID to auto-populate that side of the has_many relation (GridField will try to automatically assign the correct has_one ID).

In these cases, you can use dot-notation to distinguish between them - you’d change it to $has_many = ['Banners' => 'Banner.Page'];. See https://docs.silverstripe.org/en/3/developer_guides/model/relations/#has-many for more info.

Body:
I've run into a very bizarre issue while creating 2 TreeDropdownFields for a DataObject. For some reason, only 1 of the 2 TreeDropdownFields render correctly in the SilverStripe admin. The other doesn't render as a TreeDropdownField at all but just as a label:

Here is the code:

class HomeBanner extends DataObject {

    public static $db = array(
        'SortOrder' => 'Int',
        'Title' => 'Varchar'
    );

    public static $has_one = array(
        'Image' => 'Image',
        'SecondaryImage' => 'Image',
        'FirstLink' => 'SiteTree',
        'SecondLink' => 'SiteTree'
    );

    public function getCMSFields() {
        $fields = parent::getCMSFields();
        $fields->removeFieldFromTab('Root.Main', 'PageID');
        $fields->removeFieldFromTab('Root.Main', 'SortOrder');

        $fields->addFieldToTab('Root.Main', new TreeDropdownField('FirstLinkID', 'First Link', 'SiteTree'));
        $fields->addFieldToTab('Root.Main', new TreeDropdownField('SecondLinkID', 'Second Link', 'SiteTree'));

        return $fields;
    }

    public static $summary_fields = array(
        'ID' => 'ID',
        'Title' => 'Title',
        'Thumbnail' => 'Thumbnail'
    );

    public function getThumbnail() {
        return $this->Image()->CMSThumbnail();
    }
}

Here is what I have tried so far:

running dev/build/?flush=true

running ?flush=all and ?flush=1

logging out and logging back in after the dev/build + flushes

logging into the admin in another browser (I typically use Chrome but
logged into the site's admin on FireFox and saw the same problem)

The error logs report nothing -- they're clear

There are no errors in the console for Chrome's dev tools

Adding a third TreeDropdownField will allow the first 2 to render
properly but the third one will just show a label instead of a
TreeDropdownField

This format works, but doesn't save whatever is selected--it clears your choice as soon as you leave the page. Also, it deletes all that was saved already in the admin unless I remove it. I can't make changes or else the items saved get removed.):

$fields->addFieldToTab('Root.Main', new TreeDropdownField('SecondLink', 'Second Link', 'SiteTree', 'ID'));

Does anyone have any ideas as to why this could be happening? It doesn't seem to make sense that you can't have multiple TreeDropdownFields.

Body:
Reposting as this turned out to be the answer:

The name “HomeBanner” suggests to me that there should also be a has_one pointing back to HomePage or similar? The cause of this is probably that SilverStripe is automatically trying to set one of the has_one relations to point back to the page that the banner belongs to.

Similar conflicts can also happen when using code like this:

class Page extends SiteTree {
    private static $has_many = [
        'Banners' => 'Banner'
    ];
}

class Banner extends DataObject {
    private static $has_one = [
        'Page' => 'Page',
        'LinkedPage' => 'Page'
    ];
}

As SilverStripe doesn't know whether it should use PageID or LinkedPageID to auto-populate that side of the has_many relation (GridField will try to automatically assign the correct has_one ID).

In these cases, you can use dot-notation to distinguish between them - you’d change it to $has_many = ['Banners' => 'Banner.Page'];. See https://docs.silverstripe.org/en/3/developer_guides/model/relations/#has-many for more info.


问:
How can I write special characters in RMarkdown latex documents?
I am trying ot write a paper in RMarkdown pdf. But I dont know how to use special characters like "İ, ı, ğ, ü, ö". Those characters are present in Turkish. I can easily use them in Latex using e.g. \u{g} – ğ, \c{c} – ç, \”{u} – ü, {\i} – ı, etc.

Could you please tell how can I do the same in RMarkdown?

And where can I find some Rmarkdown paper or book templates?

答:
I guess this question per se is obsolete. As of now (rmarkdown V1.4 / knitr V1.15.1), knitr automatically follows the advice of this question and includes

```<code>\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
</code>```

in the preamble to LaTeX output (caveat: of course this means that your document editor will have to be using UTF-8, but e.g., RStudio does that by default).

Then this works as expected:

```<code>---
title: "Test"
output: pdf_document
---

Here are some special characters: İ ı Ş Ğ ş ğ ö ü
</code>```

This is not a panacea, as many scripts still require more tinkering (I tried Korean, Chinese, and Japanese). See here for where to start on bolstering the preamble in case you need more multifarious fonts.

Body:
I guess this question per se is obsolete. As of now (rmarkdown V1.4 / knitr V1.15.1), knitr automatically follows the advice of this question and includes

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

in the preamble to LaTeX output (caveat: of course this means that your document editor will have to be using UTF-8, but e.g., RStudio does that by default).

Then this works as expected:

---
title: "Test"
output: pdf_document
---

Here are some special characters: İ ı Ş Ğ ş ğ ö ü

This is not a panacea, as many scripts still require more tinkering (I tried Korean, Chinese, and Japanese). See here for where to start on bolstering the preamble in case you need more multifarious fonts.

ContentLicense: CC BY-SA 4.0


问:
Extreme case of "Error retrieving parent for item"
My Xamarin Android project doesn't compile anymore, with a couple error messages saying

Error APT0000: Error retrieving parent for item: No resource found that matches the given name 'Widget.Design.TabLayout'

Other errors that were thrown previously were in the same style, but said

No resource found that matches the given name (at 'textColor' with value '@color/md_white_1000')

I am aware that this is a very common Xamarin bug that is normally fixed by cleaning and rebuilding or, in rare cases, by clearing all packages and package caches so that they are downloaded again. However, this did not fix my error. I also completely reinstalled Xamarin and Visual Studio, but the error persists. At this point, i don't really know what to do except completely reformat my Mac.

Are there any trouble shooting steps I missed? Is this a bug that is only present in some version so that I need to downgrade? Please help, as I haven't been able to compile my code now for two days.

答:
The log is saying that the app could not find certain resources, like TabLayout and @color/md_white_1000.

Did you install the NuGet packages related to Android AppCompat libraries? In NuGet Package Manager, search for AppCompat libraries. For example:

https://www.nuget.org/packages/Xamarin.Android.Support.v7.AppCompat

Those are necessary to find AppCompat resources and themes.


问:
sorting objects with multiple conditions
I'm currently trying to sort an array of objects that is being returned in my reducer. I want to sort the apps based off of their name that is being returned, and where there are still currently some names that are null I want to list the null names at the end. Currently when I try to add an additional condition I am getting an error Cannot read property 'toLowerCase' of null which i'm expecting null items just need to move them to the end.

```<code>// Actions
export const FETCH_MYAPPS_PENDING = 'widgets/apps/FETCH_PENDING';
export const FETCH_MYAPPS_FULFILLED = 'widgets/apps/FETCH_FULFILLED';

// Reducer
const appsSort = (a, b) => {
  if (a.name != null && b.name != null) {
   if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
   if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
  }
  return 0;
};

export default function reducer(state = { data: [], pending: false }, action) {
switch (action.type) {
case FETCH_MYAPPS_FULFILLED:
  return {
    data: action.apps.sort(appsSort),
    pending: false,
    retrievedAt: Date.now(),
  };
case FETCH_MYAPPS_PENDING:
  return {
    ...state,
    pending: true,
  };
default:
  return state;
 }
}
</code>```

答:
That error suggests that a.name or b.name does not resolve to an object with the method toLowerCase on it.

You could ensure that the values for both are strings before trying to call toLowerCase on them. Here's one way of checking if the value is of type 'string'

```<code>typeof a.name === 'string'
</code>```

Body:
I'm currently trying to sort an array of objects that is being returned in my reducer. I want to sort the apps based off of their name that is being returned, and where there are still currently some names that are null I want to list the null names at the end. Currently when I try to add an additional condition I am getting an error Cannot read property 'toLowerCase' of null which i'm expecting null items just need to move them to the end.

// Actions
export const FETCH_MYAPPS_PENDING = 'widgets/apps/FETCH_PENDING';
export const FETCH_MYAPPS_FULFILLED = 'widgets/apps/FETCH_FULFILLED';

// Reducer
const appsSort = (a, b) => {
  if (a.name != null && b.name != null) {
   if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
   if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
  }
  return 0;
};

export default function reducer(state = { data: [], pending: false }, action) {
switch (action.type) {
case FETCH_MYAPPS_FULFILLED:
  return {
    data: action.apps.sort(appsSort),
    pending: false,
    retrievedAt: Date.now(),
  };
case FETCH_MYAPPS_PENDING:
  return {
    ...state,
    pending: true,
  };
default:
  return state;
 }
}

Body:
That error suggests that a.name or b.name does not resolve to an object with the method toLowerCase on it.

You could ensure that the values for both are strings before trying to call toLowerCase on them. Here's one way of checking if the value is of type 'string'

typeof a.name === 'string'


问:
How to add an expiry time for cached Angular2 http response using rxjs observables
I am using rxjs publishReplay(1) and refCount to cache http response. What's the best way to put an expiry time for the caching. I am getting a token using http call which expires every 1 hour.

```<code>@Injectable()
export class SearchService{
public url: string;
private token:Observable<any> = null;

constructor(private _http:Http){

}

getSecurityToken(url:string): any {

    headers.append("securitycode","*******");

    if(!this.token){
        this.token = this._http.post(url,{headers:headers})
            .map(this.extractData)
            .publishReplay(1)
            .refCount()
            .catch(this.handleError);
    }
    return this.token;
}

private extractData(res: Response) {
    console.log(res.status);
    if(res.status == 204) {
        return [];
    }
    else{
        let body = res.json();
        return body;
    }
}

private handleError (error: any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
   console.error(errMsg); // log to console instead
   return Observable.throw(errMsg);
}
</code>```

答:
The publishReplay internally uses the ReplaySubject that takes as the second argument the time window which defines how long is each cached item valid.

So in your case it could be for example:

```<code>...
.publishReplay(1, 60 * 1000)
</code>```

See: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-publishReplay

Body:
I am using rxjs publishReplay(1) and refCount to cache http response. What's the best way to put an expiry time for the caching. I am getting a token using http call which expires every 1 hour.

@Injectable()
export class SearchService{
public url: string;
private token:Observable<any> = null;

constructor(private _http:Http){

}

getSecurityToken(url:string): any {

    headers.append("securitycode","*******");

    if(!this.token){
        this.token = this._http.post(url,{headers:headers})
            .map(this.extractData)
            .publishReplay(1)
            .refCount()
            .catch(this.handleError);
    }
    return this.token;
}

private extractData(res: Response) {
    console.log(res.status);
    if(res.status == 204) {
        return [];
    }
    else{
        let body = res.json();
        return body;
    }
}

private handleError (error: any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
   console.error(errMsg); // log to console instead
   return Observable.throw(errMsg);
}

Body:
The publishReplay internally uses the ReplaySubject that takes as the second argument the time window which defines how long is each cached item valid.

So in your case it could be for example:

...
.publishReplay(1, 60 * 1000)

See: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-publishReplay


问:
TypeError: "unsupported operand type(s) for -: 'Timestamp' and 'str'" pandas
I am working on a project and so far my code looks like this:

```<code>def vacation_date(row):
if pd.isnull(row['vacation_date']) == False :
    return float((row['vacation_date'] - row['purchased_trip_date']).days)
else:
    pass
preprocessed_data['vacation_date'] = data.apply(lambda row:
vacation_date(row), axis=1)
</code>```

it is returning: TypeError: ("unsupported operand type(s) for -: 'Timestamp' and 'str'", 'occurred at index 3')

I am not sure what I need to do to fix this, any suggestions are appreciated, thanks!

答: how sure are you that every item in data['purchased_trip_date'] and data['vacation_date'] are properly formatted dates? I suspect that one or the  other is a string that can't be automagically transformed to a date. The error occurs when Python tries to subtract a timestamp from a string. You should validate the data in those two fields.

Body:
I am working on a project and so far my code looks like this:

def vacation_date(row):
if pd.isnull(row['vacation_date']) == False :
    return float((row['vacation_date'] - row['purchased_trip_date']).days)
else:
    pass
preprocessed_data['vacation_date'] = data.apply(lambda row:
vacation_date(row), axis=1)

it is returning: TypeError: ("unsupported operand type(s) for -: 'Timestamp' and 'str'", 'occurred at index 3')

I am not sure what I need to do to fix this, any suggestions are appreciated, thanks!


问:
Main class instance for all subclasses
I got three classes: Bank, account and Coin. I want the class Bank to have a default coin variable , which I pass on to its constructor. So I extended account to Bank, this would mean that I can access the default coin variable through the method getmainCoin() via the account class. For some reason I'm getting this error when trying that:

Error:(12, 32) java: constructor bank in class com.company.bank cannot be applied to given types;
    required: com.company.Coin
    found: no arguments
    reason: actual and formal argument lists differ in length

```<code>// Instantiations
Coin dollars = new Coin("Dollar", "$");;
bank SomeBank = new bank(dollars);
Person john = new Person("John Doe", 20, dollars, new account(9058));
System.out.println(john.checkbalance());

public class bank {
  public String name;
  private int coinsheld;
  private Coin maincoin;

  public bank(Coin maincoin){
      this.maincoin = maincoin;
  }

  public Coin getmainCoin(){
      return this.maincoin;
  }

}

public class account extends bank {
  private int balance;
  private static int accounts;
  private int accnumber;
  private Coin coin;

  public account(int balance){
      this.balance = balance;
      this.accounts += 1;
      this.accnumber = accounts;
      this.coin = getmainCoin();
  }
}

public class Coin {
  public static int total;
  private String name;
  private String sign;
  private int id;

  public Coin(String name, String sign){
      this.name = name;
      this.sign = sign;
      this.id = total + 1;
  }

  public int getID(){
      return this.id;
  }
}
</code>```

答:
Your account class constructor which is public account(int balance) implicitly calls the parent class default constructor i.e., super();, but you did not provide any default constructor in your bank class.

So, you can solve the issue by creating a default constructor in your bank class as shown below:

```<code>public class bank {

    public bank() {
    }

   //your code here
}
</code>```

However, your class relationships are not correct i.e., when you say Account extends Bank in java, it means that Account IS-A Bank, which doesn't seem right.

Also, you are NOT following java naming conventions for Class, method, variable names i.e., Class/Interface names starts with Upper case where as method/variable names should be lower case.

Title: Main class instance for all subclasses

Body:
I got three classes: Bank, account and Coin. I want the class Bank to have a default coin variable , which I pass on to its constructor. So I extended account to Bank, this would mean that I can access the default coin variable through the method getmainCoin() via the account class. For some reason I'm getting this error when trying that:

Error:(12, 32) java: constructor bank in class com.company.bank cannot be applied to given types;
    required: com.company.Coin
    found: no arguments
    reason: actual and formal argument lists differ in length

// Instantiations
Coin dollars = new Coin("Dollar", "$");;
bank SomeBank = new bank(dollars);
Person john = new Person("John Doe", 20, dollars, new account(9058));
System.out.println(john.checkbalance());

public class bank {
  public String name;
  private int coinsheld;
  private Coin maincoin;

  public bank(Coin maincoin){
      this.maincoin = maincoin;
  }

  public Coin getmainCoin(){
      return this.maincoin;
  }

}

public class account extends bank {
  private int balance;
  private static int accounts;
  private int accnumber;
  private Coin coin;

  public account(int balance){
      this.balance = balance;
      this.accounts += 1;
      this.accnumber = accounts;
      this.coin = getmainCoin();
  }
}

public class Coin {
  public static int total;
  private String name;
  private String sign;
  private int id;

  public Coin(String name, String sign){
      this.name = name;
      this.sign = sign;
      this.id = total + 1;
  }

  public int getID(){
      return this.id;
  }
}

Body:
Your account class constructor which is public account(int balance) implicitly calls the parent class default constructor i.e., super();, but you did not provide any default constructor in your bank class.

So, you can solve the issue by creating a default constructor in your bank class as shown below:

public class bank {

    public bank() {
    }

   //your code here
}

However, your class relationships are not correct i.e., when you say Account extends Bank in java, it means that Account IS-A Bank, which doesn't seem right.

Also, you are NOT following java naming conventions for Class, method, variable names i.e., Class/Interface names starts with Upper case where as method/variable names should be lower case.


问:
Make an Image with Radio Buttons a Block (CSS, HTML)
I want to make an image that has radio buttons responds like a block. When i change the scale of the window i want that image with the radio buttons change like a block without losing the positions of the radio buttons.</p>

```<code>.island{

 background-image: url("nhsia.png");
 display:block;
 position: relative;
 width: 100%;
 height: 550px;
 background-image: url("nhsia.png");
 background-repeat: no-repeat;
 background-size: contain;
 }

 #radio1 {
 position:absolute;
 left:7%;
 top:17.5%;
 }

 #radio2 {
 position:absolute;
 left:15.5%;
 top:15%;
 }

HTML

<div class="island">
<form action="">
<input type="radio" name="radio" id="radio1"/><br/>
<input type="radio" name="radio" id="radio2"/><br/>
<input type="radio" name="radio" id="radio3"/><br/>
<input type="radio" name="radio" id="radio4"/><br/>
<input type="radio" name="radio" id="radio5"/><br/>
<input type="radio" name="radio" id="radio6"/><br/>
<input type="radio" name="radio" id="radio7"/><br/>
<input type="radio" name="radio" id="radio8"/><br/>
</form>
</div>
</code>```

答:
The reason why the radio buttons are moving is because you're using relative values on the position of the radio buttons so when the parent element's size changes, the position changes as well.

If you don't want them to move around you should use exact values like px rather than relative values (as illustrated in this Fiddle).

CSS

```<code>.island {
  display: block;
  position: relative;
  width: 100%;
  height: 550px;
  background-image: url("http://placehold.it/650x550");
  background-repeat: no-repeat;
  background-size: contain;
}

#radio1 {
  position: absolute;
  left: 40px;
  top: 10px;
}

#radio2 {
  position: absolute;
  left: 90px;
  top: 50px;
}
</code>```

HTML

```<code><div class="island">
  <form action="">
    <input type="radio" name="radio" id="radio1" />
    <br/>
    <input type="radio" name="radio" id="radio2" />
    <br/>
    <input type="radio" name="radio" id="radio3" />
    <br/>
    <input type="radio" name="radio" id="radio4" />
    <br/>
    <input type="radio" name="radio" id="radio5" />
    <br/>
    <input type="radio" name="radio" id="radio6" />
    <br/>
    <input type="radio" name="radio" id="radio7" />
    <br/>
    <input type="radio" name="radio" id="radio8" />
    <br/>
  </form>
</div>
</code>```

Additional Notes

So it looks like you're doing this for a map. I'd suggest that you make the image a fixed size as well otherwise the map would shrink and grow but your radio buttons won't adapt to the new position.

Body:
I want to make an image that has radio buttons responds like a block. When i change the scale of the window i want that image with the radio buttons change like a block without losing the positions of the radio buttons.

.island{

 background-image: url("nhsia.png");
 display:block;
 position: relative;
 width: 100%;
 height: 550px;
 background-image: url("nhsia.png");
 background-repeat: no-repeat;
 background-size: contain;
 }

 #radio1 {
 position:absolute;
 left:7%;
 top:17.5%;
 }

 #radio2 {
 position:absolute;
 left:15.5%;
 top:15%;
 }

HTML

<form action="">
<input type="radio" name="radio" id="radio1"/>

<input type="radio" name="radio" id="radio2"/>

<input type="radio" name="radio" id="radio3"/>

<input type="radio" name="radio" id="radio4"/>

<input type="radio" name="radio" id="radio5"/>

<input type="radio" name="radio" id="radio6"/>

<input type="radio" name="radio" id="radio7"/>

<input type="radio" name="radio" id="radio8"/>

</form>

Body:
The reason why the radio buttons are moving is because you're using relative values on the position of the radio buttons so when the parent element's size changes, the position changes as well.

If you don't want them to move around you should use exact values like px rather than relative values (as illustrated in this Fiddle).

CSS

.island {
  display: block;
  position: relative;
  width: 100%;
  height: 550px;
  background-image: url("http://placehold.it/650x550");
  background-repeat: no-repeat;
  background-size: contain;
}

#radio1 {
  position: absolute;
  left: 40px;
  top: 10px;
}

#radio2 {
  position: absolute;
  left: 90px;
  top: 50px;
}

HTML

<div class="island">
  <form action="">
    <input type="radio" name="radio" id="radio1" />
    <br/>
    <input type="radio" name="radio" id="radio2" />
    <br/>
    <input type="radio" name="radio" id="radio3" />
    <br/>
    <input type="radio" name="radio" id="radio4" />
    <br/>
    <input type="radio" name="radio" id="radio5" />
    <br/>
    <input type="radio" name="radio" id="radio6" />
    <br/>
    <input type="radio" name="radio" id="radio7" />
    <br/>
    <input type="radio" name="radio" id="radio8" />
    <br/>
  </form>
</div>

Additional Notes

So it looks like you're doing this for a map. I'd suggest that you make the image a fixed size as well otherwise the map would shrink and grow but your radio buttons won't adapt to the new position.


答: The error message is one of the clearest I've ever seen in computing - it's telling you that you're trying to subtract a string from a Timestamp. Since what you're subtracting is row['purchased_trip_date'], it means this is a string. Convert it to another Timestamp first.

Title: TypeError: "unsupported operand type(s) for -: 'Timestamp' and 'str'" pandas


问:
Inconsistence between SVG file and Android Studio vector asset
I'm using the Sketch software to build svg images to use in my android project. I'm having an issue with this one:

As you can see, the picture is ok and I checked the previews with Chrome and the Macos preview.

When I try to import the SVG in Android Studio the import preview is the following:

The subtracted circles inside the filled ones are gone. The import log messages me this:

```<code>In ic_percent.svg:
WARNING@ line 10 We don't scale the stroke width!
WARNING@ line 11 We don't scale the stroke width!
WARNING@ line 12 We don't scale the stroke width!
WARNING@ line 13 We don't scale the stroke width!
</code>```

Does anyone know what is happening with my import?

答:
Here's how:

Open your .svg in sketch

Select that missing Circle in Page List. In my case, it's looks like this.

Click Fills (Gear shaped icon) and change Even-Odd to Non-Zero

Open Layer menu -> Path -> Reverse Order

Export the shape back to .svg format

Convert that .svg to Vector Drawable (from Android Studio or 3rd party tools)

That's it! Credit to @dineshbob medium blog

Body:
I'm using the Sketch software to build svg images to use in my android project. I'm having an issue with this one:

As you can see, the picture is ok and I checked the previews with Chrome and the Macos preview.

When I try to import the SVG in Android Studio the import preview is the following:

The subtracted circles inside the filled ones are gone. The import log messages me this:

In ic_percent.svg:
WARNING@ line 10 We don't scale the stroke width!
WARNING@ line 11 We don't scale the stroke width!
WARNING@ line 12 We don't scale the stroke width!
WARNING@ line 13 We don't scale the stroke width!

Does anyone know what is happening with my import?


问:
ION template banner positioning
Using https://templated.co/ion

I’m having trouble re-positioning the banner a little lower to allow for use of a logo image at top left instead of  text. When I load the page with the new header height, it briefly flashes the correct height white background, but the banner doesn't move down and the page reverts to original positioning, leaving the logo overhanging the banner image, even though I replaced some inherits and increased height of nav.

Any suggestions appreciated.

答:
Most probably, this is what you're looking for (adjust to your needs - 5em is demonstrative):

#header {
  height: 5em;
  line-height: 5em;
}
#skel-layers-wrapper {
  padding-top: 5em;
}
```

Please note this has to be loaded after style.css (or placed at the very end of it, if you place your own mods inside this file). Alternatively (but not recommended), you could just modify the existing values on lines 880 and 884.

Typically, the best way to go when making customizations is to just place them in a separate file and load it after the original resource, which should remain untouched.

This provides your project with better code control, increased maintain-ability & upgrade-ability. Placing the custom file after the original one allows you to apply changes without having to increase the specificity of the original selectors.

Title: ION template banner positioning

Body:
Most probably, this is what you're looking for (adjust to your needs - 5em is demonstrative):

#header {
  height: 5em;
  line-height: 5em;
}
#skel-layers-wrapper {
  padding-top: 5em;
}

Please note this has to be loaded after style.css (or placed at the very end of it, if you place your own mods inside this file). Alternatively (but not recommended), you could just modify the existing values on lines 880 and 884.

Typically, the best way to go when making customizations is to just place them in a separate file and load it after the original resource, which should remain untouched.

This provides your project with better code control, increased maintain-ability & upgrade-ability. Placing the custom file after the original one allows you to apply changes without having to increase the specificity of the original selectors.


问:
Brace placement after init list in C++
For anyone who places braces thus:

```<code>void f() {
    stuff();
}
</code>```

How do you prefer to place braces after long initializer lists?

The same way?

```<code>Object::Object()
    : foo(1)
    , bar(2) {
    stuff();
}
</code>```

Or make an exception so you actually see where the init list ends?

```<code>Object::Object()
    : foo(1)
    , bar(2)
{
    stuff();
}
</code>```

Or leave a blank line?

```<code>Object::Object()
    : foo(1)
    , bar(2) {

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

Or maybe make a weird hybrid?

```<code>Object::Object()
    : foo(1)
    , bar(2)
    {
    stuff();
}
</code>```

Or abuse indentation

```<code>Object::Object()
: foo(1)
, bar(2) {
    stuff();
}

Object::Object() : foo(1)
                            , bar(2) {
    stuff();
}
</code>```

In this small example all are pretty but crank a dozen initializers and a moderately long function body and this quickly changes.

答: I would guess that most developers like to remain consistent with their bracket formatting with how they are using it in the rest of their code. It's hard enough to read a bracket format that is not your own style. Trying to decipher a mixed format would make your program even more unreadable to someone who is not familiar to your code.  </p>

OwnerDisplayName: Iraimbilanja

LastEditorDisplayName: Iraimbilanja

Title: Brace placement after init list in C++

Body:
For anyone who places braces thus:

void f() {
    stuff();
}

How do you prefer to place braces after long initializer lists?

The same way?

Object::Object()
    : foo(1)
    , bar(2) {
    stuff();
}

Or make an exception so you actually see where the init list ends?

Object::Object()
    : foo(1)
    , bar(2)
{
    stuff();
}

Or leave a blank line?

Object::Object()
    : foo(1)
    , bar(2) {

    stuff();
}

Or maybe make a weird hybrid?

Object::Object()
    : foo(1)
    , bar(2)
    {
    stuff();
}

Or abuse indentation

Object::Object()
: foo(1)
, bar(2) {
    stuff();
}

Object::Object() : foo(1)
                            , bar(2) {
    stuff();
}

In this small example all are pretty but crank a dozen initializers and a moderately long function body and this quickly changes.

OwnerDisplayName: Matt Schwartz


问:
Is there a syntax for conditional template interpolation?
I have an angular (2.4.9) template with the following element:

```<code><div *ngIf="a || b || c || d || e">Remaining</div>
</code>```

I'm now faced with the need to change that hitherto static "Remaining" text based on another condition:

```<code><div *ngIf="a || b || c || d || e || Z != 'draft'">Initial</div>
<div *ngIf="a || b || c || d || e || Z == 'draft'">Remaining</div>
</code>```

The *ngIf is already loaded, and I'd like to prevent having to duplicate it, as I did in the example above, just to add that one extra condition.

I would also like to avoid doing this:

```<code><div *ngIf="a || b || c || d || e">
    <div *ngIf="Z != 'draft'">Initial</div>
    <div *ngIf="Z == 'draft'">Remaining</div>
</div>
</code>```

...because this changes the structure of the page and thus the style rules.

So, rather than introduce a new element within the div with its own *ngIf, which would cause us to add style rules, I was looking for something like a conditional interpolation syntax, such that I could write

```<code><div *ngIf="many || conditions">{{ status === "DRAFT" ? 'Initial' : 'Remaining' }}</div>
</code>```

in a similar way that you can do {{ 1 + 1 }}, which is also an expression which returns a value, so seems at least conceptually similar.

My attempt above causes the template parser to explode with an unmatched tag somewhere seemingly unrelated to this template, so what it's actually doing is not immediately apparent, but it's obviously incorrect.

答:
In Angular4 you can use else

```<code><template #other>
  <div>Remaining</div>
</template>

<div *ngIf="a || b || c || d || e || Z != 'draft'; else other">Initial</div>
</code>```

There is nothing for Angular2, except moving the expression to a getter or method and use that getter in *ngIf="..."

Body:
I have an angular (2.4.9) template with the following element:

Remaining

I'm now faced with the need to change that hitherto static "Remaining" text based on another condition:

Initial

Remaining

The *ngIf is already loaded, and I'd like to prevent having to duplicate it, as I did in the example above, just to add that one extra condition.

I would also like to avoid doing this:

Initial

Remaining

...because this changes the structure of the page and thus the style rules.

So, rather than introduce a new element within the div with its own *ngIf, which would cause us to add style rules, I was looking for something like a conditional interpolation syntax, such that I could write

{{ status === "DRAFT" ? 'Initial' : 'Remaining' }}

in a similar way that you can do {{ 1 + 1 }}, which is also an expression which returns a value, so seems at least conceptually similar.

My attempt above causes the template parser to explode with an unmatched tag somewhere seemingly unrelated to this template, so what it's actually doing is not immediately apparent, but it's obviously incorrect.

Body:
In Angular4 you can use else

<template #other>
  <div>Remaining</div>
</template>

<div *ngIf="a || b || c || d || e || Z != 'draft'; else other">Initial</div>

There is nothing for Angular2, except moving the expression to a getter or method and use that getter in *ngIf="..."


问:
array getting pushed elements by ngdocheck multiple times in angular 2
I am trying to update my empty array 'filelistArray' when content available on 'this.uploaCopy.queue' array, this is happening at multiple times, i mean, the same array getting executed multiple times and 'filelistArray' contains multiple duplicate items.

But, i want to update the array where there is content on 'this.uploaCopy.queue', and only available content, there should not be any duplicate.

Could anyone please help on this?

```<code>ngDoCheck() {
  if (this.uploadCopy.queue !== undefined && this.uploadCopy.queue.length > 0) {

    for (let entryitemlist of this.uploadCopy.queue) {

      this.filelistArray.push(entryitemlist.file.name);

    }

  }

  if (this.uploadCopy.queue == undefined && this.uploadCopy.queue.length == 0) {
   this.filelistArray.length = 0;
  }

}
</code>```

答:
Then you can use ngonchanges simple change and check if its current value is there and do the rest. Refer angular docs for ngonchanges. This can help remove duplicates in an Array.

this.newArr = Array.from(new Set(this.oldArr.map((itemInArray) => itemInArray)))

Body:
I am trying to update my empty array 'filelistArray' when content available on 'this.uploaCopy.queue' array, this is happening at multiple times, i mean, the same array getting executed multiple times and 'filelistArray' contains multiple duplicate items.

But, i want to update the array where there is content on 'this.uploaCopy.queue', and only available content, there should not be any duplicate.

Could anyone please help on this?

ngDoCheck() {
  if (this.uploadCopy.queue !== undefined && this.uploadCopy.queue.length > 0) {

    for (let entryitemlist of this.uploadCopy.queue) {

      this.filelistArray.push(entryitemlist.file.name);

    }

  }

  if (this.uploadCopy.queue == undefined && this.uploadCopy.queue.length == 0) {
   this.filelistArray.length = 0;
  }

}


问:
Android device monitor emulator 5554 - offline
Good afternoon! Not so long ago I began to develop an application for android. The application creates a database and write data through want Android Device Monitor pull database and view, but when you start, emulator-5554 switches to offline mode. I tried to solve the problem using the adb kill-server and adb start-server, to no avail. Prompt how to solve the problem? Used to develop Android Studio 2.3.</p>

答:
You can start the Android Device Manager (ADM) by the command line script.

Go to the Android SDK tools folder %userprofile%\AppData\Local\Android\sdk\tools

Run monitor.bat

You can ignore its ddms error message when ADM starts. It does not affect to access the emulator.

I created a shortcut of monitor.bat on my Desktop. So I just double click the shortcut to start it when I need to run it.


问:
Scrollview not scrolling
I'm using a scroll view which is having only one child linearlayout.
Linearlayout contains listview and some other items also, but only listview is scrolling. what should i do ?
Here is my layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/beco_white"
android:orientation="vertical">

<include layout="@layout/toolbar" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

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

        <ViewSwitcher
            android:id="@+id/view_switcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/button_sign_in"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/dp20"
                    android:background="@drawable/dark_blue_round_corner"
                    android:fontFamily="sans-serif-normal"
                    android:text="Login to beCo"
                    android:textAllCaps="false"
                    android:textColor="@android:color/white"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_sign_up"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="@dimen/dp20"
                    android:background="@drawable/customborder"
                    android:fontFamily="sans-serif-normal"
                    android:text="Create New Account"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent"
                    android:textSize="14sp" />

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white">

                <com.facebook.drawee.view.SimpleDraweeView
                    android:id="@+id/image_profile"
                    android:layout_width="@dimen/dp88"
                    android:layout_height="@dimen/dp88"
                    android:layout_gravity="left"
                    android:layout_marginBottom="@dimen/dp10"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_marginTop="@dimen/dp10"
                    fresco:actualImageScaleType="centerCrop"
                    fresco:placeholderImage="@drawable/no_profile_pic"
                    fresco:roundAsCircle="true"
                    fresco:roundingBorderColor="@color/white"
                    fresco:roundingBorderWidth="@dimen/dp2" />

                <TextView
                    android:id="@+id/user_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="John Doe"
                    android:textColor="@android:color/black"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/user_name"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toEndOf="@+id/image_profile"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="johndoe@mail.com"
                    android:textColor="@android:color/black"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_edit"
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignTop="@+id/image_profile"
                    android:background="@drawable/customborder"
                    android:text="Edit Profile"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent" />

            </RelativeLayout>

        </ViewSwitcher>

        <View
            android:layout_width="wrap_content"
            android:layout_height="1dp"
            android:background="@color/grey_200" />

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>
</ScrollView>
</LinearLayout>
</code>```

Any one please help me?

答:
Never put A ListView inside a ScrollView. It is a bad practice and it defeats the purpose of having a ListView. Who wants two scrollable areas on a screen anyway?

Instead add a header or footer view on your listView depending on what you need.

Title: Scrollview not scrolling

Body:
I'm using a scroll view which is having only one child linearlayout.
Linearlayout contains listview and some other items also, but only listview is scrolling. what should i do ?
Here is my layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/beco_white"
android:orientation="vertical">

<include layout="@layout/toolbar" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

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

        <ViewSwitcher
            android:id="@+id/view_switcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/button_sign_in"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/dp20"
                    android:background="@drawable/dark_blue_round_corner"
                    android:fontFamily="sans-serif-normal"
                    android:text="Login to beCo"
                    android:textAllCaps="false"
                    android:textColor="@android:color/white"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_sign_up"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="@dimen/dp20"
                    android:background="@drawable/customborder"
                    android:fontFamily="sans-serif-normal"
                    android:text="Create New Account"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent"
                    android:textSize="14sp" />

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white">

                <com.facebook.drawee.view.SimpleDraweeView
                    android:id="@+id/image_profile"
                    android:layout_width="@dimen/dp88"
                    android:layout_height="@dimen/dp88"
                    android:layout_gravity="left"
                    android:layout_marginBottom="@dimen/dp10"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_marginTop="@dimen/dp10"
                    fresco:actualImageScaleType="centerCrop"
                    fresco:placeholderImage="@drawable/no_profile_pic"
                    fresco:roundAsCircle="true"
                    fresco:roundingBorderColor="@color/white"
                    fresco:roundingBorderWidth="@dimen/dp2" />

                <TextView
                    android:id="@+id/user_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="John Doe"
                    android:textColor="@android:color/black"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/user_name"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toEndOf="@+id/image_profile"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="johndoe@mail.com"
                    android:textColor="@android:color/black"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_edit"
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignTop="@+id/image_profile"
                    android:background="@drawable/customborder"
                    android:text="Edit Profile"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent" />

            </RelativeLayout>

        </ViewSwitcher>

        <View
            android:layout_width="wrap_content"
            android:layout_height="1dp"
            android:background="@color/grey_200" />

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>
</ScrollView>
</LinearLayout>

Any one please help me?


答: I had another error in my template. My example code would have worked just fine, as RemyaJ illustrated.</p>

Title: Is there a syntax for conditional template interpolation?