问:
Save two images as a single image in android
I have an image view in android and on that image view i have another image view.. Both image views contain two different images.. Now i want to save it as a single JPG image in my phone gallery.. So how can i do that??
I tried some code but it is not working.

Here is my code.

XML File:

```<code>    <ImageView
        android:id="@+id/innerImage"
        android:layout_width="300dp"
        android:layout_height="230dp"
        android:layout_centerInParent="true"
        android:layout_centerVertical="true"
        android:contentDescription="@android:string/untitled"
        android:background="@drawable/white"/>

    <Button
        android:id="@+id/btnselectPhoto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/ivImage"
        android:layout_alignLeft="@+id/ivImage"
        android:layout_marginBottom="16dp"
        android:text="@string/select_photo" />

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:contentDescription="@android:string/untitled" />

    <Button
        android:id="@+id/btnsave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/btnselectPhoto"
        android:layout_alignBottom="@id/btnselectPhoto"
        android:layout_alignRight="@+id/ivImage"
        android:layout_marginLeft="32dp"
        android:layout_toRightOf="@id/btnselectPhoto"
        android:text="@string/save" />
</code>```

And here is my Java Code:

```<code>public class MainActivity extends ActionBarActivity {

    private static String mTempDir;
    Bitmap mBackImage, mTopImage, mBackground, mNewSaving;
    Canvas mComboImage;
    FileOutputStream mFileOutputStream;
    BitmapDrawable mBitmapDrawable;
    private String mCurrent = null;

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

        // Call method for selecting Image
        SelectImage();
    }

    // method for selecting image
    private void SelectImage() {
        // items to put in alert box
        final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };

        // Alert box
        final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Add Photo");

        // Click Event of button
        Button btn = (Button) findViewById(R.id.btnselectPhoto);
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Set items in alert box
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        // Start Camara
                        if (items[item].equals("Take Photo")) {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));

                            startActivityForResult(intent, 1);
                        }
                        // Open Gallery
                        else if (items[item].equals("Choose from Library")) {
                            Intent intent = new Itent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            intent.setType("image/*");
                            startActivityForResult(intent, 2);
                        }
                        // Cancel code
                        else if (items[item].equals("Cancel")) {
                            dialog.dismiss();
                        }
                    }
                });
                builder.show();
            }
        });
    }

    // This method is called for setting image in imageview.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final String picturePath;
        ImageView iv = (ImageView) findViewById(R.id.innerImage);

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                File f = new File(Environment.getExternalStorageDirectory().toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bm;
                    BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
                    bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);
                    // bm = Bitmap.createScaledBitmap(bm, 70, 70, true);

                    iv.setImageBitmap(bm);

                    String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
                    f.delete();
                    OutputStream fOut = null;
                    File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                    try {
                        fOut = new FileOutputStream(file);
                        bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                        fOut.flush();
                        fOut.close();
                    }
                    catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
            else if (requestCode == 2) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                picturePath = cursor.getString(columnIndex);
                cursor.close();
                // Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
                saveimage(picturePath);
            }
        }
    }

    private void saveimage(String imgPath) {
        mTempDir = Environment.getExternalStorageDirectory() + "/" + "Demo" + "/";
        File mTempFile = new File(mTempDir);
        if (!mTempFile.exists()) {
            mTempFile.mkdirs();
        }
        mCurrent = "temp.png";

        mBackground = Bitmap.createBitmap(604, 1024, Bitmap.Config.ARGB_8888);
        mBackImage = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
        mTopImage = BitmapFactory.decodeFile(imgPath);
        mComboImage = new Canvas(mBackground);
        mComboImage.drawBitmap(mBackImage, 0f, 0f, null);
        mComboImage.drawBitmap(mTopImage, 0f, 0f, null);

        Button savebtn = (Button) findViewById(R.id.btnsave);
        savebtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                try {
                    mBitmapDrawable = new BitmapDrawable(getResources(), mBackground);
                    mNewSaving = ((BitmapDrawable) mBitmapDrawable).getBitmap();
                    String FtoSave = mTempDir + mCurrent;
                    File mFile = new File(FtoSave);
                    mFileOutputStream = new FileOutputStream(mFile);
                    mNewSaving.compress(CompressFormat.PNG, 95, mFileOutputStream);
                    mFileOutputStream.flush();
                    mFileOutputStream.close();
                }
                catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
</code>```

答:
```<code>  LinearLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.layout2);
   ll=(LinearLayout)findViewById(R.id.linearlayout);

 //Add button in your layout and write the below code onclick of button.
button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

    ll.setDrawingCacheEnabled(true);
    Bitmap bitmap = ll.getDrawingCache();

    String root = Environment.getExternalStorageDirectory().toString();
    File newDir = new File(root + "/saved_picture");
    newDir.mkdirs();
    Random gen = new Random();
    int n = 10000;
    n = gen.nextInt(n);
    String fotoname = n + ".jpg";
    File file = new File(newDir, fotoname);
    String s = file.getAbsolutePath();
    System.err.print("Path of saved image." + s);

    try {
        FileOutputStream out = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    } catch (Exception e) {

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

Body:
I have an image view in android and on that image view i have another image view.. Both image views contain two different images.. Now i want to save it as a single JPG image in my phone gallery.. So how can i do that??
I tried some code but it is not working.

Here is my code.

XML File:

    <ImageView
        android:id="@+id/innerImage"
        android:layout_width="300dp"
        android:layout_height="230dp"
        android:layout_centerInParent="true"
        android:layout_centerVertical="true"
        android:contentDescription="@android:string/untitled"
        android:background="@drawable/white"/>

    <Button
        android:id="@+id/btnselectPhoto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/ivImage"
        android:layout_alignLeft="@+id/ivImage"
        android:layout_marginBottom="16dp"
        android:text="@string/select_photo" />

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:contentDescription="@android:string/untitled" />

    <Button
        android:id="@+id/btnsave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@id/btnselectPhoto"
        android:layout_alignBottom="@id/btnselectPhoto"
        android:layout_alignRight="@+id/ivImage"
        android:layout_marginLeft="32dp"
        android:layout_toRightOf="@id/btnselectPhoto"
        android:text="@string/save" />

And here is my Java Code:

public class MainActivity extends ActionBarActivity {

    private static String mTempDir;
    Bitmap mBackImage, mTopImage, mBackground, mNewSaving;
    Canvas mComboImage;
    FileOutputStream mFileOutputStream;
    BitmapDrawable mBitmapDrawable;
    private String mCurrent = null;

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

        // Call method for selecting Image
        SelectImage();
    }

    // method for selecting image
    private void SelectImage() {
        // items to put in alert box
        final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };

        // Alert box
        final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Add Photo");

        // Click Event of button
        Button btn = (Button) findViewById(R.id.btnselectPhoto);
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Set items in alert box
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        // Start Camara
                        if (items[item].equals("Take Photo")) {
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));

                            startActivityForResult(intent, 1);
                        }
                        // Open Gallery
                        else if (items[item].equals("Choose from Library")) {
                            Intent intent = new Itent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            intent.setType("image/*");
                            startActivityForResult(intent, 2);
                        }
                        // Cancel code
                        else if (items[item].equals("Cancel")) {
                            dialog.dismiss();
                        }
                    }
                });
                builder.show();
            }
        });
    }

    // This method is called for setting image in imageview.
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final String picturePath;
        ImageView iv = (ImageView) findViewById(R.id.innerImage);

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                File f = new File(Environment.getExternalStorageDirectory().toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bm;
                    BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
                    bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);
                    // bm = Bitmap.createScaledBitmap(bm, 70, 70, true);

                    iv.setImageBitmap(bm);

                    String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
                    f.delete();
                    OutputStream fOut = null;
                    File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                    try {
                        fOut = new FileOutputStream(file);
                        bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                        fOut.flush();
                        fOut.close();
                    }
                    catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
            else if (requestCode == 2) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                picturePath = cursor.getString(columnIndex);
                cursor.close();
                // Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
                iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
                saveimage(picturePath);
            }
        }
    }

    private void saveimage(String imgPath) {
        mTempDir = Environment.getExternalStorageDirectory() + "/" + "Demo" + "/";
        File mTempFile = new File(mTempDir);
        if (!mTempFile.exists()) {
            mTempFile.mkdirs();
        }
        mCurrent = "temp.png";

        mBackground = Bitmap.createBitmap(604, 1024, Bitmap.Config.ARGB_8888);
        mBackImage = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
        mTopImage = BitmapFactory.decodeFile(imgPath);
        mComboImage = new Canvas(mBackground);
        mComboImage.drawBitmap(mBackImage, 0f, 0f, null);
        mComboImage.drawBitmap(mTopImage, 0f, 0f, null);

        Button savebtn = (Button) findViewById(R.id.btnsave);
        savebtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                try {
                    mBitmapDrawable = new BitmapDrawable(getResources(), mBackground);
                    mNewSaving = ((BitmapDrawable) mBitmapDrawable).getBitmap();
                    String FtoSave = mTempDir + mCurrent;
                    File mFile = new File(FtoSave);
                    mFileOutputStream = new FileOutputStream(mFile);
                    mNewSaving.compress(CompressFormat.PNG, 95, mFileOutputStream);
                    mFileOutputStream.flush();
                    mFileOutputStream.close();
                }
                catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}


来源: stackexchange

问:
git pull fails "unable to resolve reference" "unable to update local ref"
Using git 1.6.4.2, when I tried a git pull I get this error:

```<code>error: unable to resolve reference refs/remotes/origin/LT558-optimize-sql: No such file or directory
From git+ssh://remoteserver/~/misk5
 ! [new branch]      LT558-optimize-sql -> origin/LT558-optimize-sql  (unable to update local ref)
error: unable to resolve reference refs/remotes/origin/split-css: No such file or directory
 ! [new branch]      split-css  -> origin/split-css  (unable to update local ref)
</code>```

I've tried git remote prune origin, but it didn't help.

答:
Execute the following commands:

```<code>rm .git/refs/remotes/origin/master

git fetch

git branch --set-upstream-to=origin/master
</code>```

Just in case, if you need to know what is
  .git/refs/remotes/origin/master, you would read the Remotes section
  in Git References.

ContentLicense: CC BY-SA 4.0

Body:
Using git 1.6.4.2, when I tried a git pull I get this error:

error: unable to resolve reference refs/remotes/origin/LT558-optimize-sql: No such file or directory
From git+ssh://remoteserver/~/misk5
 ! [new branch]      LT558-optimize-sql -> origin/LT558-optimize-sql  (unable to update local ref)
error: unable to resolve reference refs/remotes/origin/split-css: No such file or directory
 ! [new branch]      split-css  -> origin/split-css  (unable to update local ref)

I've tried git remote prune origin, but it didn't help.

Body:
Execute the following commands:

rm .git/refs/remotes/origin/master

git fetch

git branch --set-upstream-to=origin/master

Just in case, if you need to know what is
  .git/refs/remotes/origin/master, you would read the Remotes section
  in Git References.

ContentLicense: CC BY-SA 3.0


问:
Android Textview Scrolling Issue
Firstly, I am new to android so if I have missed something basic I do apologise.

I have created a GridView to store some information. The GridView consists of a 3x6 grid. In each cell, there is an image and text directly under the image. As the GridView is so large I have implemented a scrollbar.

This is how the page should look normally and is when first loaded/selected :

Everything looks wonderful, however, when I scroll down to the bottom and then back up, the text seems to wrap up and then push the image out of place. I am not sure why this is?

This is how the page looks after I have scrolled down and they scroll back up :

For the GridView, I have an XML file with the GridView itself along with a TextView at the very top called content_rewards.xml. I have also create an XML file for each picture/text in the grid itself called relics_gridlayout.xml. I believe I am probably missing a property of the TextViews in either one of these files, however, I am not sure which one or which property. I don't think it has anything to do with the grid or adapter itself hence I will not include that code.

content_rewards.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:fitsSystemWindows="true"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="25dp">

<GridView
    android:id="@+id/customgrid"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_below="@+id/os_texts"
    android:columnWidth="100dp"
    android:numColumns="auto_fit"
    android:stretchMode="spacingWidthUniform"
    android:verticalSpacing="35dp"
    android:scrollbars="horizontal"
    tools:layout_constraintTop_creator="1"
    android:layout_marginTop="116dp"
    tools:layout_constraintLeft_creator="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>

<TextView
    android:id="@+id/textView4"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="B = 0   S = 0   G = 0"
    android:textSize="24sp"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintBottom_creator="1"
    app:layout_constraintBottom_toTopOf="@+id/customgrid"
    app:layout_constraintRight_toRightOf="parent"
    tools:layout_constraintLeft_creator="1"
    android:layout_marginBottom="8dp"
    app:layout_constraintLeft_toLeftOf="parent"/>
</android.support.constraint.ConstraintLayout>
</code>```

relics_gridlayout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="3dp">

<ImageView
    android:id="@+id/os_images"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@mipmap/ic_launcher" />

<TextView
    android:layout_below="@+id/os_images"
    android:id="@+id/os_texts"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="This is Just Dummy Text"
    android:textAlignment="center"
    android:textSize="18dp"
    android:textStyle="bold"/>

</RelativeLayout>
</code>```

Any help would be great. Thanks.

答:
This is a problem that i faced as well , the only solution that i could come up with was hardcoding the height of the grid item.

```<code> <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:padding="3dp">
</code>```

A better option would be to use recycler view with a grid layout manager.

Title: Android Textview Scrolling Issue

Body:
Firstly, I am new to android so if I have missed something basic I do apologise.

I have created a GridView to store some information. The GridView consists of a 3x6 grid. In each cell, there is an image and text directly under the image. As the GridView is so large I have implemented a scrollbar.

This is how the page should look normally and is when first loaded/selected :

Everything looks wonderful, however, when I scroll down to the bottom and then back up, the text seems to wrap up and then push the image out of place. I am not sure why this is?

This is how the page looks after I have scrolled down and they scroll back up :

For the GridView, I have an XML file with the GridView itself along with a TextView at the very top called content_rewards.xml. I have also create an XML file for each picture/text in the grid itself called relics_gridlayout.xml. I believe I am probably missing a property of the TextViews in either one of these files, however, I am not sure which one or which property. I don't think it has anything to do with the grid or adapter itself hence I will not include that code.

content_rewards.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:fitsSystemWindows="true"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="25dp">

<GridView
    android:id="@+id/customgrid"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_below="@+id/os_texts"
    android:columnWidth="100dp"
    android:numColumns="auto_fit"
    android:stretchMode="spacingWidthUniform"
    android:verticalSpacing="35dp"
    android:scrollbars="horizontal"
    tools:layout_constraintTop_creator="1"
    android:layout_marginTop="116dp"
    tools:layout_constraintLeft_creator="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>

<TextView
    android:id="@+id/textView4"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="B = 0   S = 0   G = 0"
    android:textSize="24sp"
    tools:layout_constraintRight_creator="1"
    tools:layout_constraintBottom_creator="1"
    app:layout_constraintBottom_toTopOf="@+id/customgrid"
    app:layout_constraintRight_toRightOf="parent"
    tools:layout_constraintLeft_creator="1"
    android:layout_marginBottom="8dp"
    app:layout_constraintLeft_toLeftOf="parent"/>
</android.support.constraint.ConstraintLayout>

relics_gridlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="3dp">

<ImageView
    android:id="@+id/os_images"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@mipmap/ic_launcher" />

<TextView
    android:layout_below="@+id/os_images"
    android:id="@+id/os_texts"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="This is Just Dummy Text"
    android:textAlignment="center"
    android:textSize="18dp"
    android:textStyle="bold"/>

</RelativeLayout>

Any help would be great. Thanks.

Body:
This is a problem that i faced as well , the only solution that i could come up with was hardcoding the height of the grid item.

 <RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:padding="3dp">

A better option would be to use recycler view with a grid layout manager.


问:
Passing bitwise operation as argument to function in C
What will be the argument value if we call function with the following argument

```<code>void func((0x1 | 0x3))
</code>```

Is it true that if the result of this operation is >0 it gives true, and for the opposite it gives false, or we get 0x3 as a return value of this operation?

答: | is the bitwise operation so the result will be 3

Body:
What will be the argument value if we call function with the following argument

void func((0x1 | 0x3))

Is it true that if the result of this operation is >0 it gives true, and for the opposite it gives false, or we get 0x3 as a return value of this operation?


问:
Lagom PubSubRef subscriber drops messages
[Attention] The question is Lagom framework specific!

In my current project, the problem with cutting the list of messages from Source to Kafka topic publisher has been observed when upstream is of high speed and looks like downstream can't handle all messages in time. As realized, the cutting is related to the behavior of PubSubRef.subscribe() method https://github.com/lagom/lagom/blob/master/pubsub/javadsl/src/main/scala/com/lightbend/lagom/javadsl/pubsub/PubSubRef.scala#L85

The full method definition:

```<code>def subscriber(): Source[T, NotUsed] = {
scaladsl.Source.actorRef[T](bufferSize, OverflowStrategy.dropHead)
  .mapMaterializedValue { ref =>
    mediator ! Subscribe(topic.name, ref)
    NotUsed
  }.asJava
}
</code>```

There's OverflowStrategy.dropHead is used. Can it be changed to use back-pressure strategy?

UPD#1:
The use case is pretty simple, when a query request is published into command topic, get it and query objects from DB table, the resulting list is pushed into result Kafka topic. Code snippet:

```<code>objectsResultTopic = pubSub.refFor(TopicId.of(CustomObject.class, OBJECTS_RESULT_TOPIC));
objectQueryTopic().subscribe().atLeastOnce(
Flow.fromSinkAndSource(
    Flow.fromFunction(this::deserializeCommandAndQueryObjects)
        .mapAsync(concurrency, objects -> objects)
        .flatMapMerge(concurrency, objects -> objects)
        .alsoTo(Sink.foreach(event -> LOG.trace("Sending object {}", object)))
        .to(objectsResultTopic.publisher()),
    Source.repeat(Done.getInstance())
    )
)
</code>```

In case of objects stream generated by deserializeCommandAndQueryObjects function is more than default buffer-size = 1000 it starts cutting the elements (our case is ~ 2.5k objects).

UPD#2:
The source of objects data is:

```<code>// returns CompletionStage<Source<CustomObject, ?>>
jdbcSession.withConnection(
  connection -> Source.from(runQuery(connection, rowConverter))
)
</code>```

And there's a subscription to Kafka objectsResultTopic:

```<code>TopicProducer.singleStreamWithOffset(
offset -> objectsResultTopic.subscriber().map(gm -> {
    JsonNode node = mapper.convertValue(gm, JsonNode.class);
    return Pair.create(node, offset);
}));
</code>```

答:
If someone is interested, finally we solved that problem by using Akka Producer API, like:

```<code>ProducerSettings<String, CustomObject> producerSettings = ProducerSettings.create(system, new StringSerializer(), new CustomObjectSerializer());
objectQueryTopic().subscribe().atLeastOnce(
Flow.fromSinkAndSource(
    Flow.fromFunction(this::deserializeCommandAndQueryObjects)
        .mapAsync(concurrency, objects -> objects)
        .flatMapMerge(concurrency, objects -> objects)
        .alsoTo(Sink.foreach(object -> LOG.trace("Sending event {}", object)))
        .map(object -> new ProducerRecord<String, CustomObject>(OBJECTS_RESULT_TOPIC, object))
        .to(Producer.plainSink(producerSettings)),
    Source.repeat(Done.getInstance())));
</code>```

It works without buffering, just makes the pushing into Kafka topic.

Body:
[Attention] The question is Lagom framework specific!

In my current project, the problem with cutting the list of messages from Source to Kafka topic publisher has been observed when upstream is of high speed and looks like downstream can't handle all messages in time. As realized, the cutting is related to the behavior of PubSubRef.subscribe() method https://github.com/lagom/lagom/blob/master/pubsub/javadsl/src/main/scala/com/lightbend/lagom/javadsl/pubsub/PubSubRef.scala#L85

The full method definition:

def subscriber(): Source[T, NotUsed] = {
scaladsl.Source.actorRef[T](bufferSize, OverflowStrategy.dropHead)
  .mapMaterializedValue { ref =>
    mediator ! Subscribe(topic.name, ref)
    NotUsed
  }.asJava
}

There's OverflowStrategy.dropHead is used. Can it be changed to use back-pressure strategy?

UPD#1:
The use case is pretty simple, when a query request is published into command topic, get it and query objects from DB table, the resulting list is pushed into result Kafka topic. Code snippet:

objectsResultTopic = pubSub.refFor(TopicId.of(CustomObject.class, OBJECTS_RESULT_TOPIC));
objectQueryTopic().subscribe().atLeastOnce(
Flow.fromSinkAndSource(
    Flow.fromFunction(this::deserializeCommandAndQueryObjects)
        .mapAsync(concurrency, objects -> objects)
        .flatMapMerge(concurrency, objects -> objects)
        .alsoTo(Sink.foreach(event -> LOG.trace("Sending object {}", object)))
        .to(objectsResultTopic.publisher()),
    Source.repeat(Done.getInstance())
    )
)

In case of objects stream generated by deserializeCommandAndQueryObjects function is more than default buffer-size = 1000 it starts cutting the elements (our case is ~ 2.5k objects).

UPD#2:
The source of objects data is:

// returns CompletionStage<Source<CustomObject, ?>>
jdbcSession.withConnection(
  connection -> Source.from(runQuery(connection, rowConverter))
)

And there's a subscription to Kafka objectsResultTopic:

TopicProducer.singleStreamWithOffset(
offset -> objectsResultTopic.subscriber().map(gm -> {
    JsonNode node = mapper.convertValue(gm, JsonNode.class);
    return Pair.create(node, offset);
}));

Body:
If someone is interested, finally we solved that problem by using Akka Producer API, like:

ProducerSettings<String, CustomObject> producerSettings = ProducerSettings.create(system, new StringSerializer(), new CustomObjectSerializer());
objectQueryTopic().subscribe().atLeastOnce(
Flow.fromSinkAndSource(
    Flow.fromFunction(this::deserializeCommandAndQueryObjects)
        .mapAsync(concurrency, objects -> objects)
        .flatMapMerge(concurrency, objects -> objects)
        .alsoTo(Sink.foreach(object -> LOG.trace("Sending event {}", object)))
        .map(object -> new ProducerRecord<String, CustomObject>(OBJECTS_RESULT_TOPIC, object))
        .to(Producer.plainSink(producerSettings)),
    Source.repeat(Done.getInstance())));

It works without buffering, just makes the pushing into Kafka topic.


问:
MS SAPI 5.1 issue with C++
I am using MS Speech API 5.1 with mingw compiler. I don't have VS hence but I was able to compile the code with c::b.
The code snippet is below:

```<code>#include <sapi.h>

int main(int argc, char* argv[])
{
    ISpVoice * pVoice = NULL;

    if (FAILED(::CoInitialize(NULL)))
        return FALSE;

    HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
    if( SUCCEEDED( hr ) )
    {
        hr = pVoice->Speak(L"Hello world", 0, NULL);
        pVoice->Release();
        pVoice = NULL;
    }

    ::CoUninitialize();
    return TRUE;
}
</code>```

When I execute I found

```<code>hr = pVoice->Speak(L"Hello world", 0, NULL);
</code>```

returning NULL. After looking around for a while, I ran the example TTSApp.exe from the MS SAPI folder. By default the voice was selected as "Microsoft Marry". When I type a text and click Start, no speech sound is produce and I got "Speak error". When I changed the voice to "Microsoft Anna - English (United States)", it worked.

I do not know if I am thinking correct, but is the code of mine also failing because of a wrong/default voice selection ("Microsoft Marry")? Is there any way I can change the voice to "Microsoft Anna - English (United States)" for testing?

I need you help here. Can you help me get the SAPI working fro the above code?

Thanks!

答:
Since this is a microsoft specific question.
I use some vb mixed within some system() calls it results in much simpler code.
I haven't cleaned it up, but it works well

```<code>int say(std::string s)
{

string part1content;
string part2content;
string word,complete;
const char * temp2="WScript.exe Scrpt.vbs";
const char * temp="Scrpt.vbs";

string pat1=(
"\'By Timbo\n\n\
Const SVSFlagsAsync = 1\n\
const SVSFPurgeBeforeSpeak =2\n\n\
Dim Speech\n\
Dim FSO\n\n\
CreateObjects\n\
Main\n\
DestroyObjects\n\
Quit\n\n\
Sub Main\n\
        Dim sText\n\n\
        sText = (\""
             );
string pat2=
(
"\")\n\
    Speech.rate = 0.05\n\
        If sText <> \"\" Then\n\
                SpeakText sText\n\n\
        End If\n\
End Sub\n\n\
Sub SpeakText(sText)\n\
        On Error Resume Next\n\
        Speech.Speak sText, SVSFlagsAsync + SVSFPurgeBeforeSpeak\n\
        Do\n\
                Sleep 200\n\
        Loop Until Speech.WaitUntilDone(10)\n\
End Sub\n\n\
Sub StopSpeaking()\n\
        On Error Resume Next\n\
        Speech.Speak vbNullString, SVSFPurgeBeforeSpeak\n\
        Set Speech = Nothing\n\
End Sub\n\n\
Sub CreateObjects\n\
        Set Speech = CreateObject(\"SAPI.SpVoice\")\n\
        Set FSO = CreateObject(\"Scripting.FileSystemObject\")\n\
End Sub\n\n\
Sub DestroyObjects\n\
        Set Speech = Nothing\n\
        Set FSO = Nothing\n\
End Sub\n\n\
Sub Sleep(nTimeout)\n\
        WScript.Sleep nTimeout\n\
End Sub\n\n\
Sub Quit\n\
        WScript.Quit\n\
End Sub\n\n\
"

);

    /*Will say string s*/

    complete=pat1+s+pat2;

    ofstream myfile;
    myfile.open (temp);
    myfile << complete;
    myfile.close();
    system(temp2);
    complete.clear();
    s.clear();
}
</code>```

For different voice Change pat2 with

```<code>string pat2=
(
"\")\n\
    Speech.rate = 0.05\n\
        If sText <> \"\" Then\n\
                SpeakText sText\n\n\
        End If\n\
End Sub\n\n\
Sub SpeakText(sText)\n\
        On Error Resume Next\n\
        Speech.Speak sText, SVSFlagsAsync + SVSFPurgeBeforeSpeak\n\
        Do\n\
                Sleep 200\n\
        Loop Until Speech.WaitUntilDone(10)\n\
End Sub\n\n\
Sub StopSpeaking()\n\
        On Error Resume Next\n\
        Speech.Speak vbNullString, SVSFPurgeBeforeSpeak\n\
        Set Speech = Nothing\n\
End Sub\n\n\
Sub CreateObjects\n\
        Set Speech = CreateObject(\"SAPI.SpVoice\")\n\
        with Speech \n\
            Set .voice = .getvoices.item(1)\n\
            .Volume = 100\n\
            .Rate = 4\n\
        end with\n\
        Set FSO = CreateObject(\"Scripting.FileSystemObject\")\n\
End Sub\n\n\
Sub DestroyObjects\n\
        Set Speech = Nothing\n\
        Set FSO = Nothing\n\
End Sub\n\n\
Sub Sleep(nTimeout)\n\
        WScript.Sleep nTimeout\n\
End Sub\n\n\
Sub Quit\n\
        WScript.Quit\n\
End Sub\n\n\
"
);
</code>```

Then you can just use it simply by calling say("This is a test");

For more control you can use pipes instead of sytem() , this will enable you to kill the vbscript process if you want to stop it.

Title: MS SAPI 5.1 issue with C++

Body:
I am using MS Speech API 5.1 with mingw compiler. I don't have VS hence but I was able to compile the code with c::b.
The code snippet is below:

#include <sapi.h>

int main(int argc, char* argv[])
{
    ISpVoice * pVoice = NULL;

    if (FAILED(::CoInitialize(NULL)))
        return FALSE;

    HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
    if( SUCCEEDED( hr ) )
    {
        hr = pVoice->Speak(L"Hello world", 0, NULL);
        pVoice->Release();
        pVoice = NULL;
    }

    ::CoUninitialize();
    return TRUE;
}

When I execute I found

hr = pVoice->Speak(L"Hello world", 0, NULL);

returning NULL. After looking around for a while, I ran the example TTSApp.exe from the MS SAPI folder. By default the voice was selected as "Microsoft Marry". When I type a text and click Start, no speech sound is produce and I got "Speak error". When I changed the voice to "Microsoft Anna - English (United States)", it worked.

I do not know if I am thinking correct, but is the code of mine also failing because of a wrong/default voice selection ("Microsoft Marry")? Is there any way I can change the voice to "Microsoft Anna - English (United States)" for testing?

I need you help here. Can you help me get the SAPI working fro the above code?

Thanks!

Body:
Since this is a microsoft specific question.
I use some vb mixed within some system() calls it results in much simpler code.
I haven't cleaned it up, but it works well

int say(std::string s)
{

string part1content;
string part2content;
string word,complete;
const char * temp2="WScript.exe Scrpt.vbs";
const char * temp="Scrpt.vbs";

string pat1=(
"\'By Timbo\n\n\
Const SVSFlagsAsync = 1\n\
const SVSFPurgeBeforeSpeak =2\n\n\
Dim Speech\n\
Dim FSO\n\n\
CreateObjects\n\
Main\n\
DestroyObjects\n\
Quit\n\n\
Sub Main\n\
        Dim sText\n\n\
        sText = (\""
             );
string pat2=
(
"\")\n\
    Speech.rate = 0.05\n\
        If sText <> \"\" Then\n\
                SpeakText sText\n\n\
        End If\n\
End Sub\n\n\
Sub SpeakText(sText)\n\
        On Error Resume Next\n\
        Speech.Speak sText, SVSFlagsAsync + SVSFPurgeBeforeSpeak\n\
        Do\n\
                Sleep 200\n\
        Loop Until Speech.WaitUntilDone(10)\n\
End Sub\n\n\
Sub StopSpeaking()\n\
        On Error Resume Next\n\
        Speech.Speak vbNullString, SVSFPurgeBeforeSpeak\n\
        Set Speech = Nothing\n\
End Sub\n\n\
Sub CreateObjects\n\
        Set Speech = CreateObject(\"SAPI.SpVoice\")\n\
        Set FSO = CreateObject(\"Scripting.FileSystemObject\")\n\
End Sub\n\n\
Sub DestroyObjects\n\
        Set Speech = Nothing\n\
        Set FSO = Nothing\n\
End Sub\n\n\
Sub Sleep(nTimeout)\n\
        WScript.Sleep nTimeout\n\
End Sub\n\n\
Sub Quit\n\
        WScript.Quit\n\
End Sub\n\n\
"

);

    /*Will say string s*/

    complete=pat1+s+pat2;

    ofstream myfile;
    myfile.open (temp);
    myfile << complete;
    myfile.close();
    system(temp2);
    complete.clear();
    s.clear();
}

For different voice Change pat2 with

string pat2=
(
"\")\n\
    Speech.rate = 0.05\n\
        If sText <> \"\" Then\n\
                SpeakText sText\n\n\
        End If\n\
End Sub\n\n\
Sub SpeakText(sText)\n\
        On Error Resume Next\n\
        Speech.Speak sText, SVSFlagsAsync + SVSFPurgeBeforeSpeak\n\
        Do\n\
                Sleep 200\n\
        Loop Until Speech.WaitUntilDone(10)\n\
End Sub\n\n\
Sub StopSpeaking()\n\
        On Error Resume Next\n\
        Speech.Speak vbNullString, SVSFPurgeBeforeSpeak\n\
        Set Speech = Nothing\n\
End Sub\n\n\
Sub CreateObjects\n\
        Set Speech = CreateObject(\"SAPI.SpVoice\")\n\
        with Speech \n\
            Set .voice = .getvoices.item(1)\n\
            .Volume = 100\n\
            .Rate = 4\n\
        end with\n\
        Set FSO = CreateObject(\"Scripting.FileSystemObject\")\n\
End Sub\n\n\
Sub DestroyObjects\n\
        Set Speech = Nothing\n\
        Set FSO = Nothing\n\
End Sub\n\n\
Sub Sleep(nTimeout)\n\
        WScript.Sleep nTimeout\n\
End Sub\n\n\
Sub Quit\n\
        WScript.Quit\n\
End Sub\n\n\
"
);

Then you can just use it simply by calling say("This is a test");

For more control you can use pipes instead of sytem() , this will enable you to kill the vbscript process if you want to stop it.


问:
Convert simple array into two-dimensional array (matrix)
Imagine I have an array:

```<code>A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9);
</code>```

And I want it to convert into 2-dimensional array (matrix of N x M), for instance like this:

```<code>A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9));
</code>```

Note, that rows and columns of the matrix is changeable.

答:
Simply use two for loops:</p>

```<code>var rowNum = 3;
var colNum = 3;
var k = 0;
var dest = new Array(rowNum);

for (i=0; i<rowNum; ++i) {
  var tmp = new Array(colNum);
  for (j=0; j<colNum; ++j) {
    tmp[j] = src[k];
    k++;
  }
  dest[i] = tmp;
}
</code>```

Body:
Imagine I have an array:

A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9);

And I want it to convert into 2-dimensional array (matrix of N x M), for instance like this:

A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9));

Note, that rows and columns of the matrix is changeable.

Body:
Simply use two for loops:

var rowNum = 3;
var colNum = 3;
var k = 0;
var dest = new Array(rowNum);

for (i=0; i<rowNum; ++i) {
  var tmp = new Array(colNum);
  for (j=0; j<colNum; ++j) {
    tmp[j] = src[k];
    k++;
  }
  dest[i] = tmp;
}

ContentLicense: CC BY-SA 2.5


问:
How to get LatLng of Touch on Leaflet
I'd like to get the LatLng of the touchpoint in a touchmove event (leaflet map). I didn't find a way to solve this. Are there any ways to get the coordinates?</p>

```<code>$(document).on('touchmove', '#mapid', function(e) {
  //here i want to get the LatLng coordinates
)};
</code>```

答:
I see two approaches.

One is to use Leaflet's event handling, y doing something like map.on('mousemove', function(ev){ ... });.

That event handler will receive a Leaflet 'MouseEvent', which includes the LngLat of the point of the map where the event took place. See http://leafletjs.com/reference-1.1.0.html#map-event and http://leafletjs.com/reference-1.1.0.html#mouseevent. And yes, Leaflet listens to TouchEvents and PointerEvents when told to listen to MouseEvents.

The other approach is to use the map's containerPointToLatLng() conversion method, or the mouseEventToLatLng() method to turn a pixel coordinate or a mouse event into a LatLng.

Title: How to get LatLng of Touch on Leaflet

Body:
I'd like to get the LatLng of the touchpoint in a touchmove event (leaflet map). I didn't find a way to solve this. Are there any ways to get the coordinates?

$(document).on('touchmove', '#mapid', function(e) {
  //here i want to get the LatLng coordinates
)};


问:
The best suggestion for a structure to store multiple keys and values - dictionaries?
The intention is to create the beginnings of a facebook type program (For teaching purposes) that stores a list of names of individuals along with their bio details.

I have two questions, one follows on from the next:

Question 1: How to get at the list values that are part of a value in a key value pair in a dictionary. For instance, to find out what friends John and Mary have in common, in this case friend1 and friend3

Question 2: The best method to create a structure that stores names,gender,hobbies,and friends? Would this be a dictionary and if so, how could this be defined? If not, what do people suggest?

```<code>#create a dictionary that stores names, and a list of friends
facebook_profile={"John":["friend1","friend2","friend3","friend4"],"Mary":["friend1","friend7","friend3","friend9"]}
print(facebook_profile)
</code>```

Required to store and subsequently print the following sample data:

```<code>Name:John
Gender: Male
Hobbies: Chess
Friends: friend1,friend2,friend3,friend4

Name: Mary
Gender: Female
Hobbies: Chequers
Friends: friend1,friend2,friend3,friend4
</code>```

I am aware the best solution would be a database and to use some sort of file handling to achieve it however, for teaching purposes we are trying to use only lists or dictionaries. These dictionaries/lists could then be written to a file, but the solution(s)/answers I am looking for must ideally be utilising only the list and dictionary structures.

答:
Create a class:</p>

```<code>class Person:

  def __init__(self, name, gender, hobbies, friends):
    self.name = name
    self.gender = gender
    self.hobbies = hobbies
    self.friends = friends

  def getMutualFriends(self, personB):
    return list(set(personB.friends).intersection(self.friends))

person1 = Person('John', 'male', ['Chess'], ['friend1', 'friend2'])
person2 = Person('Anna', 'female', ['Soccer'], ['friend1', 'friend3'])

print(person1.getMutualFriends(person2))
</code>```

Body:
The intention is to create the beginnings of a facebook type program (For teaching purposes) that stores a list of names of individuals along with their bio details.

I have two questions, one follows on from the next:

Question 1: How to get at the list values that are part of a value in a key value pair in a dictionary. For instance, to find out what friends John and Mary have in common, in this case friend1 and friend3

Question 2: The best method to create a structure that stores names,gender,hobbies,and friends? Would this be a dictionary and if so, how could this be defined? If not, what do people suggest?

#create a dictionary that stores names, and a list of friends
facebook_profile={"John":["friend1","friend2","friend3","friend4"],"Mary":["friend1","friend7","friend3","friend9"]}
print(facebook_profile)

Required to store and subsequently print the following sample data:

Name:John
Gender: Male
Hobbies: Chess
Friends: friend1,friend2,friend3,friend4

Name: Mary
Gender: Female
Hobbies: Chequers
Friends: friend1,friend2,friend3,friend4

I am aware the best solution would be a database and to use some sort of file handling to achieve it however, for teaching purposes we are trying to use only lists or dictionaries. These dictionaries/lists could then be written to a file, but the solution(s)/answers I am looking for must ideally be utilising only the list and dictionary structures.

Body:
Create a class:

class Person:

  def __init__(self, name, gender, hobbies, friends):
    self.name = name
    self.gender = gender
    self.hobbies = hobbies
    self.friends = friends

  def getMutualFriends(self, personB):
    return list(set(personB.friends).intersection(self.friends))

person1 = Person('John', 'male', ['Chess'], ['friend1', 'friend2'])
person2 = Person('Anna', 'female', ['Soccer'], ['friend1', 'friend3'])

print(person1.getMutualFriends(person2))


问:
How to Find index of some value in passed array in Oracle query
I want to find index of column value in passed array for each row.
Finding if that value is presented in array is not enough because i want to compare that index with value of another column.

I expect something like this.

```<code>SELECT * FROM my_table t WHERE :argumentArray.indexOf(t.col1) BETWEEN 0 AND t.col2
</code>```

Maybe that will be possible if I convert that array to table or something like that.

Here is structure of my real example:
Below is hierarchy of employee tree.

```<code>          1000
          /  \
       1001  1002
       /        \
     1003       1004
     /
   1005
</code>```

I have table where I store document share information

```<code>document_id | shared_under | level
----------- | ------------ | ---------
123         | 1000         | 2
</code>```

this record means that document with id 123 is shared with employee with id 1000 and its children only by level 2. (employees with id 1000, 1001, 1002, 1003, 1004 can access that document and 1005 can not)

Desired result:

If employee 1005 searches documents, he passes his hierarchy as array argument, which is (1005, 1003, 1001, 1000)

query will look like:

```<code>SELECT `document_id` FROM `shared_documents` WHERE (1005, 1003, 1001, 1000).indexOf(shared_under) BETWEEN 0 AND `level`
</code>```

This query must return no data because emp.1005 is under emp.1000 on level 3 but document is shared only 2 level deep.

If emp.1003 searches for shared documents he passes (1003, 1001, 1000) and query must return document 123, because it is shared with employee 1000, and employee 1003 is under him within 2 level depth.

I have solved this problem with regex, but i wonder if Oracle supports this kind of solution.

答:
Use a table collection expression in a sub-query:

```<code>SELECT *
FROM   mytable t
WHERE  t.col1 IN ( SELECT COLUMN_VALUE
                   FROM   TABLE( :argumentArray )
                   WHERE  ROWNUM <= t."level" )
</code>```

Update with an example:

Oracle Setup:

```<code>CREATE TABLE mytable ( lvl, col1 ) AS
  SELECT 1, 'a' FROM DUAL UNION ALL
  SELECT 2, 'a' FROM DUAL UNION ALL
  SELECT 1, 'b' FROM DUAL UNION ALL
  SELECT 3, 'b' FROM DUAL;

CREATE OR REPLACE TYPE stringlist IS TABLE OF VARCHAR2(10);
/
</code>```

Query:

Calling this with a hard-coded collection but you can pass it in as a bind variable in PL/SQL or from other languages:

```<code>SELECT *
FROM   mytable t
WHERE  col1 IN ( SELECT COLUMN_VALUE
                 FROM   TABLE( stringlist( 'a', 'b' ) )
                 WHERE  ROWNUM <= t.lvl );
</code>```

Output:

```<code>LVL COL1
--- ----
  1 a
  2 a
  3 b
</code>```

Body:
I want to find index of column value in passed array for each row.
Finding if that value is presented in array is not enough because i want to compare that index with value of another column.

I expect something like this.

SELECT * FROM my_table t WHERE :argumentArray.indexOf(t.col1) BETWEEN 0 AND t.col2

Maybe that will be possible if I convert that array to table or something like that.

Here is structure of my real example:
Below is hierarchy of employee tree.

          1000
          /  \
       1001  1002
       /        \
     1003       1004
     /
   1005

I have table where I store document share information

document_id | shared_under | level
----------- | ------------ | ---------
123         | 1000         | 2

this record means that document with id 123 is shared with employee with id 1000 and its children only by level 2. (employees with id 1000, 1001, 1002, 1003, 1004 can access that document and 1005 can not)

Desired result:

If employee 1005 searches documents, he passes his hierarchy as array argument, which is (1005, 1003, 1001, 1000)

query will look like:

SELECT `document_id` FROM `shared_documents` WHERE (1005, 1003, 1001, 1000).indexOf(shared_under) BETWEEN 0 AND `level`

This query must return no data because emp.1005 is under emp.1000 on level 3 but document is shared only 2 level deep.

If emp.1003 searches for shared documents he passes (1003, 1001, 1000) and query must return document 123, because it is shared with employee 1000, and employee 1003 is under him within 2 level depth.

I have solved this problem with regex, but i wonder if Oracle supports this kind of solution.

Body:
Use a table collection expression in a sub-query:

SELECT *
FROM   mytable t
WHERE  t.col1 IN ( SELECT COLUMN_VALUE
                   FROM   TABLE( :argumentArray )
                   WHERE  ROWNUM <= t."level" )

Update with an example:

Oracle Setup:

CREATE TABLE mytable ( lvl, col1 ) AS
  SELECT 1, 'a' FROM DUAL UNION ALL
  SELECT 2, 'a' FROM DUAL UNION ALL
  SELECT 1, 'b' FROM DUAL UNION ALL
  SELECT 3, 'b' FROM DUAL;

CREATE OR REPLACE TYPE stringlist IS TABLE OF VARCHAR2(10);
/

Query:

Calling this with a hard-coded collection but you can pass it in as a bind variable in PL/SQL or from other languages:

SELECT *
FROM   mytable t
WHERE  col1 IN ( SELECT COLUMN_VALUE
                 FROM   TABLE( stringlist( 'a', 'b' ) )
                 WHERE  ROWNUM <= t.lvl );

Output:

LVL COL1
--- ----
  1 a
  2 a
  3 b


问:
A "No such file or directory" error occurs with the appscan.sh command
I am trying to generate .irx file using SAClientUtil.6.0.1142 in a Linux machine. However, when I execute the appscan.sh prepare -c <config file> -d <destination file> command, it throws an error like:

SAClientUtil.6.0.1142/bin/appscan.sh: line 75:
  /opt/SAClientUtil.6.0.1142/bin/..//jre/bin/java: No such file or
  directory

Anyone please help me.

答:
Looks like either you don't have a JRE installed on your linux system or it is not installed at path /opt/SAClientUtil.6.0.1142/bin/..//jre/bin/java.

java -version will tell you the java version if its installed, and which java will tell you the location where it is installed.


答:
```<code>function matrixify( source, count )
{
    var matrixified = [];
    var tmp;
    // iterate through the source array
    for( var i = 0; i < source.length; i++ )
    {
        // use modulous to make sure you have the correct length.
        if( i % count == 0 )
        {
            // if tmp exists, push it to the return array
            if( tmp && tmp.length ) matrixified.push(tmp);
            // reset the temporary array
            tmp = [];
        }
        // add the current source value to the temp array.
        tmp.push(source[i])
    }
    // return the result
    return matrixified;
}
</code>```

If you want to actually replace an array's internal values, I believe you can call the following:

```<code>source.splice(0, source.length, matrixify(source,3));
</code>```

Title: Convert simple array into two-dimensional array (matrix)

Body:
function matrixify( source, count )
{
    var matrixified = [];
    var tmp;
    // iterate through the source array
    for( var i = 0; i < source.length; i++ )
    {
        // use modulous to make sure you have the correct length.
        if( i % count == 0 )
        {
            // if tmp exists, push it to the return array
            if( tmp && tmp.length ) matrixified.push(tmp);
            // reset the temporary array
            tmp = [];
        }
        // add the current source value to the temp array.
        tmp.push(source[i])
    }
    // return the result
    return matrixified;
}

If you want to actually replace an array's internal values, I believe you can call the following:

source.splice(0, source.length, matrixify(source,3));


问:
React, Redux and Axios - trying to make API call
It's my first experience with React, Redux and I am totally lost. The problem is my action :

```<code>import axios from 'axios';
import { FETCH_MOVIE } from '../constants/actionTypes';
const API_KEY = <API_KEY>;
const ROOT_URL = `<API_URL>`;

export function fetchMovies(pop){

  const url = `${ROOT_URL}?api_key=${API_KEY}&sort_by=${pop}`;
  axios.get(url)
  .then(function (response) {
    console.log("response is",response)
  })
  .catch(function (error) {
    console.log(error);
  });

  return{
    type:  FETCH_MOVIE,
    payload: response.data
  };
}
</code>```

On Console.log it seems just fine - I can see the response has the data I need. But when I am trying to send response.data to payload it returns the error -  response is not defined. What am I doing wrong?

P.s. I also tried to create  const result = [] and than result = [...response.data]. The error was - SyntaxError: "result" is read-only

答:
The const error is because, result being a variable that changes over the course of the execution, you must use 'let' and not 'const'.

Now, for the fix, response is not defined comes from the last return. A good approach would be to, instead of returning the action on this function fetchMovies, you should dispatch a new action, e.g dispatch(fetchMoviesSuccess(payload)) instead of "console.log("response is",response)", which will dispatch an action that will trigger the reducer, and , in turn, update the state of the app.

Body:
It's my first experience with React, Redux and I am totally lost. The problem is my action :

import axios from 'axios';
import { FETCH_MOVIE } from '../constants/actionTypes';
const API_KEY = <API_KEY>;
const ROOT_URL = `<API_URL>`;

export function fetchMovies(pop){

  const url = `${ROOT_URL}?api_key=${API_KEY}&sort_by=${pop}`;
  axios.get(url)
  .then(function (response) {
    console.log("response is",response)
  })
  .catch(function (error) {
    console.log(error);
  });

  return{
    type:  FETCH_MOVIE,
    payload: response.data
  };
}

On Console.log it seems just fine - I can see the response has the data I need. But when I am trying to send response.data to payload it returns the error -  response is not defined. What am I doing wrong?

P.s. I also tried to create  const result = [] and than result = [...response.data]. The error was - SyntaxError: "result" is read-only


问:
Managing multiple Application classes- Volley + MultiDex
My app crossed the 65K limit after adding google play dependencies. So I had to enable multidex and add this to manifest

```<code>android:name="android.support.multidex.MultiDexApplication"
</code>```

But there is also a singleton class of volley that extends application since I need to get context of that class.

How can both be managed? Is there a way to make the volley class static? The volley class code is :

```<code>public class AppController extends Application {

public static final String TAG = AppController.class
        .getSimpleName();

private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public ImageLoader getImageLoader() {
    getRequestQueue();
    if (mImageLoader == null) {
        mImageLoader = new ImageLoader(this.mRequestQueue,
                new LruBitmapCache());
    }
    return this.mImageLoader;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    // set the default tag if tag is empty
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}
}
</code>```

And the usage of the class is :

```<code>AppController.getInstance().addToRequestQueue(strReq, "Making a request");
</code>```

If it can be made static then what should be the implementation of the class to make network calls?

答:
try this, just override this method in your Appcontroller class.link :How to use MultiDex with a custom Application class?</p>

```<code>               @Override
      protected void attachBaseContext(Context base)
      {
        super.attachBaseContext(base);
        MultiDex.install(this);
       }
</code>```

Body:
My app crossed the 65K limit after adding google play dependencies. So I had to enable multidex and add this to manifest

android:name="android.support.multidex.MultiDexApplication"

But there is also a singleton class of volley that extends application since I need to get context of that class.

How can both be managed? Is there a way to make the volley class static? The volley class code is :

public class AppController extends Application {

public static final String TAG = AppController.class
        .getSimpleName();

private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public ImageLoader getImageLoader() {
    getRequestQueue();
    if (mImageLoader == null) {
        mImageLoader = new ImageLoader(this.mRequestQueue,
                new LruBitmapCache());
    }
    return this.mImageLoader;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    // set the default tag if tag is empty
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}
}

And the usage of the class is :

AppController.getInstance().addToRequestQueue(strReq, "Making a request");

If it can be made static then what should be the implementation of the class to make network calls?

Body:
try this, just override this method in your Appcontroller class.link :How to use MultiDex with a custom Application class?

               @Override
      protected void attachBaseContext(Context base)
      {
        super.attachBaseContext(base);
        MultiDex.install(this);
       }


问:
How to use data from the localstorage in angular 2
How to use data from the localstorage for the another component. Localstorage in service are:

localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success,res:res.data}));

I want to use id, username etc from the data in another component How it possible

答:
You can also add individual item to localstorage

To set item

```<code>    localStorage.setItem('username', 'ActualUserName');
</code>```

To retrieve item

```<code>    let username= localStorage.getItem("username");
</code>```

Body:
You can also add individual item to localstorage

To set item

    localStorage.setItem('username', 'ActualUserName');

To retrieve item

    let username= localStorage.getItem("username");


问:
UICollectionView eBay iOS app
I'm pretty new to UICollectionViewController and layout transition stuff.

Currently I'm working on an project that requires layout transition from table view layout to grid layout.

After some exploration, I found that eBay app is using this transition.

![eBay Grid Layout and Transitions]http://i.imgur.com/nqfawco.png

As you can see, if you tap on the button at the top right corner, layout can be animated to

![List Layout]http://i.imgur.com/7Mcolzl.png

I'm wondering if anyone knows and can give me some guidelines on how to implement this feature?

P.S. There are totally 3 different kinds of layouts in this app, but I only want the transition from the first image to the second image above.

Thanks a lot!

Frank

答:
Take a look at my
github. I combined Edgardo's answer to complete my work. I put his code inside cell's init method.
Here is my scenario.

Create custom cell that can manipulate subviews corresponding a layout.

override apply(_ layoutAttributes: UICollectionViewLayoutAttributes) with self.layoutIfNeeded(). The method is called when a layout is about to change. So call self.layoutIfNeeded() to apply its subview to rearrange imidiately.

Once a cell call layoutIfNeeded(). layoutSubviews is called. Put a method for rearranging its subview

Call collectionView.setCollectionViewLayout with ur custom layout.In my sample project. I do have 3 layout so I instantiate 3 layout. and toggle them respectively.

Title: UICollectionView eBay iOS app


问:
How can I specify where I want my UI elements to go on orientation change in Interface Builder?
Ok so I know this is a bit of a newbie question, but being that I am a newbie its ok! I have a view that I am trying to make orientation friendly in IB, and I am having some difficulties.

I have everything looking nice in portrait of course, but then when I go to landscape mode (by hitting that arrow in the top-right corner) everything gets all messed up.

Now, because of the way the view is laid out, I need to align 3 buttons along the bottom of an image view in portrait, and then in landscape, those three buttons need to be symmetrically aligned along the right side.

No combination of fiddling with those red arrows in the size inspector are rewarding me the results I am seeking. Is it possible to set up the buttons one way in one orientation in IB, and then on change, set them completely different?

I have looked all around for a useful IB tutorial, but haven't been able to find anything.

答:
I know you want to do this in IB, but if you're willing to try it programmatically, then you can move things around pretty easily. For your buttons, just implement the setCenter method like this:

[myButton setCenter:CGPointMake(xCenter,yCenter)];

Otherwise, if you want to use the IB, use the Autosizing options. The arrows will stretch or compress the width and height, and the bars (|-|) preserve distances from the top and bottom. If you have three buttons in a row, you can fix the left distance for the left button, the right distance for the right button and both/neither for the center button. Something like that may work.

The third option is to make a new view, call it landscapeView or something, by dragging a UIView from the library to the window with File's Owner, First Responder, View, etc. Then orient that to landscape, copy over all your UI objects, lay them out as you like, and when you rotate, replace the current view with landscapeView. The problem with this that I've found (one of many) is that you have to reconnect everything and have different IBOutlets for the labels and whatnot. T


问:
Is it good that we link dao entity classes with mvc form
I am learning hibernate with spring. While implementing i am creating entity class like below

```<code>@Entity
@Table(name = "USER_DETAILS", uniqueConstraints = @UniqueConstraint(columnNames = "USER_ID"))
public class UserInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "USER_KEY", unique = true, nullable = false)
    private Long userKey;

    @Column(name = "USER_ID", unique = true, nullable = false)
    private String userId;

//getters and setters
}
</code>```

And i am designing a html page to get above input from user. As per the tutorial they are creating a DTO class with same variables which are in the DAO entity class and implementing JSR303 validation after that attaching that DTO to the form like below.

```<code><sf:form action="/addUser" commandName="userDTO"
                method="post">
//input text boxes

</sf:form>
</code>```

Its difficult to understand why we need to create a same DAO Entity class again without hibernate annotations and the same variables in the name of DTO. Please share some guidelines.

Is it a best practice or is it any performance / structural  reason that we need to create DTO class for html form.

What will happen if we directly attach DAO entity class with form.

Please give some ideas / guidelines.

答:
In my opinion it's bad that we link dao entity classes with mvc form.

It's a better idea to segregate your application to some layers. The most usual approach is to have 3 layers: persistence, service and presentation layers.

Typically, each layer uses its own kind of objects:

persistence: repositories, entities

business: services, domain objects

presentation: controllers, DTOs

We need this because we want each layer to be separated from the other layers. If you want to use entities in your controller, your presentation would depend on how your data is stored. It's really bad. It shouldn't even know that or how data is stored.

Body:
I am learning hibernate with spring. While implementing i am creating entity class like below

@Entity
@Table(name = "USER_DETAILS", uniqueConstraints = @UniqueConstraint(columnNames = "USER_ID"))
public class UserInfo implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "USER_KEY", unique = true, nullable = false)
    private Long userKey;

    @Column(name = "USER_ID", unique = true, nullable = false)
    private String userId;

//getters and setters
}

And i am designing a html page to get above input from user. As per the tutorial they are creating a DTO class with same variables which are in the DAO entity class and implementing JSR303 validation after that attaching that DTO to the form like below.

<sf:form action="/addUser" commandName="userDTO"
                method="post">
//input text boxes

</sf:form>

Its difficult to understand why we need to create a same DAO Entity class again without hibernate annotations and the same variables in the name of DTO. Please share some guidelines.

Is it a best practice or is it any performance / structural  reason that we need to create DTO class for html form.

What will happen if we directly attach DAO entity class with form.

Please give some ideas / guidelines.


问:
How to POST form-url-encoded data with Spring Cloud Feign
Using spring-mvc annotations:

How can I define an @FeignClient that can POST form-url-encoded?

答:
Use FormEncoder for Feign:

https://github.com/OpenFeign/feign-form

And your Feign configuration can look like this:

```<code>class CoreFeignConfiguration {
  @Autowired
  private ObjectFactory<HttpMessageConverters> messageConverters

  @Bean
  @Primary
  @Scope(SCOPE_PROTOTYPE)
  Encoder feignFormEncoder() {
      new FormEncoder(new SpringEncoder(this.messageConverters))
  }
}
</code>```

Then, the client can be mapped like this:

```<code>@FeignClient(name = 'client', url = 'localhost:9080', path ='/rest',
    configuration = CoreFeignConfiguration)
interface CoreClient {
    @RequestMapping(value = '/business', method = POST,
                 consumes = MediaType.APPLICATION_FORM_URLENCODED)
    @Headers('Content-Type: application/x-www-form-urlencoded')
    void activate(Map<String, ?> formParams)
}
</code>```

Body:
Use FormEncoder for Feign:

https://github.com/OpenFeign/feign-form

And your Feign configuration can look like this:

class CoreFeignConfiguration {
  @Autowired
  private ObjectFactory<HttpMessageConverters> messageConverters

  @Bean
  @Primary
  @Scope(SCOPE_PROTOTYPE)
  Encoder feignFormEncoder() {
      new FormEncoder(new SpringEncoder(this.messageConverters))
  }
}

Then, the client can be mapped like this:

@FeignClient(name = 'client', url = 'localhost:9080', path ='/rest',
    configuration = CoreFeignConfiguration)
interface CoreClient {
    @RequestMapping(value = '/business', method = POST,
                 consumes = MediaType.APPLICATION_FORM_URLENCODED)
    @Headers('Content-Type: application/x-www-form-urlencoded')
    void activate(Map<String, ?> formParams)
}


问:
Can we get the application name from the socket address?
Can we find name of the application which is running on a given socket address?

By socket address, I mean the combination of IP Address and Port Number.

Like we can find out the name of the host from the IP address by using the following command in linux:

host [IP]

But is there any command or any way to find out the application name in the same manner as we can find the hostname?

If we can find out only web-application names or tomcat service name, then it is also fine.

答:
A fairly easy way to do this is to use "netstat":

```<code>gruescher@SMARTBUILD:~$ sudo netstat -nlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      712/rpcbind
tcp        0      0 127.0.1.1:53            0.0.0.0:*               LISTEN      1217/dnsmasq
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      928/sshd
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      1487/cupsd
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      25654/postgres
tcp        0      0 0.0.0.0:445             0.0.0.0:*               LISTEN      19660/smbd
tcp        0      0 0.0.0.0:513             0.0.0.0:*               LISTEN      980/xinetd
tcp        0      0 0.0.0.0:514             0.0.0.0:*               LISTEN      980/xinetd
tcp        0      0 0.0.0.0:139             0.0.0.0:*               LISTEN      19660/smbd
tcp        0      0 0.0.0.0:41516           0.0.0.0:*               LISTEN      31353/rpc.statd
tcp6       0      0 :::111                  :::*                    LISTEN      712/rpcbind
tcp6       0      0 :::80                   :::*                    LISTEN      2757/apache2
tcp6       0      0 :::24693                :::*                    LISTEN      13707/fo_scheduler
tcp6       0      0 :::22                   :::*                    LISTEN      928/sshd
tcp6       0      0 ::1:631                 :::*                    LISTEN      1487/cupsd
tcp6       0      0 :::445                  :::*                    LISTEN      19660/smbd
tcp6       0      0 :::48611                :::*                    LISTEN      31353/rpc.statd
tcp6       0      0 :::139                  :::*                    LISTEN      19660/smbd
</code>```

As you can see, it displays port, local address, PID and process name.

You have to run this as superuser.

Body:
A fairly easy way to do this is to use "netstat":

gruescher@SMARTBUILD:~$ sudo netstat -nlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      712/rpcbind
tcp        0      0 127.0.1.1:53            0.0.0.0:*               LISTEN      1217/dnsmasq
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      928/sshd
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      1487/cupsd
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      25654/postgres
tcp        0      0 0.0.0.0:445             0.0.0.0:*               LISTEN      19660/smbd
tcp        0      0 0.0.0.0:513             0.0.0.0:*               LISTEN      980/xinetd
tcp        0      0 0.0.0.0:514             0.0.0.0:*               LISTEN      980/xinetd
tcp        0      0 0.0.0.0:139             0.0.0.0:*               LISTEN      19660/smbd
tcp        0      0 0.0.0.0:41516           0.0.0.0:*               LISTEN      31353/rpc.statd
tcp6       0      0 :::111                  :::*                    LISTEN      712/rpcbind
tcp6       0      0 :::80                   :::*                    LISTEN      2757/apache2
tcp6       0      0 :::24693                :::*                    LISTEN      13707/fo_scheduler
tcp6       0      0 :::22                   :::*                    LISTEN      928/sshd
tcp6       0      0 ::1:631                 :::*                    LISTEN      1487/cupsd
tcp6       0      0 :::445                  :::*                    LISTEN      19660/smbd
tcp6       0      0 :::48611                :::*                    LISTEN      31353/rpc.statd
tcp6       0      0 :::139                  :::*                    LISTEN      19660/smbd

As you can see, it displays port, local address, PID and process name.

You have to run this as superuser.


问:
How do I pass an image view and its properties from one view controller to another?
So I have an image view in one viewcontroller.swift file that generates a random background image every time the a question is asked (it's a quiz app). When the user get's the answer right I want the random background image produced from the first view controller when the question is asked to be the same background image for the next view controller that displays when the answer is answered correctly. How do I make sure the both background image views displays the same random image every time a question is correctly answered? Here is a snippet of my code that deals with the background image.

```<code>class ViewController : UIViewController

@IBOutlet weak var backgroundImage: UIImageView!

let backgroundImages = //array containing all the images

//random image generator function
func randomImage() {
    index = Int(arc4random_uniform(UInt32(backgroundImages.count)))
    backgroundImage.image = backgroundImages[index]
}
</code>```

Now if I wanted an image view to always display the same background images produced by the randomImage function in a different class (class SecondViewController: UIViewController) for example what would be the best way to get the data from the original view controller? (If you click the right answer button according to the question it proceeds to a new "right answer" view controller that I want to have the same background image as the previous view controller).

答: Make the subclass of UIImageView and use it.</p>

Body:
So I have an image view in one viewcontroller.swift file that generates a random background image every time the a question is asked (it's a quiz app). When the user get's the answer right I want the random background image produced from the first view controller when the question is asked to be the same background image for the next view controller that displays when the answer is answered correctly. How do I make sure the both background image views displays the same random image every time a question is correctly answered? Here is a snippet of my code that deals with the background image.

class ViewController : UIViewController

@IBOutlet weak var backgroundImage: UIImageView!

let backgroundImages = //array containing all the images

//random image generator function
func randomImage() {
    index = Int(arc4random_uniform(UInt32(backgroundImages.count)))
    backgroundImage.image = backgroundImages[index]
}

Now if I wanted an image view to always display the same background images produced by the randomImage function in a different class (class SecondViewController: UIViewController) for example what would be the best way to get the data from the original view controller? (If you click the right answer button according to the question it proceeds to a new "right answer" view controller that I want to have the same background image as the previous view controller).


问:
Translate label in Odoo 10
I am trying to translate this "Height" label without success.

```<code><label for="label_height">Height</label><field name="label_height" nolabel="1"/>
</code>```

I have run

```<code>/usr/bin/odoo -d demo_v10 --i18n-export=es_ES.po --modules=custom_labels --language=es_ES
</code>```

To get translation file, I have translated all term and updated module both in command line -u custom_labels and in the UI, but I still see non-translated term.
Could anyone paste an example on how to translate a label?

Thanks,

答:
Try below steps:

Export Translation:

Choose language, in my case Arabic.

File format : PO

Modules to export (ex: sales, stock, invoicing etc).

Click on the Export button and download ar_SY.po file

Change msgstr in *.po file.

Put that file in your custom module `mymodule/i18/ar_SY.po.

Upgrade the module

Hope it will help you.

Title: Translate label in Odoo 10

Body:
I am trying to translate this "Height" label without success.

Height<field name="label_height" nolabel="1"/>

I have run

/usr/bin/odoo -d demo_v10 --i18n-export=es_ES.po --modules=custom_labels --language=es_ES

To get translation file, I have translated all term and updated module both in command line -u custom_labels and in the UI, but I still see non-translated term.
Could anyone paste an example on how to translate a label?

Thanks,


问:
Macro or Loop to conditional formatting

I need to repeat shown the conditional formatting to all the rows. There are lot of rows. The conditional icon is based on the first value of the cell and others shows according to it. How to achieve all this in one go.
My data ranging from C2:F792.

答:
Follow these steps...

Select the range C2:F2 and press Ctrl+C to copy it.

Now select the range C3:F792.

Right click on any of the selected cells --> Choose Paste Special --> Select the radio button for Formats and click on OK.

If you want to do this programmatically, you may try something like this...

```<code>Sub CopyConditionalFormatting()
Dim rng As Range
Set rng = Range("C3:F792")
Range("C2:F2").Copy
rng.PasteSpecial xlPasteFormats
Application.CutCopyMode = 0
End Sub
</code>```

Title: Macro or Loop to conditional formatting

Body:
Follow these steps...

Select the range C2:F2 and press Ctrl+C to copy it.

Now select the range C3:F792.

Right click on any of the selected cells --> Choose Paste Special --> Select the radio button for Formats and click on OK.

If you want to do this programmatically, you may try something like this...

Sub CopyConditionalFormatting()
Dim rng As Range
Set rng = Range("C3:F792")
Range("C2:F2").Copy
rng.PasteSpecial xlPasteFormats
Application.CutCopyMode = 0
End Sub


问:
JavaFX8, SQLite(Embedded) exe, exec jar can't read/update the runtime database
I am creating a simple desktop application using JavaFx8 and SQLite and Eclipse Neon IDE. The Application works fine when launched to test from Eclipse. But If I create an executable jar or a Windows Exe file, it doesn't read/update the database.
Here's the code snippet used for creating and reading database.

```<code> private Connection loadPropertiesFileSQLite() throws SQLException, ClassNotFoundException {
    try {
        inputStream = new FileInputStream("databasesqlite.properties");
        properties.load(inputStream);
        Class.forName("org.sqlite.JDBC");
        // database path, if it's new database, it will be created in the project folder
        conSQLite = DriverManager.getConnection("jdbc:sqlite:Application.db");
        System.out.println("Database Opened Successfully.");
    } catch (Exception e) {
        System.out.println("DDDD");
        e.printStackTrace();
    }
    return conSQLite;
}
</code>```

The connectors and jars I'm using are these:

The database is created in embedded mode when the user runs the application for the first time.
I have searched and tried scores of combinations from changing the location of database in DriverManager.getConnection("jdbc:sqlite:Application.db");
to many other things. Is there anything big that I'm missing here?

答:
Are you using the properties file for nothing?
there is my config: sqlite-jdbc-3.7.15.jar
//auto commit on the connection.
conSQLite.setAutoCommit(true);

and check if do you have a permission at the file "Application.db".

Body:
I am creating a simple desktop application using JavaFx8 and SQLite and Eclipse Neon IDE. The Application works fine when launched to test from Eclipse. But If I create an executable jar or a Windows Exe file, it doesn't read/update the database.
Here's the code snippet used for creating and reading database.

 private Connection loadPropertiesFileSQLite() throws SQLException, ClassNotFoundException {
    try {
        inputStream = new FileInputStream("databasesqlite.properties");
        properties.load(inputStream);
        Class.forName("org.sqlite.JDBC");
        // database path, if it's new database, it will be created in the project folder
        conSQLite = DriverManager.getConnection("jdbc:sqlite:Application.db");
        System.out.println("Database Opened Successfully.");
    } catch (Exception e) {
        System.out.println("DDDD");
        e.printStackTrace();
    }
    return conSQLite;
}

The connectors and jars I'm using are these:

The database is created in embedded mode when the user runs the application for the first time.
I have searched and tried scores of combinations from changing the location of database in DriverManager.getConnection("jdbc:sqlite:Application.db");
to many other things. Is there anything big that I'm missing here?


问:
Android Studio: java.io.IOException: An existing connection was forcibly closed by the remote host
I read many posts to fix this problem. None worked for me.

Error:

```<code>Target device: lenovo-lenovo_a6000-89a70dc9
Installing APK: C:\Users\Nikhil\AndroidStudioProjects\ProfitKey\app\build\outputs\apk\app-debug.apk
Uploading file to: /data/local/tmp/helix.profitkey.hotelapp
java.io.IOException: An existing connection was forcibly closed by the remote host
</code>```

I tried below

Kill and start adb

Invalidate and restart android studio

Removed adb process in the taskbar

Restarted the device and pc

Restarted studio, clean and rebuild

Taskbar have only one adb.exe

Updated the driver from device manager

Another device it is working. But previously both device worked fine for me.

```<code>Target device: motorola-xt1022-ZX1B33PRVP
Installing APK: C:\Users\Nikhil\AndroidStudioProjects\ProfitKey\app\build\outputs\apk\app-debug.apk
Uploading file to: /data/local/tmp/helix.profitkey.hotelapp
Installing helix.profitkey.hotelapp
DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/helix.profitkey.hotelapp"
pkg: /data/local/tmp/helix.profitkey.hotelapp
Success
</code>```

Edited:

I tried with two lenovo A6000. One is working and another is not working. Then, Moto is working and samsung galaxy is not working. Whenever I am killing and starting the adb. The task manager creating two adb first and after few seconds one was hiding. Was this a problem? But still some devices working fine.

adb starts automatically after killing by command or from the task manager if android studio is opened.

答: I also faced same problem,this was a just port problem,I was using computer front USB port ,just use computer back USB port and problem solved.</p>

Body:
I read many posts to fix this problem. None worked for me.

Error:

Target device: lenovo-lenovo_a6000-89a70dc9
Installing APK: C:\Users\Nikhil\AndroidStudioProjects\ProfitKey\app\build\outputs\apk\app-debug.apk
Uploading file to: /data/local/tmp/helix.profitkey.hotelapp
java.io.IOException: An existing connection was forcibly closed by the remote host

I tried below

Kill and start adb

Invalidate and restart android studio

Removed adb process in the taskbar

Restarted the device and pc

Restarted studio, clean and rebuild

Taskbar have only one adb.exe

Updated the driver from device manager

Another device it is working. But previously both device worked fine for me.

Target device: motorola-xt1022-ZX1B33PRVP
Installing APK: C:\Users\Nikhil\AndroidStudioProjects\ProfitKey\app\build\outputs\apk\app-debug.apk
Uploading file to: /data/local/tmp/helix.profitkey.hotelapp
Installing helix.profitkey.hotelapp
DEVICE SHELL COMMAND: pm install -r "/data/local/tmp/helix.profitkey.hotelapp"
pkg: /data/local/tmp/helix.profitkey.hotelapp
Success

Edited:

I tried with two lenovo A6000. One is working and another is not working. Then, Moto is working and samsung galaxy is not working. Whenever I am killing and starting the adb. The task manager creating two adb first and after few seconds one was hiding. Was this a problem? But still some devices working fine.

adb starts automatically after killing by command or from the task manager if android studio is opened.


问:
SQL server with Rails

I've been trying to get my rails program to access an existing sql express server set up on another machine at work. I've followed these instructions: GitHub and set up my database.yml like this:

```<code>development:
adapter: sqlserver
mode: odbc
dns: Provider=SQLOLEDB;Data Source=MACHINENAME\SQLEXPRESS;UID=xxxx;PWD=xxxxx;Application Name=atlas
timeout: 5000
</code>```

Now when I try to run script/console (or server or whatever) I get this error:

```<code>/var/lib/gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:440:in `load_missing_constant':NameError: uninitialized constant ActiveRecord::WrappedDatabaseException
</code>```

I've tried googling and changing settings back and forth but i've come up blank. Am I doing something awfully wrong or what?

BR,

SG

答:
I can only speak for using Rails 3.0.3 with SQLServer 2005, so I hope that helps you a bit.

I've added this to my Gemfile:

```<code>gem 'ruby-odbc', '0.99991', :require => 'odbc'
gem 'activerecord-sqlserver-adapter', :branch => "arel2",
  :git => "git://github.com/rails-sqlserver/activerecord-sqlserver-adapter"
</code>```

And use this in my config/database.yml:

```<code>test:
  adapter: sqlserver
  mode: ODBC
  dsn: my_app_test
  username: [USERNAME]
  password: [PASSWORD]
</code>```

The DSN is configured elsewhere, but it is in nowhere as complex as yours. I followed these instructions: http://github.com/rails-sqlserver/activerecord-sqlserver-adapter/wiki/Platform-Installation---Ubuntu

Title: SQL server with Rails

Body:
I've been trying to get my rails program to access an existing sql express server set up on another machine at work. I've followed these instructions: GitHub and set up my database.yml like this:

development:
adapter: sqlserver
mode: odbc
dns: Provider=SQLOLEDB;Data Source=MACHINENAME\SQLEXPRESS;UID=xxxx;PWD=xxxxx;Application Name=atlas
timeout: 5000

Now when I try to run script/console (or server or whatever) I get this error:

/var/lib/gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:440:in `load_missing_constant':NameError: uninitialized constant ActiveRecord::WrappedDatabaseException

I've tried googling and changing settings back and forth but i've come up blank. Am I doing something awfully wrong or what?

BR,

SG

Body:
I can only speak for using Rails 3.0.3 with SQLServer 2005, so I hope that helps you a bit.

I've added this to my Gemfile:

gem 'ruby-odbc', '0.99991', :require => 'odbc'
gem 'activerecord-sqlserver-adapter', :branch => "arel2",
  :git => "git://github.com/rails-sqlserver/activerecord-sqlserver-adapter"

And use this in my config/database.yml:

test:
  adapter: sqlserver
  mode: ODBC
  dsn: my_app_test
  username: [USERNAME]
  password: [PASSWORD]

The DSN is configured elsewhere, but it is in nowhere as complex as yours. I followed these instructions: http://github.com/rails-sqlserver/activerecord-sqlserver-adapter/wiki/Platform-Installation---Ubuntu


问:
Does every table need a primary key?
Take the Loan table below as an example. Does it require any primary key?

Loan Table

答:
Yes.

Your Loan table looks like a junction table, so the PK should be the combination of DocumentID and EmployeeID.

Title: Does every table need a primary key?


问:
Two master instances on same database
I want to use Postgresql in Windows Server 2012 R2 for one our project where it can be 24/7 uptime.

I would like to ask the community if I can have 2 master instances in 2 different servers A&B and they will 'work' on the same DB located in a shared file storage in lan. Always one master instance on server A will be online and when it goes offline for some reason (I suppose) a powershell script will recognize that the postgresql service stopped and will start the service in server B. The same script will continuous check that only one service in servers A & B is working to avoid conflicts.

I'd like to ask if this is possible or a better approach for my configuration.
(I can't use replication because when server A shuts down the server B is in read-only mode thing that I don't want)

答:
If you manage to start two instances of PostgreSQL on the same data directory, serious data corruption will happen.

Normally there is a postmaster.pid file that prevents that, but a PostgreSQL server process on a different machine that accesses the same file system will happily unlink that after spewing some log messages, thinking it was left behind from a crash.

So you are really walking on thin ice with a solution like that.

One other issue that you didn't think of is that script that is supposed to check if the server is still running. What if that script fails, because for example the network connection between the two servers is down, but the server is still up an running happily? Such a “split brain” scenario will cause data corruption with your setup.

Another word of caution: since you seem to be using Windows (Powershell?), you probably envision a CIFS file system when you are talking of shared storage. A Windows “network share” is not a reliable file system — last time I checked, it did not honor _commit.

Creating a reliable failover cluster is harder than you think, and I'd recommend that you check existing solutions before you try to roll your own.

Title: Two master instances on same database


问:
How to close the current fragment by using Button like the back button?
I have try to close the current fragment by using Imagebutton.

I am in Fragment-A and it will turn to the Fragment-B when I click the button.

And when I click the button at Fragment-B , it will turn to the Fragment-C and close the Fragment-B.

If I click the back button at Fragment-C , it will back to the Fragment-A.

The code I have try is like the following

```<code>camera_album = (ImageButton) view.findViewById(R.id.camera_album);

camera_album.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {

                    closefragment();
        Fragment fragment = FileBrowserFragment.newInstance(null, null, null) ;
        MainActivity.addFragment(LocalFileBrowserFragment.this, fragment) ;

    }
});

private void closefragment() {
    getActivity().getFragmentManager().beginTransaction().remove(this).commit();
}
</code>```

When I click the back button at fragment-B , it turn to the Fragment-C.

But when I click the back button on Fragment-C , it doesn't back to the Fragment-A.
It back to the empty background. If I want to back to Fragment-A , I have to click the back button once again.

SO , it seem doesn't close the current fragment complete.

How to finish the current fragment like the back button of Android ?

答:
If you need to handle the action more specifically with the back button you can use the following method:</p>

```<code>view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if( keyCode == KeyEvent.KEYCODE_BACK )
        {
            onCloseFragment();
            return true;
        } else {
            return false;
        }
    }
});
</code>```

Body:
I have try to close the current fragment by using Imagebutton.

I am in Fragment-A and it will turn to the Fragment-B when I click the button.

And when I click the button at Fragment-B , it will turn to the Fragment-C and close the Fragment-B.

If I click the back button at Fragment-C , it will back to the Fragment-A.

The code I have try is like the following

camera_album = (ImageButton) view.findViewById(R.id.camera_album);

camera_album.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {

                    closefragment();
        Fragment fragment = FileBrowserFragment.newInstance(null, null, null) ;
        MainActivity.addFragment(LocalFileBrowserFragment.this, fragment) ;

    }
});

private void closefragment() {
    getActivity().getFragmentManager().beginTransaction().remove(this).commit();
}

When I click the back button at fragment-B , it turn to the Fragment-C.

But when I click the back button on Fragment-C , it doesn't back to the Fragment-A.
It back to the empty background. If I want to back to Fragment-A , I have to click the back button once again.

SO , it seem doesn't close the current fragment complete.

How to finish the current fragment like the back button of Android ?

Body:
If you need to handle the action more specifically with the back button you can use the following method:

view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if( keyCode == KeyEvent.KEYCODE_BACK )
        {
            onCloseFragment();
            return true;
        } else {
            return false;
        }
    }
});