问:
Recycle View with card layout always same size
I am implementing a recycle view with a card layout to do something like this:

the thing is, that I can't get a full width/height card layout, I just keep getting a low card layout like this:

how can I adapt my example to get the result I desire?

I already have the adapter with all the info to stick it inside the card view, but somehow the layout is always that strange :S.

Here is the XML of my mainLayout:

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout 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:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

        <include
            layout="@layout/app_bar_plant_feed"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header_plant_feed"
            app:menu="@menu/activity_plant_feed_drawer"
            android:background="@color/white"/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycleView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </android.support.v4.widget.DrawerLayout>

**and the row for the card layout:**

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:elevation="3dp"
        card_view:cardCornerRadius="@dimen/card_specie_radius">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <ImageView
                android:id="@+id/userIcon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_toEndOf="@+id/reportImg"
                android:src="@drawable/ic_user" />

            <TextView
                android:id="@+id/Avaliation"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/plantName"
                android:layout_marginStart="92dp"
                android:layout_marginTop="15dp"
                android:layout_toEndOf="@+id/dateTxt"
                android:text="Avalie a fotografia" />

            <TextView
                android:id="@+id/dateTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentEnd="true"
                android:layout_marginEnd="29dp"
                android:text="TextView" />

            <ImageView
                android:id="@+id/reportImg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/color_cursor_white" />

            <ImageView
                android:id="@+id/plantPhoto"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginRight="16dp" />

            <TextView
                android:id="@+id/plantName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/plantPhoto"
                android:textColor="@color/nephritis"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginStart="11dp"
                android:layout_toEndOf="@+id/userIcon" />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

    </LinearLayout>
</code>```

activity code

```<code>public class PlantFeed extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,PlantFeedAdapter.OnItemClickListener {

    //initialize fields

    String token;

    ArrayList<PlantPhotoUser> photos = new ArrayList<>();

    VolleyService mVolleyService;
    IResult mResultCallback = null;
    final String GETREQUEST = "GETCALL";

    final String URL = "http://10.0.2.2:3000/fotos";

    String date;
    String lat;
    String lon;
    String alt;

    PlantFeedAdapter plantFeedAdapter;
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plant_feed);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        recyclerView = (RecyclerView)findViewById(R.id.recycleView);
        recyclerView.setHasFixedSize(true);

        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),5);
        recyclerView.setLayoutManager(layoutManager);
        plantFeedAdapter = new PlantFeedAdapter(getApplicationContext(), photos,PlantFeed.this);
        recyclerView.setAdapter(plantFeedAdapter);

        token = checkForToken();

        initVolleyCallback();

        mVolleyService = new VolleyService(mResultCallback,this);

        mVolleyService.getDataVolley(GETREQUEST,URL,token);

    }

    void initVolleyCallback(){
        mResultCallback = new IResult() {
            @Override
            public void notifySuccess(String requestType,JSONObject response) {
                Log.d("HELLL","hi1");
            }

            @Override
            public void notifySuccess(String requestType, JSONArray response) {
                PlantPhotoUser plantPhotoUser;
                Log.d("HELLLL","hi");
                for (int i=0; i < response.length(); i++) {
                    try {
                        JSONObject object = response.getJSONObject(i);
                        Log.d("objeto",object.toString());

                        int userId = object.getInt("userId");
                        Log.d("objeto",String.valueOf(userId));
                        String username = object.getJSONObject("user").getString("username");
                        Log.d("objeto",String.valueOf(username));
                        int plantId = object.getInt("plantId");
                        Log.d("objeto",String.valueOf(plantId));
                        String specie = object.getJSONObject("plant").getString("specie");
                        Log.d("objeto",String.valueOf(specie));

                        String path = object.getString("image");
                        Log.d("objeto",String.valueOf(path));
                        int fotoId = object.getInt("id");

                        if(object.getString("date") != null){
                            date = object.getString("date");
                        }

                        if(object.getString("lat") != null){
                            lat = object.getString("lat");
                        }

                        if(object.getString("lon") != null){
                            lon = object.getString("lon");
                        }

                        if(object.getString("altitude") != null){
                            alt = object.getString("altitude");
                        }

                        plantPhotoUser = new PlantPhotoUser(fotoId,plantId,userId,path,specie,date,lat,lon,alt,username);
                        photos.add(plantPhotoUser);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                plantFeedAdapter.notifyDataSetChanged();

            }

            @Override
            public void notifyError(String requestType,VolleyError error) {
                Log.d("FAIL",error.toString());
            }
        };
    }

    public String checkForToken() {
        SharedPreferences sharedPref = getSharedPreferences("user", MODE_PRIVATE);
        String tokenKey = getResources().getString(R.string.token);
        String token = sharedPref.getString(getString(R.string.token), tokenKey); // take the token
        return token;
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.plant_feed, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onRowClick(int position, String name, int id, View view) {

    }
}
</code>```

any help, please?

Thank you

答:
1. You are using GridLayoutManager for your RecyclerView with span count 5 that's why your CardView uses 1/5 spaces of total screen-width.

Use LinearLayoutManager to show as full-width vertical list:

```<code>recyclerView.setLayoutManager(new LinearLayoutManager(this));
</code>```

Instead of:

```<code>RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 5);
recyclerView.setLayoutManager(layoutManager);
</code>```

2. You have used RecyclerView width and height as wrap_content. Try using match_parent.

```<code><android.support.v7.widget.RecyclerView
        android:id="@+id/recycleView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</code>```

Hope this will help~

Body:
I am implementing a recycle view with a card layout to do something like this:

the thing is, that I can't get a full width/height card layout, I just keep getting a low card layout like this:

how can I adapt my example to get the result I desire?

I already have the adapter with all the info to stick it inside the card view, but somehow the layout is always that strange :S.

Here is the XML of my mainLayout:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v4.widget.DrawerLayout 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:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

        <include
            layout="@layout/app_bar_plant_feed"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header_plant_feed"
            app:menu="@menu/activity_plant_feed_drawer"
            android:background="@color/white"/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycleView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </android.support.v4.widget.DrawerLayout>

**and the row for the card layout:**

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:elevation="3dp"
        card_view:cardCornerRadius="@dimen/card_specie_radius">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <ImageView
                android:id="@+id/userIcon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_toEndOf="@+id/reportImg"
                android:src="@drawable/ic_user" />

            <TextView
                android:id="@+id/Avaliation"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/plantName"
                android:layout_marginStart="92dp"
                android:layout_marginTop="15dp"
                android:layout_toEndOf="@+id/dateTxt"
                android:text="Avalie a fotografia" />

            <TextView
                android:id="@+id/dateTxt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentEnd="true"
                android:layout_marginEnd="29dp"
                android:text="TextView" />

            <ImageView
                android:id="@+id/reportImg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/color_cursor_white" />

            <ImageView
                android:id="@+id/plantPhoto"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_alignParentTop="true"
                android:layout_marginRight="16dp" />

            <TextView
                android:id="@+id/plantName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toRightOf="@+id/plantPhoto"
                android:textColor="@color/nephritis"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginStart="11dp"
                android:layout_toEndOf="@+id/userIcon" />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

    </LinearLayout>

activity code

public class PlantFeed extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,PlantFeedAdapter.OnItemClickListener {

    //initialize fields

    String token;

    ArrayList<PlantPhotoUser> photos = new ArrayList<>();

    VolleyService mVolleyService;
    IResult mResultCallback = null;
    final String GETREQUEST = "GETCALL";

    final String URL = "http://10.0.2.2:3000/fotos";

    String date;
    String lat;
    String lon;
    String alt;

    PlantFeedAdapter plantFeedAdapter;
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plant_feed);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        recyclerView = (RecyclerView)findViewById(R.id.recycleView);
        recyclerView.setHasFixedSize(true);

        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),5);
        recyclerView.setLayoutManager(layoutManager);
        plantFeedAdapter = new PlantFeedAdapter(getApplicationContext(), photos,PlantFeed.this);
        recyclerView.setAdapter(plantFeedAdapter);

        token = checkForToken();

        initVolleyCallback();

        mVolleyService = new VolleyService(mResultCallback,this);

        mVolleyService.getDataVolley(GETREQUEST,URL,token);

    }

    void initVolleyCallback(){
        mResultCallback = new IResult() {
            @Override
            public void notifySuccess(String requestType,JSONObject response) {
                Log.d("HELLL","hi1");
            }

            @Override
            public void notifySuccess(String requestType, JSONArray response) {
                PlantPhotoUser plantPhotoUser;
                Log.d("HELLLL","hi");
                for (int i=0; i < response.length(); i++) {
                    try {
                        JSONObject object = response.getJSONObject(i);
                        Log.d("objeto",object.toString());

                        int userId = object.getInt("userId");
                        Log.d("objeto",String.valueOf(userId));
                        String username = object.getJSONObject("user").getString("username");
                        Log.d("objeto",String.valueOf(username));
                        int plantId = object.getInt("plantId");
                        Log.d("objeto",String.valueOf(plantId));
                        String specie = object.getJSONObject("plant").getString("specie");
                        Log.d("objeto",String.valueOf(specie));

                        String path = object.getString("image");
                        Log.d("objeto",String.valueOf(path));
                        int fotoId = object.getInt("id");

                        if(object.getString("date") != null){
                            date = object.getString("date");
                        }

                        if(object.getString("lat") != null){
                            lat = object.getString("lat");
                        }

                        if(object.getString("lon") != null){
                            lon = object.getString("lon");
                        }

                        if(object.getString("altitude") != null){
                            alt = object.getString("altitude");
                        }

                        plantPhotoUser = new PlantPhotoUser(fotoId,plantId,userId,path,specie,date,lat,lon,alt,username);
                        photos.add(plantPhotoUser);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                plantFeedAdapter.notifyDataSetChanged();

            }

            @Override
            public void notifyError(String requestType,VolleyError error) {
                Log.d("FAIL",error.toString());
            }
        };
    }

    public String checkForToken() {
        SharedPreferences sharedPref = getSharedPreferences("user", MODE_PRIVATE);
        String tokenKey = getResources().getString(R.string.token);
        String token = sharedPref.getString(getString(R.string.token), tokenKey); // take the token
        return token;
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.plant_feed, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onRowClick(int position, String name, int id, View view) {

    }
}

any help, please?

Thank you

Body:
1. You are using GridLayoutManager for your RecyclerView with span count 5 that's why your CardView uses 1/5 spaces of total screen-width.

Use LinearLayoutManager to show as full-width vertical list:

recyclerView.setLayoutManager(new LinearLayoutManager(this));

Instead of:

RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 5);
recyclerView.setLayoutManager(layoutManager);

2. You have used RecyclerView width and height as wrap_content. Try using match_parent.

<android.support.v7.widget.RecyclerView
        android:id="@+id/recycleView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

Hope this will help~


来源: stackexchange

问:
Cannot set variables in generated CMake script
I am trying to get the output from the invocation of an executable in CMake as a string for processing in the build system. It is a list of test suites that I will add to the CTest tool using add_test.

In CMakeLists.txt

```<code>...(After adding the mlpack_test target)...
configure_file(generate_test_names.cmake.in generate_test_names.cmake)
add_custom_command(TARGET mlpack_test
  POST_BUILD
  COMMAND ${CMAKE_COMMAND} -P generate_test_names.cmake
)
</code>```

In generate_test_names.cmake.in

```<code>function(get_names)
  message("Adding tests to the test suite")
  execute_process(COMMAND ${CMAKE_BINARY_DIR}/bin/mlpack_test --list_content
    OUTPUT_VARIABLE FOO)
  message(STATUS "FOO='${FOO}'")
endfunction()

get_names()
</code>```

The script gets executed, and I can see the output from mlpack_test --list_content in the stdout of the build. But FOO is still an empty string.

The output :

```<code>Adding tests to the test suite
ActivationFunctionsTest*
    TanhFunctionTest*
    LogisticFunctionTest*
    SoftsignFunctionTest*
    IdentityFunctionTest*
    RectifierFunctionTest*
    LeakyReLUFunctionTest*
    HardTanHFunctionTest*
    ELUFunctionTest*
    SoftplusFunctionTest*
    PReLUFunctionTest*
-- FOO=''
</code>```

Why is the argument to OUTPUT_VARIABLE not initialised with the stdout of the process executed?

答:
When generate CMake script with configure_file, it is better to use @ONLY option for that command:

```<code>configure_file(generate_test_names.cmake.in generate_test_names.cmake @ONLY)
</code>```

In that case only @var@ references will be replaced with variable's values, but ${var} references remains unchanged:

```<code>function(get_names)
  message("Adding tests to the test suite")
  # CMAKE_BINARY_DIR will be replaced with the actual value of the variable
  execute_process(COMMAND @CMAKE_BINARY_DIR@/bin/mlpack_test --list_content
    OUTPUT_VARIABLE FOO)
  # But FOO will not be replaced by 'configure_file'.
  message(STATUS "FOO='${FOO}'")
endfunction()

get_names()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to get the output from the invocation of an executable in CMake as a string for processing in the build system. It is a list of test suites that I will add to the CTest tool using add_test.

In CMakeLists.txt

...(After adding the mlpack_test target)...
configure_file(generate_test_names.cmake.in generate_test_names.cmake)
add_custom_command(TARGET mlpack_test
  POST_BUILD
  COMMAND ${CMAKE_COMMAND} -P generate_test_names.cmake
)

In generate_test_names.cmake.in

function(get_names)
  message("Adding tests to the test suite")
  execute_process(COMMAND ${CMAKE_BINARY_DIR}/bin/mlpack_test --list_content
    OUTPUT_VARIABLE FOO)
  message(STATUS "FOO='${FOO}'")
endfunction()

get_names()

The script gets executed, and I can see the output from mlpack_test --list_content in the stdout of the build. But FOO is still an empty string.

The output :

Adding tests to the test suite
ActivationFunctionsTest*
    TanhFunctionTest*
    LogisticFunctionTest*
    SoftsignFunctionTest*
    IdentityFunctionTest*
    RectifierFunctionTest*
    LeakyReLUFunctionTest*
    HardTanHFunctionTest*
    ELUFunctionTest*
    SoftplusFunctionTest*
    PReLUFunctionTest*
-- FOO=''

Why is the argument to OUTPUT_VARIABLE not initialised with the stdout of the process executed?

Body:
When generate CMake script with configure_file, it is better to use @ONLY option for that command:

configure_file(generate_test_names.cmake.in generate_test_names.cmake @ONLY)

In that case only @var@ references will be replaced with variable's values, but ${var} references remains unchanged:

function(get_names)
  message("Adding tests to the test suite")
  # CMAKE_BINARY_DIR will be replaced with the actual value of the variable
  execute_process(COMMAND @CMAKE_BINARY_DIR@/bin/mlpack_test --list_content
    OUTPUT_VARIABLE FOO)
  # But FOO will not be replaced by 'configure_file'.
  message(STATUS "FOO='${FOO}'")
endfunction()

get_names()


问:
In Javascript, how do I generate a random element out of a list?
Suppose I have a list of strings. How do I generate a random one?</p>

答:
```<code>var rand = 0;
var newPic = [];
var pic = [1,2,3] //length = 18 for ( var i=0; i<18; i++ ){
    rand = Math.floor(Math.random()*19);
    newPic.push(pic[rand-1].slice());
} alert(newPic);
</code>```

ContentLicense: CC BY-SA 2.5


问:
How to make SOLR return a CLOB field on search
Is there anyway to return a CLOB value when searching using Solr? Does someone knows anything about this?

Please let me know if you have any opinion about this that can help me. :)

Thanks in advance!

答:
```<code><entity name="Description" transformer="ClobTransformer" query="select * from TABLENAME" >

<field column="COLUMNNAME" name="COLUMNNAME" clob="true" sourceColName="COLUMNNAME" />
</code>```

REF :: ClobTransformer

It's work with me

Body:
<entity name="Description" transformer="ClobTransformer" query="select * from TABLENAME" >

<field column="COLUMNNAME" name="COLUMNNAME" clob="true" sourceColName="COLUMNNAME" />

REF :: ClobTransformer

It's work with me


问:
How to get the output of a jsp file in an HTML text field
index.html

```<code><form action="add.jsp">
first number-<input type="text" name="n1"><br>
second number-<input type="text" name="n2"><br>
<input type="submit" value="SUBMIT"><br>
result-<input type="text">
</form>
</code>```

add.jsp

```<code><body>
<%
int a,b,c;
a=Integer.parseInt(request.getParameter("n1"));
b=Integer.parseInt(request.getParameter("n2"));
c=a+b;
%>
</body>
</code>```

How can I put the value of c in the "result" textfield in the index.html page?

答:
First of all I will suggest not to use scriptlets in a jsp. Jsp is used in view layer for serving the processed outcome, put all your logic in a servlet instead of this approach.
Simpler way to do this:

Change the form tag of your index.jsp to:

```<code><form action="${pageContext.request.contextPath}/demoCalculator">
</code>```

Now create a Servlet: (You need to map this servlet in your web.xml file with a url-pattern "demoCalculator")

```<code>import javax.servlet.http.*;
import javax.servlet.*;
public class DemoServlet extends HttpServlet{
    public void doGet(HttpServletRequest req,HttpServletResponse res)
    throws ServletException
    {

        int a=0,b=0,c=0;
        a=Integer.parseInt(request.getParameter("n1"));
        b=Integer.parseInt(request.getParameter("n2"));
        c=a+b;
        request.setAttribute("result", c);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}
</code>```

Map the servlet in web.xml with url-pattern "demoCalculator"

```<code><servlet-mapping>
    <servlet-name>DemoServlet</servlet-name>
    <url-pattern>/demoCalculator/</url-pattern>
</servlet-mapping>
</code>```

Use a jsp page as your index.jsp and keep the result like this:

```<code>result-<input type="text" value='<c:out value="${requestScope.result}"/>' >
</code>```

Body:
index.html

<form action="add.jsp">
first number-<input type="text" name="n1">

second number-<input type="text" name="n2">

<input type="submit" value="SUBMIT">

result-<input type="text">
</form>

add.jsp

<%
int a,b,c;
a=Integer.parseInt(request.getParameter("n1"));
b=Integer.parseInt(request.getParameter("n2"));
c=a+b;
%>

How can I put the value of c in the "result" textfield in the index.html page?

Body:
First of all I will suggest not to use scriptlets in a jsp. Jsp is used in view layer for serving the processed outcome, put all your logic in a servlet instead of this approach.
Simpler way to do this:

Change the form tag of your index.jsp to:

<form action="${pageContext.request.contextPath}/demoCalculator">

Now create a Servlet: (You need to map this servlet in your web.xml file with a url-pattern "demoCalculator")

import javax.servlet.http.*;
import javax.servlet.*;
public class DemoServlet extends HttpServlet{
    public void doGet(HttpServletRequest req,HttpServletResponse res)
    throws ServletException
    {

        int a=0,b=0,c=0;
        a=Integer.parseInt(request.getParameter("n1"));
        b=Integer.parseInt(request.getParameter("n2"));
        c=a+b;
        request.setAttribute("result", c);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

Map the servlet in web.xml with url-pattern "demoCalculator"

<servlet-mapping>
    <servlet-name>DemoServlet</servlet-name>
    <url-pattern>/demoCalculator/</url-pattern>
</servlet-mapping>

Use a jsp page as your index.jsp and keep the result like this:

result-<input type="text" value='<c:out value="${requestScope.result}"/>' >


问:
Add slideshow function to gallery using Jquery or javascript
What I would like to achieve is a button on toggle that will trigger an automatic slideshow. Like a play/pause button.

I'm using an image gallery from html5up.net the template is here:

https://html5up.net/lens

The next image is currently triggered on click with:

```<code><div class="nav-next"></div>
</code>```

Within the HTML the gallery appears as so, and clicking a thumb will activate the appropriate image.

```<code><section id="thumbnails">
<article>
<a class="thumbnail" href="images/fulls/114.png">
<img src="images/thumbs/114.jpg"/></a>
</article>

<article>
<a class="thumbnail" href="images/fulls/116.png">
<img src="images/thumbs/116.jpg"/></a>
</article>

<article>
<a class="thumbnail" href="images/fulls/168.png">
<img src="images/thumbs/168.jpg"/></a>
</article>
</section>
</code>```

I'm trying variations of attempts as such:

```<code>function slideSwitch() {
    var $active = $('.thumbnail');
    var $next = $active.next();

    $next.addClass('active');

    $active.removeClass('active');
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});
</code>```

However have only achieved frustration at this point as I'm not sure what I'm missing.

Here's a minimal version of the gallery if you want to experiment:

https://codepen.io/anon/pen/VWwVqd

答:
I managed to figure out the slideshow function like so:</p>

```<code>$(function(){
        setInterval(function() {
            $('.nav-next').trigger('click');
        }, 7000);

});
</code>```

Body:
What I would like to achieve is a button on toggle that will trigger an automatic slideshow. Like a play/pause button.

I'm using an image gallery from html5up.net the template is here:

https://html5up.net/lens

The next image is currently triggered on click with:

Within the HTML the gallery appears as so, and clicking a thumb will activate the appropriate image.

I'm trying variations of attempts as such:

function slideSwitch() {
    var $active = $('.thumbnail');
    var $next = $active.next();

    $next.addClass('active');

    $active.removeClass('active');
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});

However have only achieved frustration at this point as I'm not sure what I'm missing.

Here's a minimal version of the gallery if you want to experiment:

https://codepen.io/anon/pen/VWwVqd

Body:
I managed to figure out the slideshow function like so:

$(function(){
        setInterval(function() {
            $('.nav-next').trigger('click');
        }, 7000);

});


问:
What exactly means equal '=' in PHP and how can I deduce where is a simply assign or array extend?
I just discovered that '=' sign behave differently for arrays in php and I can't find a good explanation for that. I considered PHP the most powerful and elegant language (even interpreted) that at least, follows a simple and straight forward syntax, using curly brackets (eg. not indents) or start numbering array elements from 0 (eg. not from 1 like in vb).

```<code><?php

$errors = array();

$errors[] = "first element";
$errors[] = "2'nd element";
$errors[] = "3'rd element";

echo "```";
print_r($errors);
echo "```";

?>
</code>```

Will output

```<code>Array
(
    [0] => first element
    [1] => 2'nd element
    [2] => 3'rd element
)
</code>```

Which is quite odd to me (C,C#,etc..).
The '=' Isn't suppose to re-initialize the object?

I have no problem with this, but isn't it quite confusing?
What is the logic behind and how can I deduce where '=' means equal or assign and not extend object and create a new element in it?

答: = is always an assignment, the only special case here is the assignment to $arr[]. You may read that as "assignment to unspecified array key", and it results in the array key being auto-generated. It's analogous to arr.push(...) or similar in many other languages.

Body:
I just discovered that '=' sign behave differently for arrays in php and I can't find a good explanation for that. I considered PHP the most powerful and elegant language (even interpreted) that at least, follows a simple and straight forward syntax, using curly brackets (eg. not indents) or start numbering array elements from 0 (eg. not from 1 like in vb).

<?php

$errors = array();

$errors[] = "first element";
$errors[] = "2'nd element";
$errors[] = "3'rd element";

echo "
";
print_r($errors);
echo "
";

?>

Will output

Array
(
    [0] => first element
    [1] => 2'nd element
    [2] => 3'rd element
)

Which is quite odd to me (C,C#,etc..).
The '=' Isn't suppose to re-initialize the object?

I have no problem with this, but isn't it quite confusing?
What is the logic behind and how can I deduce where '=' means equal or assign and not extend object and create a new element in it?


问:
constant variance for a time series data in R
So i have been trying to find out a test for constant variance in time series data but failed to find a proper way to do it.
I Have used Bartlett's test for checking constant variance in a regression model earlier but couldn't find one for time series data. Kindly guide me with a solution.</p>

答:
For stationarity you can use any test like: box-ljung or KPSS
For variance you can use the McLeod.Li.test or Box.Coxlambda. Personally I prefer the Box.Coxlambda</p>

```<code>library(fpp)
data(elec) # random dataset
kpss.test(elec) # p = 0.01, series is not stationary
kpss.test(diff(elec, ndiffs(elec)) ) # after differencing, series is stationary

#variance
lambda <- BoxCox.lambda(elec) # = 0.27
lambda # if lambda was around 1, then you do not need any power transform
new_ts <- BoxCox(elec,lambda)
</code>```

Body:
For stationarity you can use any test like: box-ljung or KPSS
For variance you can use the McLeod.Li.test or Box.Coxlambda. Personally I prefer the Box.Coxlambda

library(fpp)
data(elec) # random dataset
kpss.test(elec) # p = 0.01, series is not stationary
kpss.test(diff(elec, ndiffs(elec)) ) # after differencing, series is stationary

#variance
lambda <- BoxCox.lambda(elec) # = 0.27
lambda # if lambda was around 1, then you do not need any power transform
new_ts <- BoxCox(elec,lambda)


答:
= means "assign". What's different between $errors = "first element"; and $errors[] = "first element"; is what you're assigning to....

```<code>$errors = "first element";
</code>```

assigns the value to a variable called $errors

```<code>$errors = array();
$errors[] = "first element";
</code>```

assigns the value to the next element in an "array variable" called $errors

However, there is no "addition" anywhere here. Addition is a mathematical operation that sums numbers together.... be vary careful using the term in the context of creating a new array element

Title: What exactly means equal '=' in PHP and how can I deduce where is a simply assign or array extend?

Body:
= means "assign". What's different between $errors = "first element"; and $errors[] = "first element"; is what you're assigning to....

$errors = "first element";

assigns the value to a variable called $errors

$errors = array();
$errors[] = "first element";

assigns the value to the next element in an "array variable" called $errors

However, there is no "addition" anywhere here. Addition is a mathematical operation that sums numbers together.... be vary careful using the term in the context of creating a new array element


问:
Android java SQLite queries and single quotes
When attempting to query text fields in SQLite I get force closes if the text field contains a single quote character. I know why it's happening but how can I fix it?</p>

答: Use the ? operator. Your query will be like FIELD=?, and the next argument to the query() call will be a String array where you provide an argument for each ? you used.


问:
How to change color of the bubble (under cursor) on EditText (programmatically)?
I have EditText and want to change color PROGRAMMATICALLY on code.

To change color of cursor I use this code.

But how to change color of the circle on EditView PROGRAMMATICALLY on code?

答:
The below method works for all cursors bubble such as left, right and center. I mean,beside your request, It works for both left and right ones.

For example;

You can change that method to only color the center handle by removing the left and right field names in the two arrays.

```<code>public static void colorHandles(TextView view, int color) {
  try {
    Field editorField = TextView.class.getDeclaredField("mEditor");
    if (!editorField.isAccessible()) {
      editorField.setAccessible(true);
    }

    Object editor = editorField.get(view);
    Class<?> editorClass = editor.getClass();

    String[] handleNames = {"mSelectHandleLeft", "mSelectHandleRight", "mSelectHandleCenter"};
    String[] resNames = {"mTextSelectHandleLeftRes", "mTextSelectHandleRightRes", "mTextSelectHandleRes"};

    for (int i = 0; i < handleNames.length; i++) {
      Field handleField = editorClass.getDeclaredField(handleNames[i]);
      if (!handleField.isAccessible()) {
        handleField.setAccessible(true);
      }

      Drawable handleDrawable = (Drawable) handleField.get(editor);

      if (handleDrawable == null) {
        Field resField = TextView.class.getDeclaredField(resNames[i]);
        if (!resField.isAccessible()) {
          resField.setAccessible(true);
        }
        int resId = resField.getInt(view);
        handleDrawable = view.getResources().getDrawable(resId);
      }

      if (handleDrawable != null) {
        Drawable drawable = handleDrawable.mutate();
        drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
        handleField.set(editor, drawable);
      }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The below method works for all cursors bubble such as left, right and center. I mean,beside your request, It works for both left and right ones.

For example;

You can change that method to only color the center handle by removing the left and right field names in the two arrays.

public static void colorHandles(TextView view, int color) {
  try {
    Field editorField = TextView.class.getDeclaredField("mEditor");
    if (!editorField.isAccessible()) {
      editorField.setAccessible(true);
    }

    Object editor = editorField.get(view);
    Class<?> editorClass = editor.getClass();

    String[] handleNames = {"mSelectHandleLeft", "mSelectHandleRight", "mSelectHandleCenter"};
    String[] resNames = {"mTextSelectHandleLeftRes", "mTextSelectHandleRightRes", "mTextSelectHandleRes"};

    for (int i = 0; i < handleNames.length; i++) {
      Field handleField = editorClass.getDeclaredField(handleNames[i]);
      if (!handleField.isAccessible()) {
        handleField.setAccessible(true);
      }

      Drawable handleDrawable = (Drawable) handleField.get(editor);

      if (handleDrawable == null) {
        Field resField = TextView.class.getDeclaredField(resNames[i]);
        if (!resField.isAccessible()) {
          resField.setAccessible(true);
        }
        int resId = resField.getInt(view);
        handleDrawable = view.getResources().getDrawable(resId);
      }

      if (handleDrawable != null) {
        Drawable drawable = handleDrawable.mutate();
        drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
        handleField.set(editor, drawable);
      }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}


问:
Facebook Graph API: Getting the total number of posts
I've been using the Facebook Graph API to display user posts.  When I get the initial "page" of posts, the resulting data object has a paging property object with a previous and next URL property.  I was hoping to generate navigation links based on this available paging information.  However, sometimes these URLs point to an empty set of data, so I obviously don't want to navigate the user to an empty page.

Is there a way to find the total count of objects in a collection so that better navigation can be derived?  Is there any way to get smarter paging data?

Update:
Sorry if my post isn't clear.  To illustrate, look at the data at https://graph.facebook.com/7901103/posts and its paging property URLs.  Then follow those URLs to see the issue: empty pages of data.

答:
I was going to try to post this as a comment to your question, but I can't seem to do so...

I know that the Graph API returns JSON, and while I've never come across a way to have the total number of posts returned, depending on what technology you are using to process the response, you might be able to capture the size of the JSON array containing the posts.

For example, if I were using a java application I could use the libraries available at json.org (or Google GSON, or XStream with the JSON driver) to populate an object and then simply use the JSONArray.length() method to check for the number of posts returned.

see:
http://www.json.org/javadoc/org/json/JSONArray.html

It might seem like a bit of a simplistic solution, but might be the type of work around you require if you can't find a way to have Facebook return that data.

Can you specify what technology your application is based in?


问:
How to access the value of an input disabled?
I'm creating a reactive form in angular 2 and using material angular 2 to inputs;

I need to set an input as disabled and when submitting the value that is in the unlocked input the value to be sent. I Already created the input and the disabled is running. My problem is that when I give a submit value it does not come.

My code

```<code>this.formVariacao = this._fb.group({

   id:[p && p['id']],
   codigoItem: [p && p['codigoItem'], Validators.required],
});
</code>```

My html

```<code><md-input-container>
    <input mdInput placeholder="Código da Variação" formControlName="codigoItem" name="codigoItem">
</md-input-container>
</code>```

I block the input as follows

```<code>this.formVariacao.get('codigoItem').disable();
</code>```

Only when I send the form the value does not come. Alguém pode me ajudar?

答:
As you noticed Angular ignores disabled form controls in the form object.

This can be easily fixed by using getRawValue(), which includes all form controls, disabled or not. So for example on your submit, you pass the form (NOT the form value) like so:

```<code>(ngSubmit)="onSubmit(formVariacao)"
</code>```

Then you can use getRawValue:

```<code>onSubmit(form) {
  console.log(form.getRawValue())
}
</code>```

Body:
I'm creating a reactive form in angular 2 and using material angular 2 to inputs;

I need to set an input as disabled and when submitting the value that is in the unlocked input the value to be sent. I Already created the input and the disabled is running. My problem is that when I give a submit value it does not come.

My code

this.formVariacao = this._fb.group({

   id:[p && p['id']],
   codigoItem: [p && p['codigoItem'], Validators.required],
});

My html

<md-input-container>
    <input mdInput placeholder="Código da Variação" formControlName="codigoItem" name="codigoItem">
</md-input-container>

I block the input as follows

this.formVariacao.get('codigoItem').disable();

Only when I send the form the value does not come. Alguém pode me ajudar?

Body:
As you noticed Angular ignores disabled form controls in the form object.

This can be easily fixed by using getRawValue(), which includes all form controls, disabled or not. So for example on your submit, you pass the form (NOT the form value) like so:

(ngSubmit)="onSubmit(formVariacao)"

Then you can use getRawValue:

onSubmit(form) {
  console.log(form.getRawValue())
}


问:
Showing Greeting Message in Javascript
How can I display a greeting message according to the time of the day in javascript?</p>

```<code>var greetdate=new Date()
var hours=greetdate.getHours()

document.write('<h2>Hello! Good Morning! Have a nice day.</h2>')

document.write('<h2>Good Noon Visitor! </h2>')

//MESSAGE FOR AFTERNOON
document.write('<h2>Good Afternoon! </h2>')

//MESSAGE FOR EVENING (6pm-8pm)
document.write('<h2>Good Evening! </h2>')

//MESSAGE FOR NIGHT (9pm-11pm)
document.write('<h2>Good Night! </h2>')

//MESSAGE FOR LATE NIGHT (12pm-4am)
document.write('<h2>Wow! You`re still awake. Working Late?</h2>')
</code>```

答:
Good usecase for a switch:

```<code>var h=(new Date()).getHours();
switch(true){
case h<13 :
  document.write('<h2>Hello! Good Morning! Have a nice day.</h2>');
break;
case h<=14 :
    document.write('<h2>Good Noon Visitor! </h2>')
break;
case h<18 :
    document.write('<h2>Good Afternoon! </h2>')
break;
case h<21 :
    document.write('<h2>Good Evening! </h2>')
break;
case h<24 :
    document.write('<h2>Good Night! </h2>');
break;
}
</code>```

All outputs: http://jsbin.com/fesulamaga/edit?output

Title: Showing Greeting Message in Javascript

Body:
How can I display a greeting message according to the time of the day in javascript?

var greetdate=new Date()
var hours=greetdate.getHours()

document.write('
Hello! Good Morning! Have a nice day.
')

document.write('
Good Noon Visitor!
')

//MESSAGE FOR AFTERNOON
document.write('
Good Afternoon!
')

//MESSAGE FOR EVENING (6pm-8pm)
document.write('
Good Evening!
')

//MESSAGE FOR NIGHT (9pm-11pm)
document.write('
Good Night!
')

//MESSAGE FOR LATE NIGHT (12pm-4am)
document.write('
Wow! You`re still awake. Working Late?
')

Body:
Good usecase for a switch:

var h=(new Date()).getHours();
switch(true){
case h<13 :
  document.write('<h2>Hello! Good Morning! Have a nice day.</h2>');
break;
case h<=14 :
    document.write('<h2>Good Noon Visitor! </h2>')
break;
case h<18 :
    document.write('<h2>Good Afternoon! </h2>')
break;
case h<21 :
    document.write('<h2>Good Evening! </h2>')
break;
case h<24 :
    document.write('<h2>Good Night! </h2>');
break;
}

All outputs: http://jsbin.com/fesulamaga/edit?output


问:
Android "O" returns "O" for version
In all previous Android versions Build.VERSION.RELEASE returned String which was actually a number : 7.1.0 , 5.0.1 etc.

Basing on this, I have a simple version controller that compares the numbers and can tell me is devices' OS was upgraded or downgraded. Android "O" beta version surprisingly returns "O" letter for  Build.VERSION.RELEASE which, of course, causes an exception.
Is this a dead end or there is some method that will return 8.0.0 in case of Android "O"?

Build.VERSION.SDK_INT returns 25.

Build.VERSION.INCREMENTAL returns huge build number.

答:
It is not released yet.

There will be a number once the API is stable. We are currently at Preview 2, but have a look at Program Overview

Preview 3 (final APIs and official SDK, Play publishing)

I would guess that's when they give it an official version number.

Title: Android "O" returns "O" for version


问:
How to ensure a file exists on assets folder at build time?
I have a JSON file db_seed.json that I want to use as a seed to pre-populate local database in my Android application. This JSON file is dynamically generated from another data source and quite big in size, so I don't want to include this in version control.

However, each time I build the application, I want to make sure that the build process check the existence of this file in the assets folder and shout a build error if it's not (to make sure that I don't publish an incomplete APK). Is it possible to configure Gradle in Android Studio to do this?

答:
try this</p>

```<code>if (!file('./app/assets/db_seed.json').exists()) {
    logger.log(LogLevel.ERROR, "file not foun")
    throw new GradleException("file not found")
}
</code>```

Body:
try this

if (!file('./app/assets/db_seed.json').exists()) {
    logger.log(LogLevel.ERROR, "file not foun")
    throw new GradleException("file not found")
}


问:
Migration from qmake to cmake
I have followed this guide http://doc.qt.io/qt-5/gettingstartedqt.html and everything works fine.
But now I want to convert this project from qmake to cmake; this is the CMakeLists.txt

```<code>project(Notepad)

# Application Version, managed by release script
set(APPLICATIONS_VERSION_MAJOR "0")
set(APPLICATIONS_VERSION_MINOR "0")
set(APPLICATIONS_VERSION_MICRO "1")
set(APPLICATIONS_VERSION "${APPLICATIONS_VERSION_MAJOR}.${APPLICATIONS_VERSION_MINOR}.${APPLICATIONS_VERSION_MICRO}")

# Minimum required software
set(CMAKE_MIN_REQUIRED_VERSION "3.7.2")
set(QT_MIN_REQUIRED_VERSION "5.7.1")
set(KF5_MIN_REQUIRED_VERSION "5.31.0")
set(ECM_MIN_REQUIRED_VERSION "5.31.0")

cmake_minimum_required(VERSION "${CMAKE_MIN_REQUIRED_VERSION}" FATAL_ERROR)

# Configure ECM
find_package(ECM "${ECM_MIN_REQUIRED_VERSION}" REQUIRED NO_MODULE)
set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH})

include(FeatureSummary)
include(ECMSetupVersion)

# Generate header with version number
ecm_setup_version("${APPLICATIONS_VERSION}" VARIABLE_PREFIX NOTEPAD
                  VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/notepad_version.h"
)

# Find Qt modules
find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS
    Core
    Gui
    Widgets
)

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOUIC ON)

set(CMAKE_CXX_STANDARD 11) # C++11...
set(CMAKE_CXX_STANDARD_REQUIRED ON) #...is required...
set(CMAKE_CXX_EXTENSIONS OFF) #...without compiler extensions like gnu++11

set(notepad_SRCS main.cpp notepad.h notepad.cpp)

add_executable(notepad ${notepad_SRCS})

target_link_libraries(notepad
    Qt5::Widgets
    Qt5::Core
    Qt5::Gui
)

feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)
</code>```

And I get this output:

```<code>/documenti/deglans/Programmazione/QtCreator/Notepad/build> make -j4
Scanning dependencies of target notepad_automoc
[ 25%] Automatic uic for target notepad
Generating ui header ui_notepad.h
[ 25%] Built target notepad_automoc
Scanning dependencies of target notepad
[ 50%] Building CXX object CMakeFiles/notepad.dir/main.cpp.o
[ 75%] Building CXX object CMakeFiles/notepad.dir/notepad.cpp.o
[100%] Linking CXX executable notepad
CMakeFiles/notepad.dir/notepad.cpp.o: In function `Notepad::Notepad(QWidget*)':
/documenti/deglans/Programmazione/QtCreator/Notepad/notepad.cpp:28: undefined reference to `vtable for Notepad'
/documenti/deglans/Programmazione/QtCreator/Notepad/notepad.cpp:28: undefined reference to `vtable for Notepad'
CMakeFiles/notepad.dir/notepad.cpp.o: In function `Notepad::~Notepad()':
/documenti/deglans/Programmazione/QtCreator/Notepad/notepad.cpp:33: undefined reference to `vtable for Notepad'
/documenti/deglans/Programmazione/QtCreator/Notepad/notepad.cpp:33: undefined reference to `vtable for Notepad'
CMakeFiles/notepad.dir/notepad.cpp.o: In function `Notepad::tr(char const*, char const*, int)':
/documenti/deglans/Programmazione/QtCreator/Notepad/notepad.h:28: undefined reference to `Notepad::staticMetaObject'
collect2: error: ld returned 1 exit status
CMakeFiles/notepad.dir/build.make:123: recipe for target 'notepad' failed
make[2]: *** [notepad] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/notepad.dir/all' failed
make[1]: *** [CMakeFiles/notepad.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2
*** Errore: Codice di uscita 2 ***
</code>```

This is the part of code that give error when using cmake:

```<code>Notepad::Notepad(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Notepad)
{
    ui->setupUi(this);
}

Notepad::~Notepad()
{
    delete ui;
}
</code>```

Note that with qmake and QtCreator I have non problem, the problem born when I try to use KDevelop and cmake.

答:
I have resolved the problem by adding this line set(CMAKE_AUTOMOC ON) as suggested by Lorenz.
So CMakeLists.txt become:

```<code>project(Notepad)

# Application Version, managed by release script
set(APPLICATIONS_VERSION_MAJOR "0")
set(APPLICATIONS_VERSION_MINOR "0")
set(APPLICATIONS_VERSION_MICRO "1")
set(APPLICATIONS_VERSION "${APPLICATIONS_VERSION_MAJOR}.${APPLICATIONS_VERSION_MINOR}.${APPLICATIONS_VERSION_MICRO}")

# Minimum required software
set(CMAKE_MIN_REQUIRED_VERSION "3.7.2")
set(QT_MIN_REQUIRED_VERSION "5.7.1")
set(KF5_MIN_REQUIRED_VERSION "5.31.0")
set(ECM_MIN_REQUIRED_VERSION "5.31.0")

cmake_minimum_required(VERSION "${CMAKE_MIN_REQUIRED_VERSION}" FATAL_ERROR)

# Configure ECM
find_package(ECM "${ECM_MIN_REQUIRED_VERSION}" REQUIRED NO_MODULE)
set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH})

include(FeatureSummary)
include(ECMSetupVersion)

# Generate header with version number
ecm_setup_version("${APPLICATIONS_VERSION}" VARIABLE_PREFIX NOTEPAD
              VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/notepad_version.h"
)

# Find Qt modules
find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS
    Core
    Gui
    Widgets
)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON) # <<<<<<<-----------------------------

set(CMAKE_CXX_STANDARD 11) # C++11...
set(CMAKE_CXX_STANDARD_REQUIRED ON) #...is required...
set(CMAKE_CXX_EXTENSIONS OFF) #...without compiler extensions like gnu++11

set(notepad_SRCS main.cpp notepad.h notepad.cpp)

add_executable(notepad ${notepad_SRCS})

target_link_libraries(notepad
    Qt5::Widgets
    Qt5::Core
    Qt5::Gui
)

feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)
</code>```

Title: Migration from qmake to cmake

Body:
I have followed this guide http://doc.qt.io/qt-5/gettingstartedqt.html and everything works fine.
But now I want to convert this project from qmake to cmake; this is the CMakeLists.txt

project(Notepad)

# Application Version, managed by release script
set(APPLICATIONS_VERSION_MAJOR "0")
set(APPLICATIONS_VERSION_MINOR "0")
set(APPLICATIONS_VERSION_MICRO "1")
set(APPLICATIONS_VERSION "${APPLICATIONS_VERSION_MAJOR}.${APPLICATIONS_VERSION_MINOR}.${APPLICATIONS_VERSION_MICRO}")

# Minimum required software
set(CMAKE_MIN_REQUIRED_VERSION "3.7.2")
set(QT_MIN_REQUIRED_VERSION "5.7.1")
set(KF5_MIN_REQUIRED_VERSION "5.31.0")
set(ECM_MIN_REQUIRED_VERSION "5.31.0")

cmake_minimum_required(VERSION "${CMAKE_MIN_REQUIRED_VERSION}" FATAL_ERROR)

# Configure ECM
find_package(ECM "${ECM_MIN_REQUIRED_VERSION}" REQUIRED NO_MODULE)
set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH})

include(FeatureSummary)
include(ECMSetupVersion)

# Generate header with version number
ecm_setup_version("${APPLICATIONS_VERSION}" VARIABLE_PREFIX NOTEPAD
                  VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/notepad_version.h"
)

# Find Qt modules
find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS
    Core
    Gui
    Widgets
)

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOUIC ON)

set(CMAKE_CXX_STANDARD 11) # C++11...
set(CMAKE_CXX_STANDARD_REQUIRED ON) #...is required...
set(CMAKE_CXX_EXTENSIONS OFF) #...without compiler extensions like gnu++11

set(notepad_SRCS main.cpp notepad.h notepad.cpp)

add_executable(notepad ${notepad_SRCS})

target_link_libraries(notepad
    Qt5::Widgets
    Qt5::Core
    Qt5::Gui
)

feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)

And I get this output:

/documenti/deglans/Programmazione/QtCreator/Notepad/build> make -j4
Scanning dependencies of target notepad_automoc
[ 25%] Automatic uic for target notepad
Generating ui header ui_notepad.h
[ 25%] Built target notepad_automoc
Scanning dependencies of target notepad
[ 50%] Building CXX object CMakeFiles/notepad.dir/main.cpp.o
[ 75%] Building CXX object CMakeFiles/notepad.dir/notepad.cpp.o
[100%] Linking CXX executable notepad
CMakeFiles/notepad.dir/notepad.cpp.o: In function `Notepad::Notepad(QWidget*)':
/documenti/deglans/Programmazione/QtCreator/Notepad/notepad.cpp:28: undefined reference to `vtable for Notepad'
/documenti/deglans/Programmazione/QtCreator/Notepad/notepad.cpp:28: undefined reference to `vtable for Notepad'
CMakeFiles/notepad.dir/notepad.cpp.o: In function `Notepad::~Notepad()':
/documenti/deglans/Programmazione/QtCreator/Notepad/notepad.cpp:33: undefined reference to `vtable for Notepad'
/documenti/deglans/Programmazione/QtCreator/Notepad/notepad.cpp:33: undefined reference to `vtable for Notepad'
CMakeFiles/notepad.dir/notepad.cpp.o: In function `Notepad::tr(char const*, char const*, int)':
/documenti/deglans/Programmazione/QtCreator/Notepad/notepad.h:28: undefined reference to `Notepad::staticMetaObject'
collect2: error: ld returned 1 exit status
CMakeFiles/notepad.dir/build.make:123: recipe for target 'notepad' failed
make[2]: *** [notepad] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/notepad.dir/all' failed
make[1]: *** [CMakeFiles/notepad.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2
*** Errore: Codice di uscita 2 ***

This is the part of code that give error when using cmake:

Notepad::Notepad(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Notepad)
{
    ui->setupUi(this);
}

Notepad::~Notepad()
{
    delete ui;
}

Note that with qmake and QtCreator I have non problem, the problem born when I try to use KDevelop and cmake.

Body:
I have resolved the problem by adding this line set(CMAKE_AUTOMOC ON) as suggested by Lorenz.
So CMakeLists.txt become:

project(Notepad)

# Application Version, managed by release script
set(APPLICATIONS_VERSION_MAJOR "0")
set(APPLICATIONS_VERSION_MINOR "0")
set(APPLICATIONS_VERSION_MICRO "1")
set(APPLICATIONS_VERSION "${APPLICATIONS_VERSION_MAJOR}.${APPLICATIONS_VERSION_MINOR}.${APPLICATIONS_VERSION_MICRO}")

# Minimum required software
set(CMAKE_MIN_REQUIRED_VERSION "3.7.2")
set(QT_MIN_REQUIRED_VERSION "5.7.1")
set(KF5_MIN_REQUIRED_VERSION "5.31.0")
set(ECM_MIN_REQUIRED_VERSION "5.31.0")

cmake_minimum_required(VERSION "${CMAKE_MIN_REQUIRED_VERSION}" FATAL_ERROR)

# Configure ECM
find_package(ECM "${ECM_MIN_REQUIRED_VERSION}" REQUIRED NO_MODULE)
set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH})

include(FeatureSummary)
include(ECMSetupVersion)

# Generate header with version number
ecm_setup_version("${APPLICATIONS_VERSION}" VARIABLE_PREFIX NOTEPAD
              VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/notepad_version.h"
)

# Find Qt modules
find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED COMPONENTS
    Core
    Gui
    Widgets
)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON) # <<<<<<<-----------------------------

set(CMAKE_CXX_STANDARD 11) # C++11...
set(CMAKE_CXX_STANDARD_REQUIRED ON) #...is required...
set(CMAKE_CXX_EXTENSIONS OFF) #...without compiler extensions like gnu++11

set(notepad_SRCS main.cpp notepad.h notepad.cpp)

add_executable(notepad ${notepad_SRCS})

target_link_libraries(notepad
    Qt5::Widgets
    Qt5::Core
    Qt5::Gui
)

feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES)


问:
handle exception in try catch block
I have a switch case scenario where I know beforehand that there is a high level of opportunity that the user might not set the the rules with the right categories. it's totally ok for me as soon as i can pop up a dialog showing instructions what to do in order to run the program. However i am missing something and here is my question.

When i test a scenario as per above the cursor goes through the default case, and pops up the error. How can i make it goes into my catch block?

```<code>try
{
    switch (userInput)
    {
        case 1:
        case 2:
        case 3:
            if (condition)
            {
               some code here
            }
            else
            {
                throw error();
            }
            break;
        case 4:
            postingType = smth;
            break;
        default:
            throw Global::error("here blows the error and does not move on to the catch");
    }
}
catch(exception::Error)
{
    info("test");
}
</code>```

Your help is much appreciated!

Thank you in advance and have a nice evening.

H.

答: The reason is that exceptions generally aren't caught inside database transactions. I explained it with a little more details in the thread about the same question in the Dynamics community forum, where it's been marked as the verified answer.</p>

Title: handle exception in try catch block

Body:
I have a switch case scenario where I know beforehand that there is a high level of opportunity that the user might not set the the rules with the right categories. it's totally ok for me as soon as i can pop up a dialog showing instructions what to do in order to run the program. However i am missing something and here is my question.

When i test a scenario as per above the cursor goes through the default case, and pops up the error. How can i make it goes into my catch block?

try
{
    switch (userInput)
    {
        case 1:
        case 2:
        case 3:
            if (condition)
            {
               some code here
            }
            else
            {
                throw error();
            }
            break;
        case 4:
            postingType = smth;
            break;
        default:
            throw Global::error("here blows the error and does not move on to the catch");
    }
}
catch(exception::Error)
{
    info("test");
}

Your help is much appreciated!

Thank you in advance and have a nice evening.

H.


问:
The correct way to Malloc() space for a pointer to an array of int
Say I have a pointer to an array of int's, like so: int (*x)[3].
What is the correct way to allocate space for such a variable? For example, say I wanted space for 10 items (so that I can store a total of 10 * 3 = 30 values in x):

```<code>/* Is this the correct way? */
x = malloc(sizeof(x) * 10);

/* Will it allow me to do this? */
x[0][0] = 10;
x[0][1] = 20;
x[0][2] = 30;

x[1][0] = 40;
x[1][1] = 50;
x[1][2] = 60;

/* ... etc ... */
</code>```

Or is there some other way to correctly malloc the memory for x (i.e. x = malloc(sizeof(int) * 10) or x = malloc(sizeof(int *) * 10)?

Thanks.

答:
First of all, you don't want to allocate space for the pointer, but for the object it points to. This is an important difference.

So you have a pointer type that points to a 2-d array with a second dimension of 3 (let's call this columns) and you want the array to have 10 rows. In C, n-dimensional arrays are stored contiguously, that means, they take exactly as much room as all of their elements together. So the formula gets pretty simple:

```<code>x = malloc(3 * 10 * sizeof(int));
</code>```

edit: if you want to avoid magic numbers, you could also work with a typedef:

```<code>typedef int inttriplet[3];
// [...]
inttriplet *x;
x = malloc(10 * sizeof(inttriplet));
</code>```

Body:
Say I have a pointer to an array of int's, like so: int (*x)[3].
What is the correct way to allocate space for such a variable? For example, say I wanted space for 10 items (so that I can store a total of 10 * 3 = 30 values in x):

/* Is this the correct way? */
x = malloc(sizeof(x) * 10);

/* Will it allow me to do this? */
x[0][0] = 10;
x[0][1] = 20;
x[0][2] = 30;

x[1][0] = 40;
x[1][1] = 50;
x[1][2] = 60;

/* ... etc ... */

Or is there some other way to correctly malloc the memory for x (i.e. x = malloc(sizeof(int) * 10) or x = malloc(sizeof(int *) * 10)?

Thanks.

Body:
First of all, you don't want to allocate space for the pointer, but for the object it points to. This is an important difference.

So you have a pointer type that points to a 2-d array with a second dimension of 3 (let's call this columns) and you want the array to have 10 rows. In C, n-dimensional arrays are stored contiguously, that means, they take exactly as much room as all of their elements together. So the formula gets pretty simple:

x = malloc(3 * 10 * sizeof(int));

edit: if you want to avoid magic numbers, you could also work with a typedef:

typedef int inttriplet[3];
// [...]
inttriplet *x;
x = malloc(10 * sizeof(inttriplet));


问:
Sum two integers in Java
Im trying to sum two numbers from user input. But its not working

This is what I have done

```<code>import java.util.*;

public class EX2 {
  public static void main(String[] args) {
    int x;
    int y;

    Scanner x = new Scanner(System.in);
    x.nextInt();

    Scanner y = new Scanner(System.in);
    y.nextInt();

    int sum = x + y;

    System.out.println(x + " " + y);
    System.out.println(sum);
  }
}
</code>```

the error code is

```<code>Error:(12, 17) java: variable x is already defined in method main(java.lang.String[])
Error:(13, 10) java: int cannot be dereferenced
</code>```

Am I missing something here?

答:
You reused the x and y variable names (hence the variable x is already defined in method main error), and forgot to assign the ints read from the Scanner to the x and y variables.

Besides, there's no need to create two Scanner objects.

```<code>public static void main(String[] args){
    int x;
    int y;

    Scanner sc = new Scanner(System.in);
    x = sc.nextInt();
    y = sc.nextInt();

    int sum = x + y;

    System.out.println(x +" "+ y);
    System.out.println(sum);
}
</code>```

Title: Sum two integers in Java

Body:
Im trying to sum two numbers from user input. But its not working

This is what I have done

import java.util.*;

public class EX2 {
  public static void main(String[] args) {
    int x;
    int y;

    Scanner x = new Scanner(System.in);
    x.nextInt();

    Scanner y = new Scanner(System.in);
    y.nextInt();

    int sum = x + y;

    System.out.println(x + " " + y);
    System.out.println(sum);
  }
}

the error code is

Error:(12, 17) java: variable x is already defined in method main(java.lang.String[])
Error:(13, 10) java: int cannot be dereferenced

Am I missing something here?

Body:
You reused the x and y variable names (hence the variable x is already defined in method main error), and forgot to assign the ints read from the Scanner to the x and y variables.

Besides, there's no need to create two Scanner objects.

public static void main(String[] args){
    int x;
    int y;

    Scanner sc = new Scanner(System.in);
    x = sc.nextInt();
    y = sc.nextInt();

    int sum = x + y;

    System.out.println(x +" "+ y);
    System.out.println(sum);
}


问:
Is there a way to set a cell in grid in edit mode with Vaadin 8 grid
I have defined a grid like this using Vaadin 8:

```<code>    ListDataProvider<Value> gridDataProvider =
        new ListDataProvider<>(new ArrayList<>());
        GridSelectionModel<Value> selectionModel;
        Grid<Value> grid = new Grid<>(Value.class);
        TextField editorField = new TextField();
        editorField.setSizeFull();
        Binder<Value> binder = new Binder<>();
        binder.bind(editorField, Value::getValue, Value::setValue);
        Editor<Value> gridEditor = grid.getEditor();
        gridEditor.setBinder(binder);
        gridEditor.addSaveListener((EditorSaveListener<Value>) event -> {

            gridDataProvider.refreshAll();
        });
        gridEditor.setEnabled(true);
        grid.addColumn(Value::getValue).setEditorComponent(editorField, Value::setValue);
        grid.removeHeaderRow(0);
        selectionModel = grid.setSelectionMode(Grid.SelectionMode.MULTI);
        grid.setDataProvider(gridDataProvider);
        grid.setSizeFull();
</code>```

The Value bean is just a regular bean

```<code>    private class Value {
       private String value;

        Value(String value) {
           this.value = value;
       }

        String getValue() {
           return value;
       }

        void setValue(String value) {
           this.value = value;
       }

       @Override public boolean equals(Object o) {
           if (this == o)
               return true;
           if (o == null || getClass() != o.getClass())
               return false;
           Value value1 = (Value) o;
           return Objects.equals(value, value1.value);
       }
</code>```

What I want to do is to add button so by clicking on that button a new row should be added to grid and the only column in the new row should be set to edit mode so user can write a new value directly.
Is it possible to do this?

答:
Opening editor programmatically is not possible with the current Vaadin 8 APIs. There are 2 issues to add this feature currently open:

https://github.com/vaadin/framework/issues/8477

https://github.com/vaadin/framework/issues/8820

It might be good idea not to use Value.value in equals method because this will cause problems with some Grid features, like grid.select(T item).

This piece of code will allow user to use arrow and enter keys to edit the latest item.

```<code>private void onButtonClick(Button.ClickEvent clickEvent) {
    Value newValue = new Value("New value");
    list.add(newValue);
    grid.getDataProvider().refreshAll();
    grid.focus();
}
</code>```

Grid will not receive focus automatically after editor is hidden. You need to help Vaadin a bit:

```<code>gridEditor.addSaveListener((EditorSaveListener<Value>) event -> {
    gridDataProvider.refreshAll();
    grid.focus();
});
</code>```

Body:
I have defined a grid like this using Vaadin 8:

    ListDataProvider<Value> gridDataProvider =
        new ListDataProvider<>(new ArrayList<>());
        GridSelectionModel<Value> selectionModel;
        Grid<Value> grid = new Grid<>(Value.class);
        TextField editorField = new TextField();
        editorField.setSizeFull();
        Binder<Value> binder = new Binder<>();
        binder.bind(editorField, Value::getValue, Value::setValue);
        Editor<Value> gridEditor = grid.getEditor();
        gridEditor.setBinder(binder);
        gridEditor.addSaveListener((EditorSaveListener<Value>) event -> {

            gridDataProvider.refreshAll();
        });
        gridEditor.setEnabled(true);
        grid.addColumn(Value::getValue).setEditorComponent(editorField, Value::setValue);
        grid.removeHeaderRow(0);
        selectionModel = grid.setSelectionMode(Grid.SelectionMode.MULTI);
        grid.setDataProvider(gridDataProvider);
        grid.setSizeFull();

The Value bean is just a regular bean

    private class Value {
       private String value;

        Value(String value) {
           this.value = value;
       }

        String getValue() {
           return value;
       }

        void setValue(String value) {
           this.value = value;
       }

       @Override public boolean equals(Object o) {
           if (this == o)
               return true;
           if (o == null || getClass() != o.getClass())
               return false;
           Value value1 = (Value) o;
           return Objects.equals(value, value1.value);
       }

What I want to do is to add button so by clicking on that button a new row should be added to grid and the only column in the new row should be set to edit mode so user can write a new value directly.
Is it possible to do this?

Body:
Opening editor programmatically is not possible with the current Vaadin 8 APIs. There are 2 issues to add this feature currently open:

https://github.com/vaadin/framework/issues/8477

https://github.com/vaadin/framework/issues/8820

It might be good idea not to use Value.value in equals method because this will cause problems with some Grid features, like grid.select(T item).

This piece of code will allow user to use arrow and enter keys to edit the latest item.

private void onButtonClick(Button.ClickEvent clickEvent) {
    Value newValue = new Value("New value");
    list.add(newValue);
    grid.getDataProvider().refreshAll();
    grid.focus();
}

Grid will not receive focus automatically after editor is hidden. You need to help Vaadin a bit:

gridEditor.addSaveListener((EditorSaveListener<Value>) event -> {
    gridDataProvider.refreshAll();
    grid.focus();
});


问:
How do I center the div vertically?

Possible Duplicate:

  What's The Best Way of Centering a Div Vertically with CSS

```<code>.title_text_only{
position:absolute;
width:100%;
display:none;
z-index:9;
top:50%;
bottom:50%;
text-align:center;
color:#fff;
font-size:18px;
text-shadow: 1px 1px 1px #666;
}
</code>```

Right now, it doesn't seem to work. top 50% doesn't center it vertically. It's a little to the bottom.  It's as if the top border is 50%.

答:
If you can specify the height of the box, you can use margin-top: -[height / 2]px (fill in [height / 2] and note that most browsers will round fractional pixels up at 100% zoom).

If you can specify the height of its parent, you can do something like this:

```<code>parent {
    height: [height]px;
}
child {
    /* Make the element part of the inline flow, as vertical-align isn't supported on block elements */
    display: -moz-inline-box; /* Old Firefox doesn't support inline-block */
    display: inline-block;
    /* IE < 8 doesn't support inline-block on native block-level elements */
    *display: inline;
    *zoom: 1;

    /* The interesting bit */
    line-height: [height]px;
    vertical-align: middle;
}
</code>```

If the content of the child is expected to wrap onto multiple lines, you can wrap it in a sub-child that resets the line-height.

Title: How do I center the div vertically?

Body:
Possible Duplicate:

  What's The Best Way of Centering a Div Vertically with CSS

.title_text_only{
position:absolute;
width:100%;
display:none;
z-index:9;
top:50%;
bottom:50%;
text-align:center;
color:#fff;
font-size:18px;
text-shadow: 1px 1px 1px #666;
}

Right now, it doesn't seem to work. top 50% doesn't center it vertically. It's a little to the bottom.  It's as if the top border is 50%.

Body:
If you can specify the height of the box, you can use margin-top: -[height / 2]px (fill in [height / 2] and note that most browsers will round fractional pixels up at 100% zoom).

If you can specify the height of its parent, you can do something like this:

parent {
    height: [height]px;
}
child {
    /* Make the element part of the inline flow, as vertical-align isn't supported on block elements */
    display: -moz-inline-box; /* Old Firefox doesn't support inline-block */
    display: inline-block;
    /* IE < 8 doesn't support inline-block on native block-level elements */
    *display: inline;
    *zoom: 1;

    /* The interesting bit */
    line-height: [height]px;
    vertical-align: middle;
}

If the content of the child is expected to wrap onto multiple lines, you can wrap it in a sub-child that resets the line-height.


问:
Travis fails to build Android project, no local.properties
Here is the thing. I've built my project on the Travis CI several times, but got the same problem every time.

The error log:

What went wrong:
A problem occurred evaluating root project 'LiteReader'.
/home/travis/build/Mindjet/LiteReader/local.properties (No such file or directory)

It's true that the project I uploaded has no local.properties, I've excluded it because it contains information specific to local configuration.

It's my .travis.yml

```<code>language: android
cache: bundler

android:
  components:
    - tools
    - build-tools-25.0.2
    - android-25
    - extra-android-m2repository
    - extra-android-support

before_install:
  - chmod +x gradlew

script:
      ./gradlew checkstyle build
</code>```

How can I solve this problem? Please help, Thanks.

答:
I am using CircleCI instead of Travis but I had the same problem :)
I fixed it like this, it should do the trick for you, if you can do something like that in Travis (I don't see a reason why you couldn't).

TL;DR

Create the "local.properties.ci" in the same directory of "local.properties"

Put fake data in it so the CI build can pass

Add it to Git

Add the code below in circle.yml:

checkout:
  post:
    - cp local.properties.ci local.properties

Body:
Here is the thing. I've built my project on the Travis CI several times, but got the same problem every time.

The error log:

What went wrong:
A problem occurred evaluating root project 'LiteReader'.
/home/travis/build/Mindjet/LiteReader/local.properties (No such file or directory)

It's true that the project I uploaded has no local.properties, I've excluded it because it contains information specific to local configuration.

It's my .travis.yml

language: android
cache: bundler

android:
  components:
    - tools
    - build-tools-25.0.2
    - android-25
    - extra-android-m2repository
    - extra-android-support

before_install:
  - chmod +x gradlew

script:
      ./gradlew checkstyle build

How can I solve this problem? Please help, Thanks.


答:
Are you aware that the scanner and an integer are sharing the same name?

```<code>int x;
Scanner x = new Scanner(System.in);
</code>```

That is invalid in Java. Think about using a more descriptive name for the scanner.

Title: Sum two integers in Java

Body:
Are you aware that the scanner and an integer are sharing the same name?

int x;
Scanner x = new Scanner(System.in);

That is invalid in Java. Think about using a more descriptive name for the scanner.