问:
Android Read Images Permission External Storage
I want to read and save Images / Bitmaps from internal storage.

In my layout I have a button and a imageview. When I click the button I want to chose a picture of the gallery to save it. When I click on the imageview I want the saved image to be shown.

Thats what I tried:

Layout:

```<code>    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="80dp"
        android:layout_marginRight="80dp"
        android:text="Upload Image"
        android:onClick="onClickUpload"
        android:layout_marginBottom="30dp" />

    <ImageView
        android:id="@+id/imgPicker"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:onClick="onClickShow"
        app:srcCompat="@android:color/holo_orange_dark" />
</code>```

Read function with asking for permission

```<code>public void onClickUpload(View view) {

    // request permission to read external storage (explicit necessary since API Level 23)

    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(DetailActivity.this,
            Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(DetailActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(DetailActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
            }
    } else {
        startActivityForResult(new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);
    }
}
</code>```

Override onRquestPermissionResult

```<code>/*
    find out whether the permission was granted
 */
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // start Activity if granted
                startActivityForResult(new Intent(Intent.ACTION_PICK,
                        MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}
</code>```

Run after permission granted:

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    //Detects request codes
    if(requestCode==GET_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
        Uri selectedImage = data.getData();
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);

            ContextWrapper cw = new ContextWrapper(getApplicationContext());
            // path to /data/data/yourapp/app_data/imageDir
            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            // Create imageDir
            File mypath=new File(directory,"profile.jpg");

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(mypath);
                // Use the compress method on the BitMap object to write image to the OutputStream
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            directory.getAbsolutePath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

In my manifest I have also permissions:

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".activities.LoginActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".activities.RegisterActivity"
        android:screenOrientation="portrait" />
    <activity
        android:name=".activities.CategoryActivity"
        android:screenOrientation="portrait" />
    <activity android:name=".activities.SuggestionActivity" />
    <activity
        android:name=".activities.DetailActivity"
        android:theme="@style/AppTheme" />

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

Nevertheless I get this error when clicking the button (Device is API 24):

```<code>06-08 19:56:28.903 18770-18782/android.process.media E/DatabaseUtils: Writing exception to parcel
                                                                      java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/file from pid=20240, uid=10046 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                          at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:608)
                                                                          at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:483)
                                                                          at android.content.ContentProvider$Transport.query(ContentProvider.java:212)
                                                                          at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)
                                                                          at android.os.Binder.execTransact(Binder.java:565)
</code>```

答:
```<code>startActivityForResult(new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);
</code>```

The above code is executed regardless of the permission being granted or not. Did you mean to wrap it around else for your if?

```<code>public void onClickUpload(View view) {

    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(DetailActivity.this,
            Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(DetailActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(DetailActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    } else {
        startActivityForResult(new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);
    }
}
</code>```

And I'm assuming you've overridden

```<code>public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[],
                                           @NonNull int[] grantResults)
</code>```

for listening to the permission being granted or not.

Body:
I want to read and save Images / Bitmaps from internal storage.

In my layout I have a button and a imageview. When I click the button I want to chose a picture of the gallery to save it. When I click on the imageview I want the saved image to be shown.

Thats what I tried:

Layout:

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="80dp"
        android:layout_marginRight="80dp"
        android:text="Upload Image"
        android:onClick="onClickUpload"
        android:layout_marginBottom="30dp" />

    <ImageView
        android:id="@+id/imgPicker"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"
        android:onClick="onClickShow"
        app:srcCompat="@android:color/holo_orange_dark" />

Read function with asking for permission

public void onClickUpload(View view) {

    // request permission to read external storage (explicit necessary since API Level 23)

    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(DetailActivity.this,
            Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(DetailActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(DetailActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
            }
    } else {
        startActivityForResult(new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);
    }
}

Override onRquestPermissionResult

/*
    find out whether the permission was granted
 */
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // start Activity if granted
                startActivityForResult(new Intent(Intent.ACTION_PICK,
                        MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

Run after permission granted:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    //Detects request codes
    if(requestCode==GET_FROM_GALLERY && resultCode == Activity.RESULT_OK) {
        Uri selectedImage = data.getData();
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);

            ContextWrapper cw = new ContextWrapper(getApplicationContext());
            // path to /data/data/yourapp/app_data/imageDir
            File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
            // Create imageDir
            File mypath=new File(directory,"profile.jpg");

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(mypath);
                // Use the compress method on the BitMap object to write image to the OutputStream
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            directory.getAbsolutePath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In my manifest I have also permissions:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".activities.LoginActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".activities.RegisterActivity"
        android:screenOrientation="portrait" />
    <activity
        android:name=".activities.CategoryActivity"
        android:screenOrientation="portrait" />
    <activity android:name=".activities.SuggestionActivity" />
    <activity
        android:name=".activities.DetailActivity"
        android:theme="@style/AppTheme" />

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

Nevertheless I get this error when clicking the button (Device is API 24):

06-08 19:56:28.903 18770-18782/android.process.media E/DatabaseUtils: Writing exception to parcel
                                                                      java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/file from pid=20240, uid=10046 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                          at android.content.ContentProvider.enforceReadPermissionInner(ContentProvider.java:608)
                                                                          at android.content.ContentProvider$Transport.enforceReadPermission(ContentProvider.java:483)
                                                                          at android.content.ContentProvider$Transport.query(ContentProvider.java:212)
                                                                          at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112)
                                                                          at android.os.Binder.execTransact(Binder.java:565)

Body:
startActivityForResult(new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);

The above code is executed regardless of the permission being granted or not. Did you mean to wrap it around else for your if?

public void onClickUpload(View view) {

    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(DetailActivity.this,
            Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(DetailActivity.this,
                Manifest.permission.READ_EXTERNAL_STORAGE)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(DetailActivity.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    } else {
        startActivityForResult(new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), GET_FROM_GALLERY);
    }
}

And I'm assuming you've overridden

public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[],
                                           @NonNull int[] grantResults)

for listening to the permission being granted or not.


来源: stackexchange

问:
how do I remove from tuples in a list of tuples
I have a list of tuples like this

```<code>[
  ('px', Timestamp('2017-07-01 00:00:00')),
  ('px', Timestamp('2017-08-01 00:00:00')),
  ('px', Timestamp('2017-09-01 00:00:00')),
  ('px', Timestamp('2017-10-01 00:00:00')),
  ('px', Timestamp('2017-11-01 00:00:00'))
]
</code>```

and want to remove the 'px' keeping only the timestamps as a tuple.

答:
You can slice off the first items in a list comprehension:

```<code>new_lst = [x[1:] for x in lst]
</code>```

The tuple slice gives you a new tuple, with the items at index 0 removed.

ContentLicense: CC BY-SA 3.0

Body:
I have a list of tuples like this

[
  ('px', Timestamp('2017-07-01 00:00:00')),
  ('px', Timestamp('2017-08-01 00:00:00')),
  ('px', Timestamp('2017-09-01 00:00:00')),
  ('px', Timestamp('2017-10-01 00:00:00')),
  ('px', Timestamp('2017-11-01 00:00:00'))
]

and want to remove the 'px' keeping only the timestamps as a tuple.

Body:
You can slice off the first items in a list comprehension:

new_lst = [x[1:] for x in lst]

The tuple slice gives you a new tuple, with the items at index 0 removed.


问:
Disable checkboxes based on status of one checkbox
if 'choose not to answer' is checked, i need to disable the other checkboxes, here is my code and html, any help as to why it's not working?

code

```<code>function toggleStatus() {
if ($('#toggleElement').is(':checked')) {
    $('#living :input').attr('disabled', true);
} else {
    $('#living :input').removeAttr('disabled');
}
</code>```

html

```<code><p>With whom do you live? Choose all that apply<br/>
    <input type="checkbox" name="living" value="alone" id="living">
    Live alone <br>
    <input type="checkbox" name="living" value="husband" id="living">
    Husband <br>
    <input type="checkbox" name="living" value="partner" id="living">
    Partner <br>
    <input type="checkbox" name="living" value="children" id="living">
    Children <br>
    <input type="checkbox" name="living" value="parents" id="living">
    Parents <br>
    <input type="checkbox" name="living" value="other_relatives" id="living">
    Other relatives <br>
    <input type="checkbox" name="living" value="religion" id="living">
    Religious order <br>
    <input type="checkbox" name="living" value="no_answer"
                id="toggleElement">
    Choose not to answer <br>
</p>
</code>```

答:
Try this instead:</p>

```<code>if ($('#toggleElement').is(':checked')) {
    $('#living :input').attr('disabled', "disabled");
} else {
    $('#living :input').attr('disabled', false);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
if 'choose not to answer' is checked, i need to disable the other checkboxes, here is my code and html, any help as to why it's not working?

code

function toggleStatus() {
if ($('#toggleElement').is(':checked')) {
    $('#living :input').attr('disabled', true);
} else {
    $('#living :input').removeAttr('disabled');
}

html

With whom do you live? Choose all that apply

    <input type="checkbox" name="living" value="alone" id="living">
    Live alone

    <input type="checkbox" name="living" value="husband" id="living">
    Husband

    <input type="checkbox" name="living" value="partner" id="living">
    Partner

    <input type="checkbox" name="living" value="children" id="living">
    Children

    <input type="checkbox" name="living" value="parents" id="living">
    Parents

    <input type="checkbox" name="living" value="other_relatives" id="living">
    Other relatives

    <input type="checkbox" name="living" value="religion" id="living">
    Religious order

    <input type="checkbox" name="living" value="no_answer"
                id="toggleElement">
    Choose not to answer

Body:
Try this instead:

if ($('#toggleElement').is(':checked')) {
    $('#living :input').attr('disabled', "disabled");
} else {
    $('#living :input').attr('disabled', false);
}


问:
Find the same string in mysql table between certain column values
I have a table in MySQL database let's call it products:

```<code>id_product | id_lang | name
-----------+---------+-----
       654 |       1 | abc
       654 |       2 | xyz
       654 |       3 | abc
       456 |       1 | qwe
       456 |       2 | rty
       456 |       3 | zxc
       123 |       1 | bnm
       123 |       2 | bnm
       123 |       3 | jkl
       789 |       1 | ert
       789 |       2 | tyu
       789 |       3 | ert
       333 |       1 | ddd
       333 |       2 | o
       333 |       3 | bbb
       222 |       1 | xxx
       222 |       2 | zzz
       222 |       3 | o
</code>```

I would like to find all id_product which have the same name in id_lang 1 and 3. So result in this case should be id_product: 654 and 789. It would be great if in this query could find also all id_product where id_lang is 3 and name is "o". So result should be id_product: 654, 789 and 222. But if it is too complicated I can have two queries and merge two array's in PHP.

答:
Including the first part of the query from @Sebastian
and adding the second piece with a Union</p>

```<code>SELECT
    id_product
FROM
    table_name
WHERE
    id_lang IN (1 , 3)
GROUP BY id_product , name
HAVING COUNT(name) > 1
UNION
SELECT
    id_product
FROM
    table_name
WHERE
    id_lang = 3 AND name = 'o'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a table in MySQL database let's call it products:

id_product | id_lang | name
-----------+---------+-----
       654 |       1 | abc
       654 |       2 | xyz
       654 |       3 | abc
       456 |       1 | qwe
       456 |       2 | rty
       456 |       3 | zxc
       123 |       1 | bnm
       123 |       2 | bnm
       123 |       3 | jkl
       789 |       1 | ert
       789 |       2 | tyu
       789 |       3 | ert
       333 |       1 | ddd
       333 |       2 | o
       333 |       3 | bbb
       222 |       1 | xxx
       222 |       2 | zzz
       222 |       3 | o

I would like to find all id_product which have the same name in id_lang 1 and 3. So result in this case should be id_product: 654 and 789. It would be great if in this query could find also all id_product where id_lang is 3 and name is "o". So result should be id_product: 654, 789 and 222. But if it is too complicated I can have two queries and merge two array's in PHP.

Body:
Including the first part of the query from @Sebastian
and adding the second piece with a Union

SELECT
    id_product
FROM
    table_name
WHERE
    id_lang IN (1 , 3)
GROUP BY id_product , name
HAVING COUNT(name) > 1
UNION
SELECT
    id_product
FROM
    table_name
WHERE
    id_lang = 3 AND name = 'o'


问:
passing image and displaying it
So after studying, researching and outsoursing i couldnt figure my problem out :(. I am currently trying to get used to segue for view to view while passing values. So whats better then developing a simple app?

My app is like this... first page with one image array that randomly spits out an image when the view loads and one action buttonthat triggers the view segue to the next view using segue preform function.

the second page contains a dismiss button and an image view that should change depend on the randomly passed image from the previeous view image array.

Everything works fine except that I cannot see the randomly passed image.

Below is my code:

Page 1

```<code>import UIKit

class MainWelcomVC: UIViewController {

var ImageArr = [UIImageView]()

@IBOutlet weak var BackGround: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    for x in 0...2 {

        let image = UIImage(named: "char\(x).png")
        let imageview = (UIImageView(image: image))
        ImageArr.append(imageview)

    }

}

@IBAction func PlayButtonPressed(_ sender: Any) {

    let randomIndex = Int(arc4random_uniform(UInt32(ImageArr.count)))
    let CharImage = ImageArr[randomIndex]

    performSegue(withIdentifier: "CharDisplayVC", sender: CharImage)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if let destination = segue.destination as? CharDisplayVC{

        if let ImageFinal = sender as? UIImage {
            destination.ImageToDisplay = ImageFinal
        }
}

}
}
</code>```

page2

```<code>import UIKit

class CharDisplayVC: UIViewController {

private var _ImageToDisplay: UIImage!

var ImageToDisplay: UIImage {

    get {

        return _ImageToDisplay

    } set {

        _ImageToDisplay = newValue
    }

}

@IBOutlet weak var CharPicture: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    CharPicture.image = _ImageToDisplay

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func PlayAgainBtnPressed(_ sender: Any) {

    dismiss(animated: true, completion: nil)
}

}
</code>```

答:
So finally found a solution after fooling around and it was to make everything a UIimage object including the array, below is the new code for  page 1: </p>

```<code>import UIKit

class MainWelcomVC: UIViewController {

var ImageArr = [UIImage]()
var CharImage: UIImage?

@IBOutlet weak var BackGround: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    for x in 0...2 {

        let image = UIImage(named: "char\(x).png")
        ImageArr.append(image!)
    }
}

@IBAction func PlayButtonPressed(_ sender: Any) {

    let randomIndex = Int(arc4random_uniform(UInt32(ImageArr.count)))
    self.CharImage = ImageArr[randomIndex]

    performSegue(withIdentifier: "CharDisplayVC", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

   if let destination = segue.destination as? CharDisplayVC {

        if let ImageFinal = self.CharImage as? UIImage! {
            destination.ImageToDisplay = ImageFinal
        }
   }
  }
 }
</code>```

<p>I still have a yellow warning which says "Conditional cast from 'UIImage?' to 'UIImage!' always succeeds" and another one which says "Pattern match introduces an implicit promotion from 'UIImage!' to 'UIImage!?'" in the below code: </p>

```<code>  if let ImageFinal = self.CharImage as? UIImage! {

  }
</code>```

Title: passing image and displaying it

Body:
So after studying, researching and outsoursing i couldnt figure my problem out :(. I am currently trying to get used to segue for view to view while passing values. So whats better then developing a simple app?

My app is like this... first page with one image array that randomly spits out an image when the view loads and one action buttonthat triggers the view segue to the next view using segue preform function.

the second page contains a dismiss button and an image view that should change depend on the randomly passed image from the previeous view image array.

Everything works fine except that I cannot see the randomly passed image.

Below is my code:

Page 1

import UIKit

class MainWelcomVC: UIViewController {

var ImageArr = [UIImageView]()

@IBOutlet weak var BackGround: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    for x in 0...2 {

        let image = UIImage(named: "char\(x).png")
        let imageview = (UIImageView(image: image))
        ImageArr.append(imageview)

    }

}

@IBAction func PlayButtonPressed(_ sender: Any) {

    let randomIndex = Int(arc4random_uniform(UInt32(ImageArr.count)))
    let CharImage = ImageArr[randomIndex]

    performSegue(withIdentifier: "CharDisplayVC", sender: CharImage)

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if let destination = segue.destination as? CharDisplayVC{

        if let ImageFinal = sender as? UIImage {
            destination.ImageToDisplay = ImageFinal
        }
}

}
}

page2

import UIKit

class CharDisplayVC: UIViewController {

private var _ImageToDisplay: UIImage!

var ImageToDisplay: UIImage {

    get {

        return _ImageToDisplay

    } set {

        _ImageToDisplay = newValue
    }

}

@IBOutlet weak var CharPicture: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    CharPicture.image = _ImageToDisplay

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func PlayAgainBtnPressed(_ sender: Any) {

    dismiss(animated: true, completion: nil)
}

}

Body:
So finally found a solution after fooling around and it was to make everything a UIimage object including the array, below is the new code for  page 1:

import UIKit

class MainWelcomVC: UIViewController {

var ImageArr = [UIImage]()
var CharImage: UIImage?

@IBOutlet weak var BackGround: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    for x in 0...2 {

        let image = UIImage(named: "char\(x).png")
        ImageArr.append(image!)
    }
}

@IBAction func PlayButtonPressed(_ sender: Any) {

    let randomIndex = Int(arc4random_uniform(UInt32(ImageArr.count)))
    self.CharImage = ImageArr[randomIndex]

    performSegue(withIdentifier: "CharDisplayVC", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

   if let destination = segue.destination as? CharDisplayVC {

        if let ImageFinal = self.CharImage as? UIImage! {
            destination.ImageToDisplay = ImageFinal
        }
   }
  }
 }

I still have a yellow warning which says "Conditional cast from 'UIImage?' to 'UIImage!' always succeeds" and another one which says "Pattern match introduces an implicit promotion from 'UIImage!' to 'UIImage!?'" in the below code:

  if let ImageFinal = self.CharImage as? UIImage! {

  }


问:
Should event listeners be inside document.ready function or does it not matter?
When I use:

```<code>$(document).ready(function(){

});
</code>```

Should my event listeners (e.g $('button').click(function(){}) go inside that doc.ready function or outside according to convention?

答: You should include all jQuery code inside of it.  Generally speaking, this is what I've seen most programmers do.  Additionally,  you should include your event listeners inside this section of code.  That way, if you were to load you jQuery code before your HTML, your code will still operate properly.</p>

Body:
When I use:

$(document).ready(function(){

});

Should my event listeners (e.g $('button').click(function(){}) go inside that doc.ready function or outside according to convention?


问:
Can anyone explain why a section isn't centering on my page?
I'm trying to center a few elements on my page vertically and horizontally, but for some reason, setting the container element to have a margin of auto isn't centering them.  Can anyone explain why?

HTML/CSS

body{
 margin: 0;
 padding: 0;
 background-color: rgb(0, 0, 0);
}

#links{
 margin: auto;
}

.link{
 display: inline-block;
 margin: 0 2%;
 width: 15vw;
 height: 15vw;
 border: 2px solid rgb(100, 100, 0);
 border-radius: 50%;
 background-image: url("line.png");
 background-repeat: no-repeat;
 background-size: contain;
 background-position: center;
 background-color: rgb(0, 0, 50);
}

.link:first-of-type{
 margin-left: 0;
}

.link:last-of-type{
 margin-right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="landingpage">
    <section id="links">
        <div class="link" id="home"></div>
        <div class="link" id="work"></div>
        <div class="link" id="contact"></div>
    </section>
</div></code>```

Pen

答:
Because inline-block you center with text-align. Also, your #links has no width and is display: block, so it is 100% wide.

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

body{
 margin: 0;
 padding: 0;
 background-color: rgb(0, 0, 0);
}

#links{
 text-align: center;
}

.link{
 display: inline-block;
 margin: 0 2%;
 width: 15vw;
 height: 15vw;
 border: 2px solid rgb(100, 100, 0);
 border-radius: 50%;
 background-color: rgb(0, 0, 50);
}

.link:first-of-type{
 margin-left: 0;
}

.link:last-of-type{
 margin-right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="landingpage">
    <section id="links">
        <div class="link" id="home"></div>
        <div class="link" id="work"></div>
        <div class="link" id="contact"></div>
    </section>
</div></code>```

Body:
I'm trying to center a few elements on my page vertically and horizontally, but for some reason, setting the container element to have a margin of auto isn't centering them.  Can anyone explain why?

HTML/CSS

body{
 margin: 0;
 padding: 0;
 background-color: rgb(0, 0, 0);
}

#links{
 margin: auto;
}

.link{
 display: inline-block;
 margin: 0 2%;
 width: 15vw;
 height: 15vw;
 border: 2px solid rgb(100, 100, 0);
 border-radius: 50%;
 background-image: url("line.png");
 background-repeat: no-repeat;
 background-size: contain;
 background-position: center;
 background-color: rgb(0, 0, 50);
}

.link:first-of-type{
 margin-left: 0;
}

.link:last-of-type{
 margin-right: 0;
}

Pen

Body:
Because inline-block you center with text-align. Also, your #links has no width and is display: block, so it is 100% wide.

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

body{
 margin: 0;
 padding: 0;
 background-color: rgb(0, 0, 0);
}

#links{
 text-align: center;
}

.link{
 display: inline-block;
 margin: 0 2%;
 width: 15vw;
 height: 15vw;
 border: 2px solid rgb(100, 100, 0);
 border-radius: 50%;
 background-color: rgb(0, 0, 50);
}

.link:first-of-type{
 margin-left: 0;
}

.link:last-of-type{
 margin-right: 0;
}

<div id="landingpage">
    <section id="links">
        <div class="link" id="home"></div>
        <div class="link" id="work"></div>
        <div class="link" id="contact"></div>
    </section>
</div>


问:
Enable and Disable manual proxy setting in Windows 8
I want to enable and disable manual proxy setup in windows 7,8 and 8. I want to toggle the manual proxy setup option using command script. I want to create a .bat file using command line and whenever I click on that .bat file, the manual proxy setup option will be toggled. I don't know the command for doing my job. I want to know the command for this job.
<img src="https://i.stack.imgur.com/n59Zf.jpg" alt="Required toggle option is marked">  </p>

答:
I agree with @Quirk this question is better placed in the super user group, but at the same time, users are drawn more often to StackOverflow and get discouraged when they don't find the answer.

Here is something I came up with, also my taught process:

all of Windows configurations that are flags or simple values are kept in the registry

you can manipulate the registry with the REG command

REG /? shows you what you can do

with regedit you can search the registry (F3) for your proxy host name

HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings

once you found the REG_KEY you are ready to write your script

in conclusion:

here is your 'command' for enabling your proxy:

REG ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet
  Settings" /v ProxyEnable /t REG_DWORD /d 1 /f

here is your 'command' for disabling your proxy:

REG ADD "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet
  Settings" /v ProxyEnable /t REG_DWORD /d 0 /f

It works, the value is set, but I am pretty sure your Network Settings Window does not get the update until the next time you open it.

Hope this helps.


问:
Java object, interface
using UI-Model i have a problem in blue J the problem code is
" class Operation is public , should be declared in a file named Operation.jave"
model class</p>

```<code>import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;

public class CalcModel extends Observable
{

    private JTextArea JDisplay;
 private JTextField JScreen;
     private OperandEntry eState;
    private String sScreen, sDisplay;
    private Operation operation;
    private double dOperand1,dOperand2;

        private void ClearData(boolean bAll)
    {
        sScreen = "";
        int a= 1;
        if (bAll == true)
        {
            sDisplay = ("");
            a= 3;
            eState = OperandEntry.First;
            operation = null;
        }
        SetUpdate(iChange);
        JScreen.setText("");

        }
    private void ProcessOpr()
    {
       dOperand2 = Double.parseDouble(sScreen);
       dOperand1 = objOpr.execute(dOperand1,dOperand2);
        sDisplay(dOperand2+ " = " + dOperand1+ " " );
        SetUpdate(x);
    }

      private Operation add = new Operation()
    {   public double execute(double d1,double d2)
        { return d1 + d2;
          SetUpdate(x);
        }
    };
     private Operation Div = new Operation()
        {

        public double execute(double d1,double d2)
        {

            return d1 /d2;
           SetUpdate(x);
        }

    };
    private Operation sub = new Operation()
    {
        public double execute(double d1,double d2)
        { return d1 -d2;
         SetUpdate(x);
        }
    };
    private Operation Multi = new Operation()
    {
        public double execute(double d1,double d2)
        {
            return d1 * d2;
            SetUpdate(x);
        }

    };
    private Operation Mag = new Operation()
    {
        public double execute(double d1,double d2)
         {
             if((int)d1 != d2 || (int)d1 != d1)
            {
                d1=(int)d1;
                d2=(int)d2;
                MsgInfo("Assuming Integers;" + d1 + " %" +d2);
            }

            return d1 % d2;
            SetUpdate(x);
        }

    };

    public void SetUpdate(ObservableState o)
    {
        setChanged();
        notifyObservers(o);
    }

  }
     public  interface Oparation
    {
        public double execute(double d1,double d2);
    }

     public  enum OperandEntry{
         First, Second,ResultFirst
        };
     public  enum ObservableState{ Screen,Display,Both};
</code>```

答:
In the line 100 you're declaring:

```<code>public interface Oparation {
...
</code>```

Each top level element ( class or interface in this case ) should be saved in its own file ( just like the error message indicates )

Save that portion into "Oparation.java" file and try again.

Title: Java object, interface

Body:
using UI-Model i have a problem in blue J the problem code is
" class Operation is public , should be declared in a file named Operation.jave"
model class

import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;

public class CalcModel extends Observable
{

    private JTextArea JDisplay;
 private JTextField JScreen;
     private OperandEntry eState;
    private String sScreen, sDisplay;
    private Operation operation;
    private double dOperand1,dOperand2;

        private void ClearData(boolean bAll)
    {
        sScreen = "";
        int a= 1;
        if (bAll == true)
        {
            sDisplay = ("");
            a= 3;
            eState = OperandEntry.First;
            operation = null;
        }
        SetUpdate(iChange);
        JScreen.setText("");

        }
    private void ProcessOpr()
    {
       dOperand2 = Double.parseDouble(sScreen);
       dOperand1 = objOpr.execute(dOperand1,dOperand2);
        sDisplay(dOperand2+ " = " + dOperand1+ " " );
        SetUpdate(x);
    }

      private Operation add = new Operation()
    {   public double execute(double d1,double d2)
        { return d1 + d2;
          SetUpdate(x);
        }
    };
     private Operation Div = new Operation()
        {

        public double execute(double d1,double d2)
        {

            return d1 /d2;
           SetUpdate(x);
        }

    };
    private Operation sub = new Operation()
    {
        public double execute(double d1,double d2)
        { return d1 -d2;
         SetUpdate(x);
        }
    };
    private Operation Multi = new Operation()
    {
        public double execute(double d1,double d2)
        {
            return d1 * d2;
            SetUpdate(x);
        }

    };
    private Operation Mag = new Operation()
    {
        public double execute(double d1,double d2)
         {
             if((int)d1 != d2 || (int)d1 != d1)
            {
                d1=(int)d1;
                d2=(int)d2;
                MsgInfo("Assuming Integers;" + d1 + " %" +d2);
            }

            return d1 % d2;
            SetUpdate(x);
        }

    };

    public void SetUpdate(ObservableState o)
    {
        setChanged();
        notifyObservers(o);
    }

  }
     public  interface Oparation
    {
        public double execute(double d1,double d2);
    }

     public  enum OperandEntry{
         First, Second,ResultFirst
        };
     public  enum ObservableState{ Screen,Display,Both};

Body:
In the line 100 you're declaring:

public interface Oparation {
...

Each top level element ( class or interface in this case ) should be saved in its own file ( just like the error message indicates )

Save that portion into "Oparation.java" file and try again.


问:
Missing data when Marshalling map to JSON
I'm trying to marshal to JSON a struct Foo that has a Values map[string]CellValue property where CellValue is another struct.  For some reason, the resultant JSON does not contain the data held in the CellValue struct even though all the keys in the Values map are present.

Here's a simple playground repro of the issue.

I'm new to Go, can anyone spot the problem here?

答: The fields of CellValue are unexported (start with a lowercase character). Per the documentation (emphasis mine), "Each exported struct field becomes a member of the object" - meaning unexported values are ignored when marshaling or unmarshaling.


问:
JavaFX capture events of a disabled button
In my application I have a multi step form wizard in which
the next button is disabled unless all the required fields are entered.

Some fields require extra validation such as the directory picker,
for which I have to check whether the directory exists or not.

To ease the user experience I need to show an "Invalid directory" tooltip
next to the directory text field.

I would like to show the tooltips when the user tries to click/enter the disabled
next button.

Is it possible to capture events performed on a disabled button in JavaFX?

```<code>public void nextEntered(Event event) {
    Button button = (Button)event.getSource();
    if(button.isDisabled()){
        validate(currentTab);
    }
}
</code>```

答:
I had a similar problem where I wanted to show a tooltip of a disabled field's value when the user moused over that disabled field.

I ended up putting a blank label over the disabled field and attaching a mouse event to that.

In the case of a button, you can just give the dummy label mouse transparency when the button becomes enabled so the user can click the button.

(You might even be able to bind the label's mouse transparency property to the button's enabled property but I'm not sure.)

I know this was asked a year ago but maybe it will help someone else.

Body:
In my application I have a multi step form wizard in which
the next button is disabled unless all the required fields are entered.

Some fields require extra validation such as the directory picker,
for which I have to check whether the directory exists or not.

To ease the user experience I need to show an "Invalid directory" tooltip
next to the directory text field.

I would like to show the tooltips when the user tries to click/enter the disabled
next button.

Is it possible to capture events performed on a disabled button in JavaFX?

public void nextEntered(Event event) {
    Button button = (Button)event.getSource();
    if(button.isDisabled()){
        validate(currentTab);
    }
}


问:
Running S3-put-triggered Lambda function on existing S3 objects?
I have a Lambda function in Node.js that processes new images added to my bucket. I want to run the function for all existing objects. How can I do this? I figured the easiest way is to "re-put" each object, to trigger the function, but I'm not sure how to do this.

To be clear - I want to run, one-time, on each of the existing objects. The trigger is already working for new objects, I just need to run it on the objects that were inserted before the lambda function was created.

答:
As I had to do this on a very large bucket, and lambda functions have a max. execution time of 10 minutes, I ended up doing a script with the Ruby AWS-SDK.

```<code>require 'aws-sdk-v1'

class LambdaS3Invoker

  BUCKET_NAME = "HERE_YOUR_BUCKET"
  FUNCTION_NAME = "HERE_YOUR_FUNCTION_NAME"
  AWS_KEY = "HERE_YOUR_AWS_KEY"
  AWS_SECRET = "HERE_YOUR_AWS_SECRET"
  REGION = "HERE_YOUR_REGION"

  def execute
    bucket.objects({ prefix: 'products'}).each do |o|
      lambda_invoke(o.key)
    end
  end

  private

  def lambda_invoke(key)
    lambda.invoke({
      function_name: FUNCTION_NAME,
      invocation_type: 'Event',
      payload: JSON.generate({
        Records: [{
          s3: {
            object: {
              key: key,
            },
            bucket: {
              name: BUCKET_NAME,
            }
          }
        }]
      })
    })
  end

  def lambda
    @lambda ||= Aws::Lambda::Client.new(
      region: REGION,
      access_key_id: AWS_KEY,
      secret_access_key: AWS_SECRET
    )
  end

  def resource
    @resource ||= Aws::S3::Resource.new(
      access_key_id: AWS_KEY,
      secret_access_key: AWS_SECRET
    )
  end

  def bucket
    @bucket ||= resource.bucket(BUCKET_NAME)
  end
end
</code>```

And then you can call it like:

```<code>LambdaS3Invoker.new.execute
</code>```

Body:
As I had to do this on a very large bucket, and lambda functions have a max. execution time of 10 minutes, I ended up doing a script with the Ruby AWS-SDK.

require 'aws-sdk-v1'

class LambdaS3Invoker

  BUCKET_NAME = "HERE_YOUR_BUCKET"
  FUNCTION_NAME = "HERE_YOUR_FUNCTION_NAME"
  AWS_KEY = "HERE_YOUR_AWS_KEY"
  AWS_SECRET = "HERE_YOUR_AWS_SECRET"
  REGION = "HERE_YOUR_REGION"

  def execute
    bucket.objects({ prefix: 'products'}).each do |o|
      lambda_invoke(o.key)
    end
  end

  private

  def lambda_invoke(key)
    lambda.invoke({
      function_name: FUNCTION_NAME,
      invocation_type: 'Event',
      payload: JSON.generate({
        Records: [{
          s3: {
            object: {
              key: key,
            },
            bucket: {
              name: BUCKET_NAME,
            }
          }
        }]
      })
    })
  end

  def lambda
    @lambda ||= Aws::Lambda::Client.new(
      region: REGION,
      access_key_id: AWS_KEY,
      secret_access_key: AWS_SECRET
    )
  end

  def resource
    @resource ||= Aws::S3::Resource.new(
      access_key_id: AWS_KEY,
      secret_access_key: AWS_SECRET
    )
  end

  def bucket
    @bucket ||= resource.bucket(BUCKET_NAME)
  end
end

And then you can call it like:

LambdaS3Invoker.new.execute


问:
Two different DataTemplate
I have two ListBoxs defined in my XAML and one Class MyListItem.
Now one ListBox should display the name as button and the second ListBox should display the name as a TextBlock.

Here a little example, both ListBoxs behave the same.

MyListItem

```<code>public class MyListItem
{
    private string _name;
    public string Name
    {
        get{return _name;}
        set{_name = value;}
    }
}
</code>```

XAML

```<code><Window xmlns="https://github.com/avaloniaui"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:DataTemplate.Views.MainWindow"
    xmlns:viewsmodels="clr-namespace:DataTemplate.ViewModels;assembly=DataTemplate"
    xmlns:dt="clr-namespace:DataTemplate;assembly=DataTemplate"
    Title="DataTemplate" Width="700">
<Window.DataContext>
  <viewsmodels:MainWindowViewModel />
</Window.DataContext>
<Grid ColumnDefinitions="250,250,250">
  <ItemsControl Grid.Column="1" Items="{Binding List2}">
    <ItemsControl.DataTemplates>
      <DataTemplate DataType="{x:Type dt:MyListItem}">
        <TextBlock Text="{Binding Name}"/>
      </DataTemplate>
    </ItemsControl.DataTemplates>
  </ItemsControl>
  <ItemsControl Grid.Column="2" Items="{Binding List3}">
    <ItemsControl.DataTemplates>
      <DataTemplate DataType="{x:Type dt:MyListItem}">
        <Button Content="{Binding Name}"/>
      </DataTemplate>
    </ItemsControl.DataTemplates>
  </ItemsControl>
</Grid>
</Window>
</code>```

ViewMode

```<code>public class MainWindowViewModel
{
            public ObservableCollection<MyListItem> List1 { get; set; }
    public ObservableCollection<MyListItem> List2 { get; set; }
    public ObservableCollection<MyListItem> List3 { get; set; }

    public MainWindowViewModel()
    {
        List1 = new ObservableCollection<MyListItem>();
        List2 = new ObservableCollection<MyListItem>();
        List3 = new ObservableCollection<MyListItem>();

        Random rand = new Random();

        for (int i = 0; i < rand.Next(1, 20); i++)
        {
            MyListItem mli = new MyListItem();
            mli.Name = "ListItem" + i;
            List1.Add(mli);
        }

        for (int i = 0; i < rand.Next(1, 20); i++)
        {
            MyListItem mli = new MyListItem();
            mli.Name = "ListItem" + i;
            List2.Add(mli);
        }

        for (int i = 0; i < rand.Next(1, 20); i++)
        {
            MyListItem mli = new MyListItem();
            mli.Name = "ListItem" + i;
            List3.Add(mli);
        }
    }
}
</code>```

Title: Two different DataTemplate

Body:
I have two ListBoxs defined in my XAML and one Class MyListItem.
Now one ListBox should display the name as button and the second ListBox should display the name as a TextBlock.

Here a little example, both ListBoxs behave the same.

MyListItem

public class MyListItem
{
    private string _name;
    public string Name
    {
        get{return _name;}
        set{_name = value;}
    }
}

XAML

<Window xmlns="https://github.com/avaloniaui"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:DataTemplate.Views.MainWindow"
    xmlns:viewsmodels="clr-namespace:DataTemplate.ViewModels;assembly=DataTemplate"
    xmlns:dt="clr-namespace:DataTemplate;assembly=DataTemplate"
    Title="DataTemplate" Width="700">
<Window.DataContext>
  <viewsmodels:MainWindowViewModel />
</Window.DataContext>
<Grid ColumnDefinitions="250,250,250">
  <ItemsControl Grid.Column="1" Items="{Binding List2}">
    <ItemsControl.DataTemplates>
      <DataTemplate DataType="{x:Type dt:MyListItem}">
        <TextBlock Text="{Binding Name}"/>
      </DataTemplate>
    </ItemsControl.DataTemplates>
  </ItemsControl>
  <ItemsControl Grid.Column="2" Items="{Binding List3}">
    <ItemsControl.DataTemplates>
      <DataTemplate DataType="{x:Type dt:MyListItem}">
        <Button Content="{Binding Name}"/>
      </DataTemplate>
    </ItemsControl.DataTemplates>
  </ItemsControl>
</Grid>
</Window>

ViewMode

public class MainWindowViewModel
{
            public ObservableCollection<MyListItem> List1 { get; set; }
    public ObservableCollection<MyListItem> List2 { get; set; }
    public ObservableCollection<MyListItem> List3 { get; set; }

    public MainWindowViewModel()
    {
        List1 = new ObservableCollection<MyListItem>();
        List2 = new ObservableCollection<MyListItem>();
        List3 = new ObservableCollection<MyListItem>();

        Random rand = new Random();

        for (int i = 0; i < rand.Next(1, 20); i++)
        {
            MyListItem mli = new MyListItem();
            mli.Name = "ListItem" + i;
            List1.Add(mli);
        }

        for (int i = 0; i < rand.Next(1, 20); i++)
        {
            MyListItem mli = new MyListItem();
            mli.Name = "ListItem" + i;
            List2.Add(mli);
        }

        for (int i = 0; i < rand.Next(1, 20); i++)
        {
            MyListItem mli = new MyListItem();
            mli.Name = "ListItem" + i;
            List3.Add(mli);
        }
    }
}

Body:
Unfortunately there's currently no good way to do this in Avalonia that I can think of. The most obvious way would be to add the data templates to a <Style.Resources> collection and use {StyleResource} to reference them, but this doesn't work currently.

I think you have two alternatives here for the moment:

Just copy and paste the data templates into the ItemsControl.ItemTemplate

Define the data templates in code and reference them using {Static}. For this you can use FuncDataTemplate<>

I've added an issue to track this problem here: https://github.com/AvaloniaUI/Avalonia/issues/1020


答:
You can also unpack your data using list comprehension:

```<code>final = [(v,) for _, v in yourlist]
</code>```

Title: how do I remove from tuples in a list of tuples

Body:
I have a list of tuples like this

[
  ('px', Timestamp('2017-07-01 00:00:00')),
  ('px', Timestamp('2017-08-01 00:00:00')),
  ('px', Timestamp('2017-09-01 00:00:00')),
  ('px', Timestamp('2017-10-01 00:00:00')),
  ('px', Timestamp('2017-11-01 00:00:00'))
]

and want to remove the 'px' keeping only the timestamps as a tuple.

Body:
You can also unpack your data using list comprehension:

final = [(v,) for _, v in yourlist]


问:
How do I track file downloads
I have a website that plays mp3s in a flash player. If a user clicks 'play' the flash player automatically downloads an mp3 and starts playing it.

Is there an easy way to track how many times a particular song clip (or any binary file) has been downloaded?

Is the play link a link to the actual
  mp3 file or to some javascript code
  that pops up a player?

If the latter, you can easily add your
  own logging code in there to track the
  number of hits to it.

If the former, you'll need something
  that can track the web server log
  itself and make that distinction. My
  hosting plan comes with Webalizer,
  which does this nicely.

It's a javascript code so that answers that.

However, it would be nice to know how to track downloads using the other method (without switching hosts).

答:
Is there a database for your music library? If there is any server code that runs when downloading the mp3 then you can add extra code there to increment the play count. You could also have javascript make a second request to increment the play count, but this could lead to people/robots falsely incrementing counts.

I used to work for an internet-radio site and we used separate tables to track the time every song was played. Our streams were powered by a perl script running icecast, so we triggered a database request every time a new track started playing. Then to compute the play count we would run a query to count how many times a song's id was in the play log.

Title: How do I track file downloads

OwnerDisplayName: Mike H


问:
Count Stored Procedures in Database?
How can i count the number of stored procedures in my database and is it a bad practice to have too many stored procedures?</p>

答:
This will exclude the ones that sometimes get created when using the diagramming tool (they will start with dt_)</p>

```<code>SELECT * FROM information_schema.routines
WHERE OBJECTPROPERTY(OBJECT_ID(SPECIFIC_NAME),'IsMSShipped') =1
AND  routine_type = 'PROCEDURE'
</code>```

OwnerDisplayName: Jack

Title: Count Stored Procedures in Database?

LastEditorDisplayName: Cade Roux

Body:
This will exclude the ones that sometimes get created when using the diagramming tool (they will start with dt_)

SELECT * FROM information_schema.routines
WHERE OBJECTPROPERTY(OBJECT_ID(SPECIFIC_NAME),'IsMSShipped') =1
AND  routine_type = 'PROCEDURE'

OwnerDisplayName: SQLMenace


问:
Replace a range of numbers with different range of numbers in SQL
For example replace

```<code>TransactionID
--------
 1
 2
 3
</code>```

with

```<code>TransactionID
--------
 95
 96
 97
</code>```

respectively. Basically, I want to replace numbers with numbers but for multiple items without writing update statement for each item.

Example:

```<code>Update BatchItem
    set TransactionID = '95'
    where BatchItemID = 12345**6**

Update BatchItem
    set TransactionID = '96'
    where BatchItemID = 12345**7**

Update BatchItem
    set TransactionID = '97'
    where BatchItemID = 12345**8**
</code>```

How do I write above statement to update multiple transactionID in sequence?

答:
Not 100% sure I understand what you're trying to achieve. Are you trying to do something like this?</p>

```<code>declare @offset int
set @offset = 94

update BatchItem
    set TransactionID = TransactionID + @offset
    where BatchItemID = 123456
</code>```

Body:
For example replace

TransactionID
--------
 1
 2
 3

with

TransactionID
--------
 95
 96
 97

respectively. Basically, I want to replace numbers with numbers but for multiple items without writing update statement for each item.

Example:

Update BatchItem
    set TransactionID = '95'
    where BatchItemID = 12345**6**

Update BatchItem
    set TransactionID = '96'
    where BatchItemID = 12345**7**

Update BatchItem
    set TransactionID = '97'
    where BatchItemID = 12345**8**

How do I write above statement to update multiple transactionID in sequence?

Body:
Not 100% sure I understand what you're trying to achieve. Are you trying to do something like this?

declare @offset int
set @offset = 94

update BatchItem
    set TransactionID = TransactionID + @offset
    where BatchItemID = 123456


答:
Adding this CSS should do what you need. Using display: table and display: table-cell with a vertical-align: middle will allow you to center it both vertically and horizontally.

#landingpage {
    width: 100%;
    height: 100vh;
    display: table;
    text-align: center;
}

#links{
    margin: auto;
    display: table-cell;
    vertical-align: middle;
}
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
    margin: 0;
    padding: 0;
    background-color: rgb(0, 0, 0);
}

#landingpage {
    width: 100%;
    height: 100vh;
    display: table;
    text-align: center;
}

#links{
    margin: auto;
    display: table-cell;
    vertical-align: middle;
}

.link{
    display: inline-block;
    margin: 0 2%;
    width: 15vw;
    height: 15vw;
    border: 2px solid rgb(100, 100, 0);
    border-radius: 50%;
    background-image: url("line.png");
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
    background-color: rgb(0, 0, 50);
}

.link:first-of-type{
    margin-left: 0;
}

.link:last-of-type{
    margin-right: 0;
}</code>```

```

Codepen: https://codepen.io/anon/pen/owbgQp

Title: Can anyone explain why a section isn't centering on my page?

Body:
Adding this CSS should do what you need. Using display: table and display: table-cell with a vertical-align: middle will allow you to center it both vertically and horizontally.

#landingpage {
    width: 100%;
    height: 100vh;
    display: table;
    text-align: center;
}

#links{
    margin: auto;
    display: table-cell;
    vertical-align: middle;
}

body{
    margin: 0;
    padding: 0;
    background-color: rgb(0, 0, 0);
}

#landingpage {
    width: 100%;
    height: 100vh;
    display: table;
    text-align: center;
}

#links{
    margin: auto;
    display: table-cell;
    vertical-align: middle;
}

.link{
    display: inline-block;
    margin: 0 2%;
    width: 15vw;
    height: 15vw;
    border: 2px solid rgb(100, 100, 0);
    border-radius: 50%;
    background-image: url("line.png");
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
    background-color: rgb(0, 0, 50);
}

.link:first-of-type{
    margin-left: 0;
}

.link:last-of-type{
    margin-right: 0;
}

<div id="landingpage">
    <section id="links">
        <div class="link" id="home"></div>
        <div class="link" id="work"></div>
        <div class="link" id="contact"></div>
    </section>
</div>

Codepen: https://codepen.io/anon/pen/owbgQp


问:
{"error":"unsupported_grant_type"} for angular call
My api post call for retrieving a jwt token responds with 400 error. Here is my api angular call.  I tried with URLSearchparams too.</p>

```<code>authenticateUser(userid: string, password: string) {
        // var authorization_grant = "password";
        // let body = new URLSearchParams();
        // body.append('username', userid);
        // body.append('password', password);
        // body.append('grant_type', authorization_grant);
        let body = 'userName=' + userid+ '&password=' +password +'&grant_type=password';
        let headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        headers.append('Access-Control-Allow-Origin', '*');
        let options = new RequestOptions({ headers: headers });

        return this.http.post(this.config.apiBaseUrl + '/token', body, options).retry(3).map((res: Response) => {
            if (res.status == 200) {
                this.validatedUser = res.json();
                localStorage.setItem("access_token", this.validatedUser.access_token);
            }
            return this.validatedUser;
        })
    }
</code>```

答:
OK, after investigating the traffic in Fiddler tool, I compared the headers when called from postman vs angular.

On Client-Side:
I removed line headers.append('Access-Control-Allow-Origin', '*'); from my code which resolved this issue.

On Server-Side
Most importantly I moved app.UseCors(CorsOptions.AllowAll) line of code on top of app.UseOAuthAuthorizationServer where I generate token in my startup.cs.

Thanks @jps, @biswajit-rout and @Ruard Van Elburg for looking into it.

Body:
My api post call for retrieving a jwt token responds with 400 error. Here is my api angular call.  I tried with URLSearchparams too.

authenticateUser(userid: string, password: string) {
        // var authorization_grant = "password";
        // let body = new URLSearchParams();
        // body.append('username', userid);
        // body.append('password', password);
        // body.append('grant_type', authorization_grant);
        let body = 'userName=' + userid+ '&password=' +password +'&grant_type=password';
        let headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        headers.append('Access-Control-Allow-Origin', '*');
        let options = new RequestOptions({ headers: headers });

        return this.http.post(this.config.apiBaseUrl + '/token', body, options).retry(3).map((res: Response) => {
            if (res.status == 200) {
                this.validatedUser = res.json();
                localStorage.setItem("access_token", this.validatedUser.access_token);
            }
            return this.validatedUser;
        })
    }


问:
Windows 10 UWP C# Barcode Sample does not see scanner
I've been trying to get my scanner to work in this UWP sample, Windows-universal-samples/Samples/BarcodeScanner/cs/. However, my scanner Honeywell Xenon 1900GHD-2 is not found as a valid scanner. The project reports "Barcode scanner not found. Please connect a barcode scanner."

This particular scanner (Honeywell Xenon 1900G) is listed on the Windows compatibility list, yet doesn't work. I've tried using Honeywell's EZConfig utility to force the scanner into dedicated HID POS mode (I've actually tried all of its available modes) and it makes no difference.

I'm running Windows 10 Anniversary Update, so it should work as noted in the sample project, Windows 10 Version 1703 is the SDK target.

Any idea why it's not working?

答:
I ran into something similar recently, and I found this
barcode while going through Honeywell Voyager 1200g manual. After scanning this, the device is being recognized as a POS Barcode Scanner in my Device Manager. And the UWP Barcode Sample solution was able to recognize the device as well. Apart from that, make sure that PointOfService is mentioned in the Device Capabilities in the appxmanifest file.</p>


问:
How to get Javascript variable value into CSS?
How can I have the time variable's contents displayed as the content property in my CSS?

JavaScript:

function clock(){
    var d = new Date();
    var hour = d.getHours();
    var min = d.getMinutes();
    var time = hour + ":" + min;
}
```

<p>CSS:</p>

<pre class="lang-css prettyprint-override"><code>.screen{
    position: absolute;
    height: 75%;
    width: 75%;
    background: #98E8EE;
    top: 11.5%;
    left: 12.5%;
}

.screen::after{
    color: #F9F5F4;
    font-size: 40px;
    content: ;
    font-family: Arial;
    margin-left: 36.5px;
    top: 20px;
    position: relative
}
</code>```

答:
Not sure what you're going for, but if you want the value of time to appear on your page, formatted using your css, maybe this?

document.write( '
' + time + '
 );

Or this?

var timeDiv = document.createElement('div');
timeDiv.classList.add('screen');
document.body.appendChild(timeDiv);

Just guessing.  Usually CSS defines how things are formatted, so I'm not sure what you're asking.

Body:
How can I have the time variable's contents displayed as the content property in my CSS?

JavaScript:

function clock(){
    var d = new Date();
    var hour = d.getHours();
    var min = d.getMinutes();
    var time = hour + ":" + min;
}

CSS:

.screen{
    position: absolute;
    height: 75%;
    width: 75%;
    background: #98E8EE;
    top: 11.5%;
    left: 12.5%;
}

.screen::after{
    color: #F9F5F4;
    font-size: 40px;
    content: ;
    font-family: Arial;
    margin-left: 36.5px;
    top: 20px;
    position: relative
}

Body:
Not sure what you're going for, but if you want the value of time to appear on your page, formatted using your css, maybe this?

document.write( '<p class="screen">' + time + '</p> );

Or this?

var timeDiv = document.createElement('div');
timeDiv.classList.add('screen');
document.body.appendChild(timeDiv);

Just guessing.  Usually CSS defines how things are formatted, so I'm not sure what you're asking.


问:
Get attribute of viewcontroller created with storyboard
I'm currently learning swift and I'm trying to learn of instanciation from storyboard works, but the error I'm facing now isn't documented very much.

I created a viewcontroller in my main storyboard and I specified it's type as a custom class I called previously SimpleNewsViewController, here's the code of my class, it is'nt complicated:

```<code>class SimpleNewsViewController: UIViewController {

@IBOutlet weak var myImage: UIImageView!
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myText: UITextView!

var event: Events!

override func viewDidLoad() {
    super.viewDidLoad()
}
</code>```

}

On my main storyboard here is the custom ViewController I specified :
My Storyboard implementation

Now here's the problem : In my code I instanciate my ViewController thanks to the instanciateViewController(identifier: "NewsView") and then I try to set my 3 attributes like in this piece of code :

```<code>...
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "NewsView") as! SimpleNewsViewController
    //controller.myImage.image = UIImage(named: "image.jpg")
    //controller.myText.text = "this is an example that can be really long"
    //controller.myTitle.text = "this is a title example
    self.navigationController?.pushViewController(controller, animated: true)
...
</code>```

If I un-comment the three lines I have an error saying:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

The IDE also displays the error code and the thread (if that can help):
The error

答:
Right after instantiating the controller the outlets are not connected yet, you have to declare temporary variables and set the outlet properties in viewDidLoad()

```<code>...
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "NewsView") as! SimpleNewsViewController
    controller.tempImage = UIImage(named: "image.jpg")
    controller.tempLabel = "this is an example that can be really long"
    controller.tempText = "this is a title example
    self.navigationController?.pushViewController(controller, animated: true)
...
</code>```

```<code>class SimpleNewsViewController: UIViewController {

@IBOutlet weak var myImage: UIImageView!
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myText: UITextView!

var tempImage : UIImage?
var tempLabel = ""
var tempText = ""

var event: Events!

override func viewDidLoad() {
    super.viewDidLoad()
    myImage.image = tempImage
    myLabel.text = tempLabel
    tempText.text = tempText
}
</code>```

Body:
I'm currently learning swift and I'm trying to learn of instanciation from storyboard works, but the error I'm facing now isn't documented very much.

I created a viewcontroller in my main storyboard and I specified it's type as a custom class I called previously SimpleNewsViewController, here's the code of my class, it is'nt complicated:

class SimpleNewsViewController: UIViewController {

@IBOutlet weak var myImage: UIImageView!
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myText: UITextView!

var event: Events!

override func viewDidLoad() {
    super.viewDidLoad()
}

}

On my main storyboard here is the custom ViewController I specified :
My Storyboard implementation

Now here's the problem : In my code I instanciate my ViewController thanks to the instanciateViewController(identifier: "NewsView") and then I try to set my 3 attributes like in this piece of code :

...
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "NewsView") as! SimpleNewsViewController
    //controller.myImage.image = UIImage(named: "image.jpg")
    //controller.myText.text = "this is an example that can be really long"
    //controller.myTitle.text = "this is a title example
    self.navigationController?.pushViewController(controller, animated: true)
...

If I un-comment the three lines I have an error saying:

Fatal error: Unexpectedly found nil while unwrapping an Optional value

The IDE also displays the error code and the thread (if that can help):
The error

Body:
Right after instantiating the controller the outlets are not connected yet, you have to declare temporary variables and set the outlet properties in viewDidLoad()

...
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "NewsView") as! SimpleNewsViewController
    controller.tempImage = UIImage(named: "image.jpg")
    controller.tempLabel = "this is an example that can be really long"
    controller.tempText = "this is a title example
    self.navigationController?.pushViewController(controller, animated: true)
...

class SimpleNewsViewController: UIViewController {

@IBOutlet weak var myImage: UIImageView!
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myText: UITextView!

var tempImage : UIImage?
var tempLabel = ""
var tempText = ""

var event: Events!

override func viewDidLoad() {
    super.viewDidLoad()
    myImage.image = tempImage
    myLabel.text = tempLabel
    tempText.text = tempText
}


答:
First of all, you've misspelled Operation in the interface definition. I don't know if that's a typo here or in your source

Second of all, a public interface or class needs to be in its own file. There's no reason that you can't have a file-local class:

```<code>interface Operation { ... }
</code>```

or even a public class inside of another:

```<code>public class CalcModel extends Observable {
    ...
    public class Operation { ... }
}
</code>```

You can the access the class as CalcModel.Operation

The error tells you all this. The class can't be public, or it needs to be in its own file.

Title: Java object, interface

Body:
using UI-Model i have a problem in blue J the problem code is
" class Operation is public , should be declared in a file named Operation.jave"
model class

import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;

public class CalcModel extends Observable
{

    private JTextArea JDisplay;
 private JTextField JScreen;
     private OperandEntry eState;
    private String sScreen, sDisplay;
    private Operation operation;
    private double dOperand1,dOperand2;

        private void ClearData(boolean bAll)
    {
        sScreen = "";
        int a= 1;
        if (bAll == true)
        {
            sDisplay = ("");
            a= 3;
            eState = OperandEntry.First;
            operation = null;
        }
        SetUpdate(iChange);
        JScreen.setText("");

        }
    private void ProcessOpr()
    {
       dOperand2 = Double.parseDouble(sScreen);
       dOperand1 = objOpr.execute(dOperand1,dOperand2);
        sDisplay(dOperand2+ " = " + dOperand1+ " " );
        SetUpdate(x);
    }

      private Operation add = new Operation()
    {   public double execute(double d1,double d2)
        { return d1 + d2;
          SetUpdate(x);
        }
    };
     private Operation Div = new Operation()
        {

        public double execute(double d1,double d2)
        {

            return d1 /d2;
           SetUpdate(x);
        }

    };
    private Operation sub = new Operation()
    {
        public double execute(double d1,double d2)
        { return d1 -d2;
         SetUpdate(x);
        }
    };
    private Operation Multi = new Operation()
    {
        public double execute(double d1,double d2)
        {
            return d1 * d2;
            SetUpdate(x);
        }

    };
    private Operation Mag = new Operation()
    {
        public double execute(double d1,double d2)
         {
             if((int)d1 != d2 || (int)d1 != d1)
            {
                d1=(int)d1;
                d2=(int)d2;
                MsgInfo("Assuming Integers;" + d1 + " %" +d2);
            }

            return d1 % d2;
            SetUpdate(x);
        }

    };

    public void SetUpdate(ObservableState o)
    {
        setChanged();
        notifyObservers(o);
    }

  }
     public  interface Oparation
    {
        public double execute(double d1,double d2);
    }

     public  enum OperandEntry{
         First, Second,ResultFirst
        };
     public  enum ObservableState{ Screen,Display,Both};

Body:
First of all, you've misspelled Operation in the interface definition. I don't know if that's a typo here or in your source

Second of all, a public interface or class needs to be in its own file. There's no reason that you can't have a file-local class:

interface Operation { ... }

or even a public class inside of another:

public class CalcModel extends Observable {
    ...
    public class Operation { ... }
}

You can the access the class as CalcModel.Operation

The error tells you all this. The class can't be public, or it needs to be in its own file.


问:
Disable @media in css
I have some set of CSS classes and in one of classes we track max width of sized window and change styles if it is less then 100.

```<code>@media all and (max-width: 100px) {
   some code...
}
</code>```

So I need to prevent changing styles when window is width is less than 100. In other words how I can overload current @media and disable it, only by CSS way (not javascript, jQuery)?

答:
You can add a class to body (for example .no-media) and add styles for this class:

```<code>@media all and (max-width: 100) {
  .no-media p {
    color: red;
  }
}
</code>```

You can also use !important to force some CSS rules:

```<code>p {
  color: red !important;
}
</code>```

Title: Disable @media in css

Body:
I have some set of CSS classes and in one of classes we track max width of sized window and change styles if it is less then 100.

@media all and (max-width: 100px) {
   some code...
}

So I need to prevent changing styles when window is width is less than 100. In other words how I can overload current @media and disable it, only by CSS way (not javascript, jQuery)?

Body:
You can add a class to body (for example .no-media) and add styles for this class:

@media all and (max-width: 100) {
  .no-media p {
    color: red;
  }
}

You can also use !important to force some CSS rules:

p {
  color: red !important;
}


问:
"Don't know how to convert parameter" error in Python
When I run the below code, I am getting "Don't know how to convert parameter"error. I am trying islice to cut my name. Kindly help.</p>

```<code>import ctypes
from itertools import islice

i = "sakthi srinivasan"
sliced_text =  islice(i, 0, 6)
ctypes.windll.user32.MessageBoxW(0, sliced_text, "MsgBox", 0)
</code>```

答:
The second argument to MessageBoxW is a string1. The function itertools.islice returns an iterator over the characters in i. Since ctypes can't figure out how to cast that to a character array, it throws the error "Don't know how to convert parameter...".

You could convert the iterator to a string with ''.join(sliced_text), but the best way to do so here is by using the slicing built into Python strings by passing i[0:6] as the second argument. That is the standard way to get a substring in Python.

1 Technically, an LPCTSTR, which is either a const char* or const wchar_t*, depending on whether or not you compile in UNICODE configuration.

Body:
When I run the below code, I am getting "Don't know how to convert parameter"error. I am trying islice to cut my name. Kindly help.

import ctypes
from itertools import islice

i = "sakthi srinivasan"
sliced_text =  islice(i, 0, 6)
ctypes.windll.user32.MessageBoxW(0, sliced_text, "MsgBox", 0)


答:
#link{
    margin : auto;
    text-align : center;
}
```

Do the following additions.
When you apply display:inline-block on the children elements, they act as a text and by default align themselves in left align.

But what I have done will pass on this property to all the children elements, so if in case you want any of the children elements to align left or right, you may mention that in CSS.

Body:
I'm trying to center a few elements on my page vertically and horizontally, but for some reason, setting the container element to have a margin of auto isn't centering them.  Can anyone explain why?

HTML/CSS

body{
 margin: 0;
 padding: 0;
 background-color: rgb(0, 0, 0);
}

#links{
 margin: auto;
}

.link{
 display: inline-block;
 margin: 0 2%;
 width: 15vw;
 height: 15vw;
 border: 2px solid rgb(100, 100, 0);
 border-radius: 50%;
 background-image: url("line.png");
 background-repeat: no-repeat;
 background-size: contain;
 background-position: center;
 background-color: rgb(0, 0, 50);
}

.link:first-of-type{
 margin-left: 0;
}

.link:last-of-type{
 margin-right: 0;
}

Pen

Body:
#link{
    margin : auto;
    text-align : center;
}

Do the following additions.
When you apply display:inline-block on the children elements, they act as a text and by default align themselves in left align.

But what I have done will pass on this property to all the children elements, so if in case you want any of the children elements to align left or right, you may mention that in CSS.


问:
hava jabber-bot. XMPP over smack 4.2.0 with TLS
I need to develop mini jabber-bot. I have an openfire server with only TLS connection rules. I used to smack 4.2.0 - last stable build from http://www.igniterealtime.org/downloads/ I try to connect but have an exception:
code:

```<code>XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
                .setUsernameAndPassword("testjava", "12345678")
                .setServiceName(server)
                .setPort(5222)
                .setHost(server)                    .setSecurityMode(ConnectionConfiguration.SecurityMode.required)
                .setDebuggerEnabled(true)
                .build();

        AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);

        conn2.connect();
</code>```

Log:

```<code>10:35:31 AM SENT (0): <stream:stream xmlns='jabber:client' to='***.pro' xmlns:stream='http://etherx.jabber.org/streams' version='1.0' from='testjava@***.pro' xml:lang='en'>
10:35:31 AM RECV (0): <?xml version='1.0' encoding='UTF-8'?><stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" from="***.pro" id="xb9bamjxw" xml:lang="en" version="1.0">
10:35:32 AM RECV (0): <stream:features><starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"><required/></starttls><mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><mechanism>PLAIN</mechanism></mechanisms></stream:features>
10:35:32 AM SENT (0): <starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>
10:35:32 AM RECV (0): <proceed xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>
Exception in thread "main" org.jivesoftware.smack.SmackException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1010)
    at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$200(XMPPTCPConnection.java:937)
    at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:952)
    at java.lang.Thread.run(Thread.java:745)
</code>```

I use Pidgin and have establish connect to the server. What  need I to add to my code to support TLS authenticat?

答: It looks like your server doesn't have a 'valid' certificate.  Buy a valid certificate, or configure the library to allow 'untrusted' certificates.</p>

Body:
I need to develop mini jabber-bot. I have an openfire server with only TLS connection rules. I used to smack 4.2.0 - last stable build from http://www.igniterealtime.org/downloads/ I try to connect but have an exception:
code:

XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
                .setUsernameAndPassword("testjava", "12345678")
                .setServiceName(server)
                .setPort(5222)
                .setHost(server)                    .setSecurityMode(ConnectionConfiguration.SecurityMode.required)
                .setDebuggerEnabled(true)
                .build();

        AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);

        conn2.connect();

Log:

10:35:31 AM SENT (0): <stream:stream xmlns='jabber:client' to='***.pro' xmlns:stream='http://etherx.jabber.org/streams' version='1.0' from='testjava@***.pro' xml:lang='en'>
10:35:31 AM RECV (0): <?xml version='1.0' encoding='UTF-8'?><stream:stream xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" from="***.pro" id="xb9bamjxw" xml:lang="en" version="1.0">
10:35:32 AM RECV (0): <stream:features><starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"><required/></starttls><mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><mechanism>PLAIN</mechanism></mechanisms></stream:features>
10:35:32 AM SENT (0): <starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'></starttls>
10:35:32 AM RECV (0): <proceed xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>
Exception in thread "main" org.jivesoftware.smack.SmackException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1010)
    at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$200(XMPPTCPConnection.java:937)
    at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:952)
    at java.lang.Thread.run(Thread.java:745)

I use Pidgin and have establish connect to the server. What  need I to add to my code to support TLS authenticat?


问:
concatenate two lists of string in r
Here is my sample:

```<code>a = c("a","b","c")
b = c("1","2","3")
</code>```

I need to concatenate a and b automatically. The result should be "a 1","a 2","a 3","b 1","b 2","b 3","c 1","c 2","c 3".

For now, I am using the paste function:

```<code>paste(a[1],b[1])
</code>```

I need an automatic way to do this. Besides writing a loop, is there any easier way to achieve this?

答:
Other options are :

```<code>paste(rep.int(a,length(b)),b)
</code>```

or :

```<code>with(expand.grid(b,a),paste(Var2,Var1))
</code>```

Title: concatenate two lists of string in r

Body:
Here is my sample:

a = c("a","b","c")
b = c("1","2","3")

I need to concatenate a and b automatically. The result should be "a 1","a 2","a 3","b 1","b 2","b 3","c 1","c 2","c 3".

For now, I am using the paste function:

paste(a[1],b[1])

I need an automatic way to do this. Besides writing a loop, is there any easier way to achieve this?

Body:
Other options are :

paste(rep.int(a,length(b)),b)

or :

with(expand.grid(b,a),paste(Var2,Var1))


问:
How to sort key/value objects in javascript?
Following How can I add a key/value pair to a JavaScript object? and Best way to store a key=>value array in JavaScript?, I built my Key/Value map (object).

And I build it like below where MyFunc returns an array:

```<code>let MyMap = {}; // object
for(let i = 0; i < MyContainer.length; i++)
{
   // create the key (id of current element) and set its value as array of elements (result from MyFunc)
   await MyFunc(MyContainer[i]).then((response) => MyMap[MyContainer[i].id] = response);
}
</code>```

MyMap look like this:

```<code>MyMap =
{
   1: [Object, Object, Object, …] // 13 elements
   2: [Object, Object, Object, …] // 7 elements
   3: [Object, Object, Object, …] // 4 elements
   4: [Object]
   5: [Object]
   6: [Object, Object, Object, …] // 5 elements
   7: [Object, Object, Object, …] // 9 elements
}
</code>```

I would like to iterate my map (keys) but starting from the key that has the smallest value (The smallest array).

Therefore, I would like to:

access MyContainer and pick the element that has id 4, and do stuff (has the smallest array: 1 element)

then access MyContainer and pick the element that has id 5, and do stuff

then 3

then 6

.. etc

and finally access MyContainer and pick the element that has id 1 and do stuff (has the largest array: 13 elements)

Now since myMap is an object, then I can't sort it.

How can I accomplish this?

答:
Eventually, you won't be able to use an Object because the order of the keys is not guaranteed.

You can:

Use Object.keys(obj) to get the keys of your object as an Array

Use those keys to build an Array of objects of your structure, each item in the array being the key/value pair of your original object.

Then sort that Arrayof objects based on the length of each item.value within it. The item.value in this case is your original object's values which are Arrays

const obj = {
  "1": [1, 2, 3],
  "2": [1],
  "3": [1, 2],
  "4": [1, 2, 3, 4]
};

// Transform object into a nested array
// Each array item contains the value of a key of your original object,
// which itself is an Array
const arr = Object.keys(obj).reduce((arr, key) => {
 arr.push({ key: key, value: obj[key] });

 return arr;
}, [])

// Sort the nested Array based on the length of each item
const sortedArr = arr.sort((a, b) => a.value.length - b.value.length);

console.log(sortedArr);```
</div>
</div>
</p>

<h2>Same as above but more compact, using chaining</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const obj = {
  "1": [1, 2, 3],
  "2": [1],
  "3": [1, 2],
  "4": [1, 2, 3, 4]
};

const sortedArr = Object.keys(obj).reduce((arr, key) => {
  arr.push({ key: key, value: obj[key] });

  return arr;
}, [])
.sort((a, b) => a.value.length - b.value.length)

console.log(sortedArr);</code>```

Body:
Following How can I add a key/value pair to a JavaScript object? and Best way to store a key=>value array in JavaScript?, I built my Key/Value map (object).

And I build it like below where MyFunc returns an array:

let MyMap = {}; // object
for(let i = 0; i < MyContainer.length; i++)
{
   // create the key (id of current element) and set its value as array of elements (result from MyFunc)
   await MyFunc(MyContainer[i]).then((response) => MyMap[MyContainer[i].id] = response);
}

MyMap look like this:

MyMap =
{
   1: [Object, Object, Object, …] // 13 elements
   2: [Object, Object, Object, …] // 7 elements
   3: [Object, Object, Object, …] // 4 elements
   4: [Object]
   5: [Object]
   6: [Object, Object, Object, …] // 5 elements
   7: [Object, Object, Object, …] // 9 elements
}

I would like to iterate my map (keys) but starting from the key that has the smallest value (The smallest array).

Therefore, I would like to:

access MyContainer and pick the element that has id 4, and do stuff (has the smallest array: 1 element)

then access MyContainer and pick the element that has id 5, and do stuff

then 3

then 6

.. etc

and finally access MyContainer and pick the element that has id 1 and do stuff (has the largest array: 13 elements)

Now since myMap is an object, then I can't sort it.

How can I accomplish this?

Body:
Eventually, you won't be able to use an Object because the order of the keys is not guaranteed.

You can:

Use Object.keys(obj) to get the keys of your object as an Array

Use those keys to build an Array of objects of your structure, each item in the array being the key/value pair of your original object.

Then sort that Arrayof objects based on the length of each item.value within it. The item.value in this case is your original object's values which are Arrays

const obj = {
  "1": [1, 2, 3],
  "2": [1],
  "3": [1, 2],
  "4": [1, 2, 3, 4]
};

// Transform object into a nested array
// Each array item contains the value of a key of your original object,
// which itself is an Array
const arr = Object.keys(obj).reduce((arr, key) => {
 arr.push({ key: key, value: obj[key] });

 return arr;
}, [])

// Sort the nested Array based on the length of each item
const sortedArr = arr.sort((a, b) => a.value.length - b.value.length);

console.log(sortedArr);

Same as above but more compact, using chaining

const obj = {
  "1": [1, 2, 3],
  "2": [1],
  "3": [1, 2],
  "4": [1, 2, 3, 4]
};

const sortedArr = Object.keys(obj).reduce((arr, key) => {
  arr.push({ key: key, value: obj[key] });

  return arr;
}, [])
.sort((a, b) => a.value.length - b.value.length)

console.log(sortedArr);


问:
Dynamically define properties to Ember Data model
I'm working on a data model that has a set of predefined attributes that will always be present, and other custom properties defined for it by the user.

A company has many roles. Each company using this system will want to define custom properties for all its roles, in addition to the fixed set of properties that all roles have across different companies.

The idea would be that then roles payload in json-api come with all the attributes, custom or not:

```<code>{
  "id": "123",
  "type": "roles",
  "attributes": {
    "name": "CEO",
    "salary": 100000,
    "favoriteColor": "blue"
  }
}
</code>```

In the above role, name and salary are default attributes, present in all roles regardless company, but favoriteColor is a custom attribute that the particular company owning this role defined as something that they needed to have for all its roles.

I'm wondering if I could get away with something like this using Ember Data, given that I won't be able to define these custom attributes in the role model definition:

```<code>// app/models/role.js
export default DS.Model.extend({
  name: DS.attr('string'),
  salary: DS.attr('number'),
})
</code>```

To make matters even worse, the idea is that these custom attributes will not necessarily be string values, but they can have their type specified too. So a company may want to have favoriteColor of type string, and also birthDate of type date.

答: Use customizable jsona data formatter, it may be very helpful to creating ember data models automatically. Also, it will possible to create correct JSON from your ember data models automatically too :)</p>

Body:
I'm working on a data model that has a set of predefined attributes that will always be present, and other custom properties defined for it by the user.

A company has many roles. Each company using this system will want to define custom properties for all its roles, in addition to the fixed set of properties that all roles have across different companies.

The idea would be that then roles payload in json-api come with all the attributes, custom or not:

{
  "id": "123",
  "type": "roles",
  "attributes": {
    "name": "CEO",
    "salary": 100000,
    "favoriteColor": "blue"
  }
}

In the above role, name and salary are default attributes, present in all roles regardless company, but favoriteColor is a custom attribute that the particular company owning this role defined as something that they needed to have for all its roles.

I'm wondering if I could get away with something like this using Ember Data, given that I won't be able to define these custom attributes in the role model definition:

// app/models/role.js
export default DS.Model.extend({
  name: DS.attr('string'),
  salary: DS.attr('number'),
})

To make matters even worse, the idea is that these custom attributes will not necessarily be string values, but they can have their type specified too. So a company may want to have favoriteColor of type string, and also birthDate of type date.


问:
Could you share a powershell script for setting up a new computer?
I've long used a cmd.exe script to set up new (virtual) machines.  I'm tired of using reg.exe and regedit.exe to set registry values - both are quirky.  I suspect powershell is a better solution for my problem.  Could someone share their powershell script that sets registry keys the way they want them?</p>

答:
Here's a very simple one:</p>

```<code>[UInt16]$limit = Read-Host -Prompt "Enter max number of CodeAnalysis " + `
                                   "warnings to display (default is 200)"
if ($limit -eq 0) { $limit = 200 }

$path = 'HKLM:\SOFTWARE\Microsoft\VisualStudio\8.0\Setup\EDev'
Set-ItemProperty -Path $path -Name CodeAnalysisErrorListViolationLimit `
                             -Value $limit
</code>```

Body:
Here's a very simple one:

[UInt16]$limit = Read-Host -Prompt "Enter max number of CodeAnalysis " + `
                                   "warnings to display (default is 200)"
if ($limit -eq 0) { $limit = 200 }

$path = 'HKLM:\SOFTWARE\Microsoft\VisualStudio\8.0\Setup\EDev'
Set-ItemProperty -Path $path -Name CodeAnalysisErrorListViolationLimit `
                             -Value $limit