问:
CollectionViewCell not appearing in collectionView
I have an issue where a custom UICollectionViewCell will not appear in the UICollectionView. Anyone know what I am missing? I appreciate it in advance.

Below is my UICollectionViewController:

```<code>private let reuseIdentifier = "FeedCell"

class FeedViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    // MARK: Properties
    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView!.register(FeedCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    //MARK: - UICollectionViewFlowLayout

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = view.frame.width

        return CGSize(width: width, height: width)
    }

    //MARK: - UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! FeedCell
        print("CELL")
        cell.backgroundColor = .black

        return cell
    }

//FEED CELL

class FeedCell: UICollectionViewCell {

    //MARK: - Properties

    let profileImageView: CustomeImageView = {
        let imageView = CustomeImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.backgroundColor = .lightGray

        return imageView
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.backgroundColor = .red
        print("feedcell1")
        addSubview(profileImageView)
        profileImageView.anchor(top: topAnchor, bottom: nil, left: leftAnchor, right: nil, paddingTop: 8, paddingBottom: 0, paddingLeft: 8, paddingRight: 0, width: 40, height: 40)
        profileImageView.layer.cornerRadius = 40/2
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

THANKS :)

答:
The issue was I had previously instantiated FeedViewController with

FeedViewController(collectionViewLayout: UICollectionViewLayout())

instead of `FeedViewController(collectionViewLayout:

UICollectionViewFlowLayout()))` since FeedViewController has

UICollectionViewDelegateFlowLayout protocol.

Body:
I have an issue where a custom UICollectionViewCell will not appear in the UICollectionView. Anyone know what I am missing? I appreciate it in advance.

Below is my UICollectionViewController:

private let reuseIdentifier = "FeedCell"

class FeedViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    // MARK: Properties
    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView!.register(FeedCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    //MARK: - UICollectionViewFlowLayout

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = view.frame.width

        return CGSize(width: width, height: width)
    }

    //MARK: - UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! FeedCell
        print("CELL")
        cell.backgroundColor = .black

        return cell
    }

//FEED CELL

class FeedCell: UICollectionViewCell {

    //MARK: - Properties

    let profileImageView: CustomeImageView = {
        let imageView = CustomeImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.backgroundColor = .lightGray

        return imageView
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        self.backgroundColor = .red
        print("feedcell1")
        addSubview(profileImageView)
        profileImageView.anchor(top: topAnchor, bottom: nil, left: leftAnchor, right: nil, paddingTop: 8, paddingBottom: 0, paddingLeft: 8, paddingRight: 0, width: 40, height: 40)
        profileImageView.layer.cornerRadius = 40/2
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

THANKS :)


来源: stackexchange

问:
PowerBI: return a calculation when either VAR is fulfilled
I have a table like this in PowerBI:

I would like to achieve: for year 2018, sum the head count who is older than 19; for each year after 2018, sum the head count for those who is exactly 19.

My code below returns an error ("The expression refers to multiple columns. Multiple columns cannot be converted to a scalar value"):

```<code>nineteen_years =
VAR age_test_2018 =
    FILTER ( 'table', 'table'[age] >= 19 && 'table'[year] = 2018 )
VAR age_test_later =
    FILTER ( 'table', 'table'[age] = 19 && 'table'[year] > 2018 )
RETURN
    CALCULATE ( SUM ( 'Union'[head count] ), age_test_2018 || age_test_later )
</code>```

Anyone can give me a hand on this? Appreciate your help!

答:
The problem here is that age_test_2018 and age_test_later are tables. You can't use OR operator (||) with tables, it expects scalar values (hence the error).

To fix it, you can combine the tables into one, for example:

```<code>nineteen_years =
VAR age_test_2018 =
    FILTER ( 'table', 'table'[age] >= 19 && 'table'[year] = 2018 )
VAR age_test_later =
    FILTER ( 'table', 'table'[age] = 19 && 'table'[year] > 2018 )
VAR all_age_tests =
    UNION ( age_test_2018, age_test_later )
RETURN
    CALCULATE ( SUM ( 'Union'[head count] ), all_age_tests )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a table like this in PowerBI:

I would like to achieve: for year 2018, sum the head count who is older than 19; for each year after 2018, sum the head count for those who is exactly 19.

My code below returns an error ("The expression refers to multiple columns. Multiple columns cannot be converted to a scalar value"):

nineteen_years =
VAR age_test_2018 =
    FILTER ( 'table', 'table'[age] >= 19 && 'table'[year] = 2018 )
VAR age_test_later =
    FILTER ( 'table', 'table'[age] = 19 && 'table'[year] > 2018 )
RETURN
    CALCULATE ( SUM ( 'Union'[head count] ), age_test_2018 || age_test_later )

Anyone can give me a hand on this? Appreciate your help!

Body:
The problem here is that age_test_2018 and age_test_later are tables. You can't use OR operator (||) with tables, it expects scalar values (hence the error).

To fix it, you can combine the tables into one, for example:

nineteen_years =
VAR age_test_2018 =
    FILTER ( 'table', 'table'[age] >= 19 && 'table'[year] = 2018 )
VAR age_test_later =
    FILTER ( 'table', 'table'[age] = 19 && 'table'[year] > 2018 )
VAR all_age_tests =
    UNION ( age_test_2018, age_test_later )
RETURN
    CALCULATE ( SUM ( 'Union'[head count] ), all_age_tests )


问:
Have problem converting GlmNet vec3 to glm vec3 in Cli/C++
I need to convert GlmNet::vec3 to C++ glm::vec3 in my cli/c++ wrapper, but if I add the GlmNet reference in my project, a compiler error occurred said the glm::vec3 is ambiguous. Anyone has clue for this?</p>

答: I found the solution to my problem by creating a alias for the glm namespace.</p>


问:
In simplistic terms, what is Client Business Logic & a Business Entity?
as the question states -  what is Client Business Logic & a Business Entity?</p>

答:
Client Business Logic
The part of an application program that performs the required data processing of the business. It refers to the routines that perform the data entry, update, query and report processing, and more specifically to the processing that takes place behind the scenes rather than the presentation logic required to display the data on the screen (GUI processing). Client applications are made up of a user interface and business logic. Server applications are mostly business logic.

Business Entity
That the accounting records reflect the financial activities of a specific corporate entity, separate and distinct from the people who finance it or work in it. It is one of the 'ground rules' of accounting, see accounting concepts for the others.

ContentLicense: CC BY-SA 3.0


问:
Recognising touch events on Xamarin Android and 'dropping event due to no window focus'
I'm attempting to handle left swipe, right swipe, and double-tapping on a Xamarin Android smartwatch app.

I've used this post as a guide, however I can't seem to call OnSingle, OnLongPress, OnSwipeRight, OnSwipeLeft...

I receive the following output:

```<code>02-17 10:29:36.893 W/ViewRootImpl[MainActivity]( 4450): Dropping event due to no window focus: MotionEvent { action=ACTION_MOVE, actionButton=0, id[0]=0, x[0]=46.893387, y[0]=209.68695, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=2, eventTime=2834886, downTime=2834684, deviceId=0, source=0x1002 }
</code>```

What am I missing or doing incorrectly?

Code:

```<code>[Activity(Label = "@string/app_name", MainLauncher = true)]
public class MainActivity : WearableActivity, GestureDetector.IOnGestureListener
{
    private GestureDetector gestureDetector;
    const int SWIPE_DISTANCE_THRESHOLD = 100;
    const int SWIPE_VELOCITY_THRESHOLD = 100;

    /// <summary>
    /// The on create.
    /// </summary>
    /// <param name="bundle">
    /// The bundle.
    /// </param>
    protected override async void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        this.SetContentView(Resource.Layout.activity_main);
        this.gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener());

        TextView text = this.FindViewById<TextView>(Resource.Id.text);
        this.SetAmbientEnabled();

        while (true)
        {
            //...code...

            await Task.Delay(5000);

            //...code...
        }

    }

    public bool OnDown(MotionEvent e)
    {
        return true;
    }

    public bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
    {
        float distanceX = e2.GetX() - e1.GetX();
        float distanceY = e2.GetY() - e1.GetY();
        if (Math.Abs(distanceX) > Math.Abs(distanceY) && Math.Abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.Abs(velocityX) > SWIPE_VELOCITY_THRESHOLD)
        {
            if (distanceX > 0)
            {
                this.OnSwipeRight();
            }
            else
            {
                this.OnSwipeLeft();
            }

            return true;
        }
        return false;
    }

    void OnSwipeLeft()
    {
        TextView serviceScoreLabel = this.FindViewById<TextView>(Resource.Id.serviceScore);
        serviceScoreLabel.Text = "LLLLL";
    }

    void OnSwipeRight()
    {
        TextView serviceScoreLabel = this.FindViewById<TextView>(Resource.Id.serviceScore);
        serviceScoreLabel.Text = "RRRRR";
    }

    public void OnLongPress(MotionEvent e)
    {
        TextView serviceScoreLabel = this.FindViewById<TextView>(Resource.Id.serviceScore);
        serviceScoreLabel.Text = "long press";
    }

    public bool OnScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
    {
        return false;
    }

    public void OnShowPress(MotionEvent e)
    {
        TextView serviceScoreLabel = this.FindViewById<TextView>(Resource.Id.serviceScore);
        serviceScoreLabel.Text = "show press";
    }

    public bool OnSingleTapUp(MotionEvent e)
    {
        TextView serviceScoreLabel = this.FindViewById<TextView>(Resource.Id.serviceScore);
        serviceScoreLabel.Text = "single tap";
        return false;
    }

    public bool OnTouch(View v, MotionEvent e)
    {
        return gestureDetector.OnTouchEvent(e);
    }
}
</code>```

答:
You should override OnTouchEvcent method,did you miss it ?

```<code>[Activity(Label = "SwipActivity",MainLauncher =true)]
public class SwipActivity : Activity, GestureDetector.IOnGestureListener
{
    AlertDialog _dialog;
    GestureDetector gestureDetector;
    const int SWIPE_DISTANCE_THRESHOLD = 100;
    const int SWIPE_VELOCITY_THRESHOLD = 100;
    protected override void OnCreate(Bundle savedInstanceState)
    {

        base.OnCreate(savedInstanceState);

        SetContentView(Resource.Layout.swip);

        gestureDetector = new GestureDetector(this);
    }

public bool OnDown(MotionEvent e)
    {
        return true;
    }

    public bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
    {
        float distanceX = e2.GetX() - e1.GetX();
        float distanceY = e2.GetY() - e1.GetY();
        if (Math.Abs(distanceX) > Math.Abs(distanceY) && Math.Abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.Abs(velocityX) > SWIPE_VELOCITY_THRESHOLD)
        {
            if (distanceX > 0)
                OnSwipeRight();
            else
                OnSwipeLeft();
            return true;
        }
        return false;
    }

    void OnSwipeLeft()
    {

        Toast.MakeText(this, "Swip left", ToastLength.Short).Show();
    }

    void OnSwipeRight()
    {

        Toast.MakeText(this, "Swip right", ToastLength.Short).Show();
    }

    public void OnLongPress(MotionEvent e)
    {

        Toast.MakeText(this, "OnLongPress", ToastLength.Short).Show();
    }

   public bool OnScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
    {
        return false;
    }

    public void OnShowPress(MotionEvent e)
    {
    }

    public bool OnSingleTapUp(MotionEvent e)
    {
        return false;
    }

    public bool OnTouch(View v, MotionEvent e)
    {
        return gestureDetector.OnTouchEvent(e);
    }

    public override bool OnTouchEvent(MotionEvent e)
    {
        gestureDetector.OnTouchEvent(e);
        return false;
    }

}
</code>```

Body:
I'm attempting to handle left swipe, right swipe, and double-tapping on a Xamarin Android smartwatch app.

I've used this post as a guide, however I can't seem to call OnSingle, OnLongPress, OnSwipeRight, OnSwipeLeft...

I receive the following output:

02-17 10:29:36.893 W/ViewRootImpl[MainActivity]( 4450): Dropping event due to no window focus: MotionEvent { action=ACTION_MOVE, actionButton=0, id[0]=0, x[0]=46.893387, y[0]=209.68695, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=2, eventTime=2834886, downTime=2834684, deviceId=0, source=0x1002 }

What am I missing or doing incorrectly?

Code:

[Activity(Label = "@string/app_name", MainLauncher = true)]
public class MainActivity : WearableActivity, GestureDetector.IOnGestureListener
{
    private GestureDetector gestureDetector;
    const int SWIPE_DISTANCE_THRESHOLD = 100;
    const int SWIPE_VELOCITY_THRESHOLD = 100;

    ///
    /// The on create.
    ///
    /// <param name="bundle">
    /// The bundle.
    /// </param>
    protected override async void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        this.SetContentView(Resource.Layout.activity_main);
        this.gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener());

        TextView text = this.FindViewById<TextView>(Resource.Id.text);
        this.SetAmbientEnabled();

        while (true)
        {
            //...code...

            await Task.Delay(5000);

            //...code...
        }

    }

    public bool OnDown(MotionEvent e)
    {
        return true;
    }

    public bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
    {
        float distanceX = e2.GetX() - e1.GetX();
        float distanceY = e2.GetY() - e1.GetY();
        if (Math.Abs(distanceX) > Math.Abs(distanceY) && Math.Abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.Abs(velocityX) > SWIPE_VELOCITY_THRESHOLD)
        {
            if (distanceX > 0)
            {
                this.OnSwipeRight();
            }
            else
            {
                this.OnSwipeLeft();
            }

            return true;
        }
        return false;
    }

    void OnSwipeLeft()
    {
        TextView serviceScoreLabel = this.FindViewById<TextView>(Resource.Id.serviceScore);
        serviceScoreLabel.Text = "LLLLL";
    }

    void OnSwipeRight()
    {
        TextView serviceScoreLabel = this.FindViewById<TextView>(Resource.Id.serviceScore);
        serviceScoreLabel.Text = "RRRRR";
    }

    public void OnLongPress(MotionEvent e)
    {
        TextView serviceScoreLabel = this.FindViewById<TextView>(Resource.Id.serviceScore);
        serviceScoreLabel.Text = "long press";
    }

    public bool OnScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
    {
        return false;
    }

    public void OnShowPress(MotionEvent e)
    {
        TextView serviceScoreLabel = this.FindViewById<TextView>(Resource.Id.serviceScore);
        serviceScoreLabel.Text = "show press";
    }

    public bool OnSingleTapUp(MotionEvent e)
    {
        TextView serviceScoreLabel = this.FindViewById<TextView>(Resource.Id.serviceScore);
        serviceScoreLabel.Text = "single tap";
        return false;
    }

    public bool OnTouch(View v, MotionEvent e)
    {
        return gestureDetector.OnTouchEvent(e);
    }
}

Body:
You should override OnTouchEvcent method,did you miss it ?

[Activity(Label = "SwipActivity",MainLauncher =true)]
public class SwipActivity : Activity, GestureDetector.IOnGestureListener
{
    AlertDialog _dialog;
    GestureDetector gestureDetector;
    const int SWIPE_DISTANCE_THRESHOLD = 100;
    const int SWIPE_VELOCITY_THRESHOLD = 100;
    protected override void OnCreate(Bundle savedInstanceState)
    {

        base.OnCreate(savedInstanceState);

        SetContentView(Resource.Layout.swip);

        gestureDetector = new GestureDetector(this);
    }

public bool OnDown(MotionEvent e)
    {
        return true;
    }

    public bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
    {
        float distanceX = e2.GetX() - e1.GetX();
        float distanceY = e2.GetY() - e1.GetY();
        if (Math.Abs(distanceX) > Math.Abs(distanceY) && Math.Abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.Abs(velocityX) > SWIPE_VELOCITY_THRESHOLD)
        {
            if (distanceX > 0)
                OnSwipeRight();
            else
                OnSwipeLeft();
            return true;
        }
        return false;
    }

    void OnSwipeLeft()
    {

        Toast.MakeText(this, "Swip left", ToastLength.Short).Show();
    }

    void OnSwipeRight()
    {

        Toast.MakeText(this, "Swip right", ToastLength.Short).Show();
    }

    public void OnLongPress(MotionEvent e)
    {

        Toast.MakeText(this, "OnLongPress", ToastLength.Short).Show();
    }

   public bool OnScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
    {
        return false;
    }

    public void OnShowPress(MotionEvent e)
    {
    }

    public bool OnSingleTapUp(MotionEvent e)
    {
        return false;
    }

    public bool OnTouch(View v, MotionEvent e)
    {
        return gestureDetector.OnTouchEvent(e);
    }

    public override bool OnTouchEvent(MotionEvent e)
    {
        gestureDetector.OnTouchEvent(e);
        return false;
    }

}


问:
Postgres query for daily occupancy?
The table e_log has columns time_event (timestamp) and event_type ('E' or 'X' for entry or exit). There are no people overnight so on a given day the occupancy is the Es minus the Xs where time_event is that day. I'm trying to query for each day's occupancy of 2019, the result is supposed to be

Day                    Occupancy

2019-01-01            14

2109-01-02            22

.

.

.

Any suggestions? The closest is hard-coding each specific day and counting the number of entries but I am unsure of how to get the point in the day where the entries - exits is max. For example this query will always return 0 because everyone leaves by midnight -

```<code>select sum(case when event_type ='E' then 1 else -1 end)
from e_log
where e_log.time_event > cast('2019-01-01 00:00:00' as timestamp) and
      e_log.time_event < cast('2019-01-01 23:59:00' as timestamp);
</code>```

Thanks for any suggestions!

答:
Edited based on the max_occupancy at time of day

```<code>with data
  as(
    select cast(e_log.time_event as date) day_val
           ,e_log.time_event
           ,sum(case when event_type ='E' then 1
                     when event_type='X' then -1
                 end) over(partition by cast(e_log.time_event as date) order by e_log.time_event) as total_occupancy
      from e_log
     )
    ,ranked_by_max_occupancy
     as (
        select row_number() over(partition by day_val order by total_occupancy desc) as rnk
               ,*
          from data
         )
select *
  from ranked_by_max_occupancy
 where rnk=1
</code>```

Updated dbfiddle link
https://dbfiddle.uk/?rdbms=postgres_12&fiddle=3d924f2187373d764325ed555361a9ab

You are on the right track, just need to group it by cast(time_event as date) as follows

```<code>select cast(e_log.time_event as date)
       ,sum(case when event_type ='E' then 1
                 when event_type='X' then -1
             end) as total_occupancy
  from e_log
group by cast(e_log.time_event as date)
</code>```

db fiddle link
https://dbfiddle.uk/?rdbms=postgres_12&fiddle=bb85ea98329829572ed1f234d90640f6

Title: Postgres query for daily occupancy?

Body:
The table e_log has columns time_event (timestamp) and event_type ('E' or 'X' for entry or exit). There are no people overnight so on a given day the occupancy is the Es minus the Xs where time_event is that day. I'm trying to query for each day's occupancy of 2019, the result is supposed to be

Day                    Occupancy

2019-01-01            14

2109-01-02            22

.

.

.

Any suggestions? The closest is hard-coding each specific day and counting the number of entries but I am unsure of how to get the point in the day where the entries - exits is max. For example this query will always return 0 because everyone leaves by midnight -

select sum(case when event_type ='E' then 1 else -1 end)
from e_log
where e_log.time_event > cast('2019-01-01 00:00:00' as timestamp) and
      e_log.time_event < cast('2019-01-01 23:59:00' as timestamp);

Thanks for any suggestions!

Body:
Edited based on the max_occupancy at time of day

with data
  as(
    select cast(e_log.time_event as date) day_val
           ,e_log.time_event
           ,sum(case when event_type ='E' then 1
                     when event_type='X' then -1
                 end) over(partition by cast(e_log.time_event as date) order by e_log.time_event) as total_occupancy
      from e_log
     )
    ,ranked_by_max_occupancy
     as (
        select row_number() over(partition by day_val order by total_occupancy desc) as rnk
               ,*
          from data
         )
select *
  from ranked_by_max_occupancy
 where rnk=1

Updated dbfiddle link
https://dbfiddle.uk/?rdbms=postgres_12&fiddle=3d924f2187373d764325ed555361a9ab

You are on the right track, just need to group it by cast(time_event as date) as follows

select cast(e_log.time_event as date)
       ,sum(case when event_type ='E' then 1
                 when event_type='X' then -1
             end) as total_occupancy
  from e_log
group by cast(e_log.time_event as date)

db fiddle link
https://dbfiddle.uk/?rdbms=postgres_12&fiddle=bb85ea98329829572ed1f234d90640f6


问:
Android Studio cannot update
I am running Mint 14 (Linux) , and have run into a major issue with using Android Studio. When running the update feature, all of the packages come back as "ACCESS DENIED". how can I fix this? How can I grant the permission to download and install.

Additional information:
the studio.sh is running out of my root directory under /usr/bin/android-studio/bin

Thank you for your help, my grade depends on this.

答:
Had same issue when upgrading Android Studio from 3.4.x to 3.5.3 (with Flutter and Dart plugins).

Running Debian Buster.

My path is /opt/android-studio/.

I use terminal to run the studio.sh: /opt/android-studio/bin$ ./studio.sh

I have tried the suggested answers with no luck:

set the ownership of the folder ($ sudo chown -R name:group /opt/android-studio).

kill the java processes (ps -A | grep java), but it actually kills the Android Studio and the downloader.

run Android Studio as sudo, fails with some errors, which is good as it's not supposed to be run as sudo. Setting the ownership should be enough.

What I did:

Close all Android Studio windows / projects, leave only 1 window to update.

Help > 'Check for Updates' > select 'Update and restart'.

It shows download process, click 'Run in background'.

when it's done downloading, click at download process at the bottom which will prompt to implement the update.

click OK or Update now.

Android Studio will close automatically and process / unzip the update.

Done.

Or just download the latest Android Studio zip file and extract again.

Title: Android Studio cannot update


问:
AWS organization - I want all org users to be able to see and share all resources
My AWS IAM use case is quite basic:

We are building a quick MVP of an app and so we are quickly spinning up services that are part of it. Right now it's just 2 of us so it's not like we have a huge org to manage. We need to be able to work together quickly and all I want is a situation that results in the following:

I created the master account. I created an organization and invited my friend to the org via his email (his email, and mine, and the root account email, all use the same domain, not that it matters here)

I log into my account - my ORG account

He logs into his account - his ORG account

He creates functions in lambda.

I go to the lambda dashboard and I can see and manage the functions he created

I create something in Elastic Beanstalk

He goes to the EB dashboard and sees and can manage the resources I created

This doesn't seem like it should be so difficult but about the nearest I can tell is that someone somewhere has to create an IAM role between the two and it has to be given switch role permissions.

Or something.

This tutorial is impossible to follow because it starts using "account" interchangeably and I don't know which it is referring to.

https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts_access.html#orgs_manage_accounts_create-cross-account-role

I've also tried:
https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_cross-account-with-roles.html

And that doesn't seem to be what I want. If I want to switch roles I'll just give my friend the username & password to the admin role, which defeats the whole point. It seems more correct that there's a role we share that allows us to see the resources that the other creates.

Someone who can shed some light on what should be an insanely simple thing, I'd much appreciate it...

I am 100% willing to accept my assumptions are bad. I've never done this before.

答:
My understanding of what you are looking for isn't possible within the AWS console. You can grant permissions across accounts, and you can use APIs to get data across accounts, but the console is only ever going to show you data from one account. Even to use the various "list" type APIs you have to be in the context of a single account. You may be able to access a resource in another account, but you cannot see those resources together.

Bottom line, I don't think you are using organizations in the way it is expected to be used. If you just want multiple developers to have access to the same information you should just have more than one user in a single account, or, better yet, have users from an SSO log into the account via an assumed role. If you use AWS Control Tower to create your accounts it will create an SSO for you and you can add users to the SSO, and grant them access to the various accounts, with varying permissions.


问:
zsh: Evaluate array as command
It is very useful to be able to use array constructs to compose large, multi-line commands.  For example:

```<code>declare -a command=(
   somecommand
       -flagA # comment
       -flagB # comment

   # No need for line continuation characters!
   foo/bar/baz.ext

   # Pipe into grep
   || grep fizz buzz # <=== This does not work!
)
</code>```

And it can then be executed as ${command[@]}.  However, you cannot embed control-flow characters like && or || and have them executed correctly.

Is there any way to do this from a ZSH array?

答:
(EDIT: there seems to be some edits to the original question after I answered it)

Having to guess as you did not provide sample code, but the eval command comes to mind:

```
declare -a command=(
  ls
     -l
   /dev/random
   '||'
   cat -n
     )

echo EXE: ${command[*]}
eval "${command[@]}"
```

Quoting the metacharacters within the definition is required.

Use of double quotes on the eval becomes quite important
to automagically quote the || and other shell
metacharacters.

Title: zsh: Evaluate array as command

Body:
It is very useful to be able to use array constructs to compose large, multi-line commands.  For example:

declare -a command=(
   somecommand
       -flagA # comment
       -flagB # comment

   # No need for line continuation characters!
   foo/bar/baz.ext

   # Pipe into grep
   || grep fizz buzz # <=== This does not work!
)

And it can then be executed as ${command[@]}.  However, you cannot embed control-flow characters like && or || and have them executed correctly.

Is there any way to do this from a ZSH array?

Body:
(EDIT: there seems to be some edits to the original question after I answered it)

Having to guess as you did not provide sample code, but the eval command comes to mind:

declare -a command=(
  ls
     -l
   /dev/random
   '||'
   cat -n
     )

echo EXE: ${command[*]}
eval "${command[@]}"

Quoting the metacharacters within the definition is required.

Use of double quotes on the eval becomes quite important
to automagically quote the || and other shell
metacharacters.


问:
.htaccess rule to remove from URL if present?
We are having a problem with one of our websites, sometimes we see a long url that is not related to any real page on our site. For example the URL should be

```<code>https://example.com/browse
</code>```

But one time in a hundred we get this

```<code>https://example.com/index.php/module/action/param1/static/PFBC/js/jquery/rss/signup/static/js/jquery/templates/themes/love/img/icon/asset/css/legal/user/album/tipocorneo/me/browse
</code>```

Its not always the same URL it changes from time to time but my question is this... Is there a rewrite rule we could use that simply removes the extra part of the URL if its present?

```<code>RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>
    Options +FollowSymLinks

</IfModule>

<IfModule mod_php5.c>
    php_flag allow_url_include Off
    php_flag expose_php Off
</IfModule>

### Security and Spam ###

# Protect the repository directory
<IfModule mod_rewrite.c>
    RewriteRule "(^|/)\.git" - [F,L]
</IfModule>

ServerSignature Off

# Deny access to all CGI, Perl, Python, Bash, SQL, Template, INI configuration, cache, log, temporary and text files
<FilesMatch "\.(cgi|pl|py|sh|bash|sql|tpl|ini|cache|log|tmp|txt)$">
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
</FilesMatch>

# Leave open the humans.txt and robots.txt file
<FilesMatch "humans\.txt|robots\.txt">
    <IfModule mod_authz_core.c>
        Require all granted
    </IfModule>
</FilesMatch>

# Deny access for "composer.json"
<FilesMatch "composer\.json|sample\.htaccess">
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
</FilesMatch>

# Prevent .htaccess/.htpasswd from being downloaded
<Files ~ "^\.ht">
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
</Files>

<Limit GET POST PUT DELETE HEAD>
    <IfModule mod_authz_core.c>
        <RequireAll>
            Require all granted
            Require not env bad_bot
        </RequireAll>
    </IfModule>
</Limit>

ErrorDocument 400 /error/http/index?code=400
ErrorDocument 401 /error/http/index?code=401
ErrorDocument 402 /error/http/index?code=402
ErrorDocument 403 /error/http/index?code=403
ErrorDocument 404 /error
ErrorDocument 405 /error/http/index?code=405
ErrorDocument 500 /error/http/index?code=500
ErrorDocument 501 /error/http/index?code=501
ErrorDocument 502 /error/http/index?code=502
ErrorDocument 504 /error/http/index?code=504
ErrorDocument 505 /error/http/index?code=505

# URL Rewrite
<IfModule mod_rewrite.c>
    <IfModule mod_env.c>
        # Tell PHP that the mod_rewrite module is ENABLED.
        SetEnv HTTP_MOD_REWRITE On
    </IfModule>

    # Uncomment the following only if HTTPS is enabled. HSTS header increases security of your website & SEO
    # <IfModule mod_headers.c>
    # Header set Strict-Transport-Security "max-age=31536000; preload" env=HTTPS
    # </IfModule>

    # Remove www subdomain in the URL
    # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    # RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

    # Force the URL to be https (only if you have an SSL certificate). May not be necessary if HSTS is enabled
    # RewriteCond %{SERVER_PORT} 80
    # RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule ^(.*)$ index.php?$1 [L,QSA]

    # Start Bad Bot Prvention
    RewriteCond %{HTTP_USER_AGENT} ^BackWeb [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Bandit [OR]
    RewriteCond %{HTTP_USER_AGENT} ^BatchFTP [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Buddy [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Collector [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Copier [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Download\Wonder [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Downloader [OR]
    RewriteCond %{HTTP_USER_AGENT} ^LinkWalker [OR]
    RewriteCond %{HTTP_USER_AGENT} ^BlackWidow [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Bot\ mailto:craftbot@yahoo.com [OR]
    RewriteCond %{HTTP_USER_AGENT} ^ChinaClaw [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Custo [OR]
    RewriteCond %{HTTP_USER_AGENT} ^DISCo [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Download\ Demon [OR]
    RewriteCond %{HTTP_USER_AGENT} ^eCatch [OR]
    RewriteCond %{HTTP_USER_AGENT} ^EirGrabber [OR]
    RewriteCond %{HTTP_USER_AGENT} ^EmailSiphon [OR]
    RewriteCond %{HTTP_USER_AGENT} ^EmailWolf [OR]
    RewriteCond %{HTTP_USER_AGENT} ^EmailCollector [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Crescent [OR]
    RewriteCond %{HTTP_USER_AGENT} ^CherryPicker [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Express\ WebPictures [OR]
    RewriteCond %{HTTP_USER_AGENT} ^ExtractorPro [OR]
    RewriteCond %{HTTP_USER_AGENT} ^EyeNetIE [OR]
    RewriteCond %{HTTP_USER_AGENT} ^FlashGet [OR]
    RewriteCond %{HTTP_USER_AGENT} ^GetRight [OR]
    RewriteCond %{HTTP_USER_AGENT} ^GetWeb! [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Go!Zilla [OR]
    RewriteCond %{HTTP_USER_AGENT} ^gotit [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Go-Ahead-Got-It [OR]
    RewriteCond %{HTTP_USER_AGENT} ^GrabNet [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Grafula [OR]
    RewriteCond %{HTTP_USER_AGENT} ^HMView [OR]
    RewriteCond %{HTTP_USER_AGENT} HTTrack [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} ^Image\ Stripper [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Image\ Sucker [OR]
    RewriteCond %{HTTP_USER_AGENT} Indy\ Library [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} ^InterGET [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Internet\ Ninja [OR]
    RewriteCond %{HTTP_USER_AGENT} ^JetCar [OR]
    RewriteCond %{HTTP_USER_AGENT} ^JOC\ Web\ Spider [OR]
    RewriteCond %{HTTP_USER_AGENT} ^larbin [OR]
    RewriteCond %{HTTP_USER_AGENT} ^libghttp [OR]
    RewriteCond %{HTTP_USER_AGENT} ^LeechFTP [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Mass\ Downloader [OR]
    RewriteCond %{HTTP_USER_AGENT} ^MIDown\ tool [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Mister\ PiX [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Navroad [OR]
    RewriteCond %{HTTP_USER_AGENT} ^NearSite [OR]
    RewriteCond %{HTTP_USER_AGENT} ^NetAnts [OR]
    RewriteCond %{HTTP_USER_AGENT} ^NetSpider [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Net\ Vampire [OR]
    RewriteCond %{HTTP_USER_AGENT} ^NetZIP [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Octopus [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Offline\ Explorer [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Offline\ Navigator [OR]
    RewriteCond %{HTTP_USER_AGENT} ^PageGrabber [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Papa\ Foto [OR]
    RewriteCond %{HTTP_USER_AGENT} ^pavuk [OR]
    RewriteCond %{HTTP_USER_AGENT} ^pcBrowser [OR]
    RewriteCond %{HTTP_USER_AGENT} libwww-perl.* [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Pockey [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Pump [OR]
    RewriteCond %{HTTP_USER_AGENT} ^RealDownload [OR]
    RewriteCond %{HTTP_USER_AGENT} ^ReGet [OR]
    RewriteCond %{HTTP_USER_AGENT} ^SiteSnagger [OR]
    RewriteCond %{HTTP_USER_AGENT} ^SmartDownload [OR]
    RewriteCond %{HTTP_USER_AGENT} ^SuperBot [OR]
    RewriteCond %{HTTP_USER_AGENT} ^SuperHTTP [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Surfbot [OR]
    RewriteCond %{HTTP_USER_AGENT} ^tAkeOut [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Teleport\ Pro [OR]
    RewriteCond %{HTTP_USER_AGENT} ^VoidEYE [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Web\ Image\ Collector [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Web\ Sucker [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebAuto [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebCopier [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebFetch [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebGo\ IS [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebLeacher [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebReaper [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebSauger [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Website\ eXtractor [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Website\ Quester [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebStripper [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebWhacker [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebZIP [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Wget [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Widow [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WWWOFFLE [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Zeus
    RewriteRule ^.* - [F,L]
    # End Bad Bot Prevention
</IfModule>

# Modify Headers
<IfModule mod_headers.c>
    # Cache files
    <FilesMatch "\.(jpe?g|png|gif|ico|webp|swf|mp3|mp4|flv|webm|pdf)$">
        Header set Cache-Control "public"
        Header set Expires "Mon, 20 Apr 2060 20:00:00 GMT"
        Header unset Last-Modified
    </FilesMatch>

    # Cache JavaScript & CSS
    <FilesMatch "\.(js|css)$">
        Header set Cache-Control "public"
        Header set Expires "Mon, 20 Apr 2060 20:00:00 GMT"
        Header unset Last-Modified
    </FilesMatch>
</IfModule>

# Compress files
<IfModule mod_deflate.c>
    # Insert filter
    SetOutputFilter DEFLATE
    <IfModule mod_setenvif.c>
        # Netscape 4.x has some problems...
        BrowserMatch ^Mozilla/4 gzip-only-text/html
        # Netscape 4.06-4.08 have some more problems
        BrowserMatch ^Mozilla/4\.0[678] no-gzip
        # MSIE masquerades as Netscape, but it is fine
        BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
        # Don't compress images/archives/music/video/etc
        SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
        SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
        SetEnvIfNoCase Request_URI \.(?:avi|mov|mp3|mp4|rm|flv|swf|mp?g)$ no-gzip dont-vary
    </IfModule>
    <IfModule mod_headers.c>
        # Make sure proxies don't deliver the wrong content
        Header append Vary User-Agent env=!dont-vary
    </IfModule>
</IfModule>

# Enable Expirations
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 1 month"
    # expire images/css/js/swf files after a month in the client's cache
    ExpiresByType text/css "access plus 31 days"
    ExpiresByType text/javascript "access plus 31 days"
    ExpiresByType application/javascript "access plus 31 days"
    ExpiresByType application/x-javascript "access plus 31 days"
    ExpiresByType application/x-gzip "access plus 31 days"
    ExpiresByType image/gif "access plus 31 days"
    ExpiresByType image/jpeg "access plus 31 days"
    ExpiresByType image/png "access plus 31 days"
    ExpiresByType application/x-shockwave-flash "access plus 31 days"
    ExpiresByType image/vnd.microsoft.icon "access plus 31 days"
    ExpiresByType image/x-icon "access plus 1 year"
</IfModule>

# For the videos extensions
#AddType video/ogg .ogg
AddType video/webm .webm
AddType video/mp4 .mp4
AddType application/rss+xml .xml
</code>```

答:
This is the correct answer it was written by donatJ</p>

```<code>    RewriteEngine On

    RewriteRule ^index\.php/module/action/param1/.*/(.*+)$ /$1 [L,R=301]
</code>```

Body:
We are having a problem with one of our websites, sometimes we see a long url that is not related to any real page on our site. For example the URL should be

https://example.com/browse

But one time in a hundred we get this

https://example.com/index.php/module/action/param1/static/PFBC/js/jquery/rss/signup/static/js/jquery/templates/themes/love/img/icon/asset/css/legal/user/album/tipocorneo/me/browse

Its not always the same URL it changes from time to time but my question is this... Is there a rewrite rule we could use that simply removes the extra part of the URL if its present?

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>
    Options +FollowSymLinks

</IfModule>

<IfModule mod_php5.c>
    php_flag allow_url_include Off
    php_flag expose_php Off
</IfModule>

### Security and Spam ###

# Protect the repository directory
<IfModule mod_rewrite.c>
    RewriteRule "(^|/)\.git" - [F,L]
</IfModule>

ServerSignature Off

# Deny access to all CGI, Perl, Python, Bash, SQL, Template, INI configuration, cache, log, temporary and text files
<FilesMatch "\.(cgi|pl|py|sh|bash|sql|tpl|ini|cache|log|tmp|txt)$">
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
</FilesMatch>

# Leave open the humans.txt and robots.txt file
<FilesMatch "humans\.txt|robots\.txt">
    <IfModule mod_authz_core.c>
        Require all granted
    </IfModule>
</FilesMatch>

# Deny access for "composer.json"
<FilesMatch "composer\.json|sample\.htaccess">
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
</FilesMatch>

# Prevent .htaccess/.htpasswd from being downloaded
<Files ~ "^\.ht">
    <IfModule mod_authz_core.c>
        Require all denied
    </IfModule>
</Files>

<Limit GET POST PUT DELETE HEAD>
    <IfModule mod_authz_core.c>
        <RequireAll>
            Require all granted
            Require not env bad_bot
        </RequireAll>
    </IfModule>
</Limit>

ErrorDocument 400 /error/http/index?code=400
ErrorDocument 401 /error/http/index?code=401
ErrorDocument 402 /error/http/index?code=402
ErrorDocument 403 /error/http/index?code=403
ErrorDocument 404 /error
ErrorDocument 405 /error/http/index?code=405
ErrorDocument 500 /error/http/index?code=500
ErrorDocument 501 /error/http/index?code=501
ErrorDocument 502 /error/http/index?code=502
ErrorDocument 504 /error/http/index?code=504
ErrorDocument 505 /error/http/index?code=505

# URL Rewrite
<IfModule mod_rewrite.c>
    <IfModule mod_env.c>
        # Tell PHP that the mod_rewrite module is ENABLED.
        SetEnv HTTP_MOD_REWRITE On
    </IfModule>

    # Uncomment the following only if HTTPS is enabled. HSTS header increases security of your website & SEO
    # <IfModule mod_headers.c>
    # Header set Strict-Transport-Security "max-age=31536000; preload" env=HTTPS
    # </IfModule>

    # Remove www subdomain in the URL
    # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    # RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

    # Force the URL to be https (only if you have an SSL certificate). May not be necessary if HSTS is enabled
    # RewriteCond %{SERVER_PORT} 80
    # RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    RewriteRule ^(.*)$ index.php?$1 [L,QSA]

    # Start Bad Bot Prvention
    RewriteCond %{HTTP_USER_AGENT} ^BackWeb [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Bandit [OR]
    RewriteCond %{HTTP_USER_AGENT} ^BatchFTP [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Buddy [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Collector [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Copier [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Download\Wonder [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Downloader [OR]
    RewriteCond %{HTTP_USER_AGENT} ^LinkWalker [OR]
    RewriteCond %{HTTP_USER_AGENT} ^BlackWidow [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Bot\ mailto:craftbot@yahoo.com [OR]
    RewriteCond %{HTTP_USER_AGENT} ^ChinaClaw [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Custo [OR]
    RewriteCond %{HTTP_USER_AGENT} ^DISCo [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Download\ Demon [OR]
    RewriteCond %{HTTP_USER_AGENT} ^eCatch [OR]
    RewriteCond %{HTTP_USER_AGENT} ^EirGrabber [OR]
    RewriteCond %{HTTP_USER_AGENT} ^EmailSiphon [OR]
    RewriteCond %{HTTP_USER_AGENT} ^EmailWolf [OR]
    RewriteCond %{HTTP_USER_AGENT} ^EmailCollector [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Crescent [OR]
    RewriteCond %{HTTP_USER_AGENT} ^CherryPicker [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Express\ WebPictures [OR]
    RewriteCond %{HTTP_USER_AGENT} ^ExtractorPro [OR]
    RewriteCond %{HTTP_USER_AGENT} ^EyeNetIE [OR]
    RewriteCond %{HTTP_USER_AGENT} ^FlashGet [OR]
    RewriteCond %{HTTP_USER_AGENT} ^GetRight [OR]
    RewriteCond %{HTTP_USER_AGENT} ^GetWeb! [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Go!Zilla [OR]
    RewriteCond %{HTTP_USER_AGENT} ^gotit [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Go-Ahead-Got-It [OR]
    RewriteCond %{HTTP_USER_AGENT} ^GrabNet [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Grafula [OR]
    RewriteCond %{HTTP_USER_AGENT} ^HMView [OR]
    RewriteCond %{HTTP_USER_AGENT} HTTrack [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} ^Image\ Stripper [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Image\ Sucker [OR]
    RewriteCond %{HTTP_USER_AGENT} Indy\ Library [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} ^InterGET [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Internet\ Ninja [OR]
    RewriteCond %{HTTP_USER_AGENT} ^JetCar [OR]
    RewriteCond %{HTTP_USER_AGENT} ^JOC\ Web\ Spider [OR]
    RewriteCond %{HTTP_USER_AGENT} ^larbin [OR]
    RewriteCond %{HTTP_USER_AGENT} ^libghttp [OR]
    RewriteCond %{HTTP_USER_AGENT} ^LeechFTP [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Mass\ Downloader [OR]
    RewriteCond %{HTTP_USER_AGENT} ^MIDown\ tool [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Mister\ PiX [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Navroad [OR]
    RewriteCond %{HTTP_USER_AGENT} ^NearSite [OR]
    RewriteCond %{HTTP_USER_AGENT} ^NetAnts [OR]
    RewriteCond %{HTTP_USER_AGENT} ^NetSpider [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Net\ Vampire [OR]
    RewriteCond %{HTTP_USER_AGENT} ^NetZIP [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Octopus [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Offline\ Explorer [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Offline\ Navigator [OR]
    RewriteCond %{HTTP_USER_AGENT} ^PageGrabber [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Papa\ Foto [OR]
    RewriteCond %{HTTP_USER_AGENT} ^pavuk [OR]
    RewriteCond %{HTTP_USER_AGENT} ^pcBrowser [OR]
    RewriteCond %{HTTP_USER_AGENT} libwww-perl.* [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Pockey [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Pump [OR]
    RewriteCond %{HTTP_USER_AGENT} ^RealDownload [OR]
    RewriteCond %{HTTP_USER_AGENT} ^ReGet [OR]
    RewriteCond %{HTTP_USER_AGENT} ^SiteSnagger [OR]
    RewriteCond %{HTTP_USER_AGENT} ^SmartDownload [OR]
    RewriteCond %{HTTP_USER_AGENT} ^SuperBot [OR]
    RewriteCond %{HTTP_USER_AGENT} ^SuperHTTP [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Surfbot [OR]
    RewriteCond %{HTTP_USER_AGENT} ^tAkeOut [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Teleport\ Pro [OR]
    RewriteCond %{HTTP_USER_AGENT} ^VoidEYE [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Web\ Image\ Collector [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Web\ Sucker [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebAuto [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebCopier [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebFetch [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebGo\ IS [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebLeacher [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebReaper [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebSauger [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Website\ eXtractor [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Website\ Quester [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebStripper [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebWhacker [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WebZIP [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Wget [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Widow [OR]
    RewriteCond %{HTTP_USER_AGENT} ^WWWOFFLE [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]
    RewriteCond %{HTTP_USER_AGENT} ^Zeus
    RewriteRule ^.* - [F,L]
    # End Bad Bot Prevention
</IfModule>

# Modify Headers
<IfModule mod_headers.c>
    # Cache files
    <FilesMatch "\.(jpe?g|png|gif|ico|webp|swf|mp3|mp4|flv|webm|pdf)$">
        Header set Cache-Control "public"
        Header set Expires "Mon, 20 Apr 2060 20:00:00 GMT"
        Header unset Last-Modified
    </FilesMatch>

    # Cache JavaScript & CSS
    <FilesMatch "\.(js|css)$">
        Header set Cache-Control "public"
        Header set Expires "Mon, 20 Apr 2060 20:00:00 GMT"
        Header unset Last-Modified
    </FilesMatch>
</IfModule>

# Compress files
<IfModule mod_deflate.c>
    # Insert filter
    SetOutputFilter DEFLATE
    <IfModule mod_setenvif.c>
        # Netscape 4.x has some problems...
        BrowserMatch ^Mozilla/4 gzip-only-text/html
        # Netscape 4.06-4.08 have some more problems
        BrowserMatch ^Mozilla/4\.0[678] no-gzip
        # MSIE masquerades as Netscape, but it is fine
        BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
        # Don't compress images/archives/music/video/etc
        SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
        SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
        SetEnvIfNoCase Request_URI \.(?:avi|mov|mp3|mp4|rm|flv|swf|mp?g)$ no-gzip dont-vary
    </IfModule>
    <IfModule mod_headers.c>
        # Make sure proxies don't deliver the wrong content
        Header append Vary User-Agent env=!dont-vary
    </IfModule>
</IfModule>

# Enable Expirations
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 1 month"
    # expire images/css/js/swf files after a month in the client's cache
    ExpiresByType text/css "access plus 31 days"
    ExpiresByType text/javascript "access plus 31 days"
    ExpiresByType application/javascript "access plus 31 days"
    ExpiresByType application/x-javascript "access plus 31 days"
    ExpiresByType application/x-gzip "access plus 31 days"
    ExpiresByType image/gif "access plus 31 days"
    ExpiresByType image/jpeg "access plus 31 days"
    ExpiresByType image/png "access plus 31 days"
    ExpiresByType application/x-shockwave-flash "access plus 31 days"
    ExpiresByType image/vnd.microsoft.icon "access plus 31 days"
    ExpiresByType image/x-icon "access plus 1 year"
</IfModule>

# For the videos extensions
#AddType video/ogg .ogg
AddType video/webm .webm
AddType video/mp4 .mp4
AddType application/rss+xml .xml

Body:
This is the correct answer it was written by donatJ

    RewriteEngine On

    RewriteRule ^index\.php/module/action/param1/.*/(.*+)$ /$1 [L,R=301]


问:
Convert progressive JPEG to baseline JPEG
I'm getting a user profile image from Azure AD using below graph api. But when i'm trying to hit the api using POSTMAN tool its giving me a PJPEG image and then i'm not able to get the actual image. So is there any way i can get the jpeg image or convert that pjpeg bytes to base64 and then to image.

Please help.

Graph API.

答:
If you want to update user photo with postman, please refer to the following steps

Register Azure AD application

Configure API permissions

Get access token in Postman

update photo. My test pjpeg file

```<code>PUT PUT https://graph.microsoft.com/v1.0/me/photo/$value
Content-type: image/pjpeg

Body: Binary data for the image
</code>```

Check

```<code>GET https://graph.microsoft.com/v1.0/me/photo/$value
</code>```

Body:
If you want to update user photo with postman, please refer to the following steps

Register Azure AD application

Configure API permissions

Get access token in Postman

update photo. My test pjpeg file

PUT PUT https://graph.microsoft.com/v1.0/me/photo/$value
Content-type: image/pjpeg

Body: Binary data for the image

Check

GET https://graph.microsoft.com/v1.0/me/photo/$value


问:
Laravel Schema onDelete set default
I have two tables with a one-to-one relationship, set by a foreign key constraint. I want to set the onDelete rule to 'set default', meaning that when a row on the foreign table is dropped, the reference value reverts to its default value. Here is my code:

Tours Table:

```<code>Schema::create('tours', function (Blueprint $table) {
    $table->increments('id')->unsigned()->index();
    $table->integer('grade')->unsigned()->default(1);
    $table->timestamps();
});
</code>```

Grades Table:

```<code>Schema::create('grades', function(Blueprint $table){
    $table->increments('id')->unsigned()->index();
    $table->string('name');
    $table->timestamps();
});
</code>```

Set Foreign Key:

```<code>Schema::table('tours', function (Blueprint $table) {
    $table->foreign('grade')->references('id')->on('grades')->onDelete('set default');
});
</code>```

When I run my migrations, it works- no errors. However, looking at the table in HeidiSQL, it hasn't worked properly; the foreign key has been set, but the onDelete property just shows 'NO ACTION'.

Subsequently when I delete a row in the grades table, I get a foreign key constraint error.

What am I doing wrong?

答:
It's been a while but.. it depends on the engine your database uses. If you use InnoDB or NDB, the syntax will be parsed but ignored.

Check this section of the MySQL documentation:

Referential Actions

...

SET DEFAULT: This action is recognized by the MySQL parser, but both InnoDB and NDB reject table definitions containing ON DELETE SET DEFAULT or ON UPDATE SET DEFAULT clauses.

You could use SET NULL instead in case this suit your needs. If not, then you could create an observer that'd perform this operation for you.

Title: Laravel Schema onDelete set default

Body:
I have two tables with a one-to-one relationship, set by a foreign key constraint. I want to set the onDelete rule to 'set default', meaning that when a row on the foreign table is dropped, the reference value reverts to its default value. Here is my code:

Tours Table:

Schema::create('tours', function (Blueprint $table) {
    $table->increments('id')->unsigned()->index();
    $table->integer('grade')->unsigned()->default(1);
    $table->timestamps();
});

Grades Table:

Schema::create('grades', function(Blueprint $table){
    $table->increments('id')->unsigned()->index();
    $table->string('name');
    $table->timestamps();
});

Set Foreign Key:

Schema::table('tours', function (Blueprint $table) {
    $table->foreign('grade')->references('id')->on('grades')->onDelete('set default');
});

When I run my migrations, it works- no errors. However, looking at the table in HeidiSQL, it hasn't worked properly; the foreign key has been set, but the onDelete property just shows 'NO ACTION'.

Subsequently when I delete a row in the grades table, I get a foreign key constraint error.

What am I doing wrong?


问:
parse (input) to JSON string
Hello not overly familiar with JavaScript quite new to it actually so i pulled bits from other projects and now struggling to wrap things up.

This is for a small RGB lighting project. The json payload message is transported via MQTT and the initial input is a string value as follows "rrr,ggg,bbb".

what i have come up with so far is as follows

```<code>(function(i) {

  var rgb = i.split(",");
  var color = {"r":rgb[0],"g":rgb[1],"b":rgb[2]}
  return JSON.stringify({color});

})(input)
</code>```

Desired result needs to be {"color":{"r":232,"g":200,"b":55}}

the JS gets stored as a .js file and referenced when transformation is needed

any help would be much appreciated.

答:
It appears you are creating your inner object correctly, but the value you are stringifying is just the inner object wrapped in braces, you need to change your stringify line to:

```<code> return JSON.stringify({"color": color});
</code>```

The way you currently have it written, would come out as

```<code>{{"r":232,"g":200,"b":55}}

</code>```

Title: parse (input) to JSON string

Body:
Hello not overly familiar with JavaScript quite new to it actually so i pulled bits from other projects and now struggling to wrap things up.

This is for a small RGB lighting project. The json payload message is transported via MQTT and the initial input is a string value as follows "rrr,ggg,bbb".

what i have come up with so far is as follows

(function(i) {

  var rgb = i.split(",");
  var color = {"r":rgb[0],"g":rgb[1],"b":rgb[2]}
  return JSON.stringify({color});

})(input)

Desired result needs to be {"color":{"r":232,"g":200,"b":55}}

the JS gets stored as a .js file and referenced when transformation is needed

any help would be much appreciated.

Body:
It appears you are creating your inner object correctly, but the value you are stringifying is just the inner object wrapped in braces, you need to change your stringify line to:

 return JSON.stringify({"color": color});

The way you currently have it written, would come out as

{{"r":232,"g":200,"b":55}}


问:
How can I stop datatables columns from being responsive?
I'm using this template from Creative-Tim.com.

Here is a link to the file:  drive.google.com/open?id=1EPLpOmM9bNj2-HH-v9rF6HvSoNtTqJtQ

The file is: BS3/examples/new_table.html.

I'm using datatables table and when the browswer window width is descrease, the column headers become responsive where longest table header names appear on top of the sorting arrow, which causes them to look staggered and crooked as not all of them do this because the header names are of different length. How can I keep them all static? I currently have the table set to responsive = false, and have a scrollX bar.

```<code> var table = $('#datatables').DataTable({
     "scrollX": true,
     orderCellsTop: true,
     fixedHeader: true,
     "pageLength": 10,
     responsive: false,
     sDom: 'lrtip'
 });
</code>```

I just want there to be a decent space between columns and for them to stay that way and use scroll for when the page narrows.

答:
If I understood your question correctly, then adding the following CSS will do the trick for you:

table.dataTable thead .sorting:after,
table.dataTable thead .sorting_asc:after,
table.dataTable thead .sorting_desc:after,
table.dataTable thead .sorting_asc_disabled:after,
table.dataTable thead .sorting_desc_disabled:after {
    position: absolute;
    display: block;
    bottom: 8px;
    right: 8px;
    font-family: 'FontAwesome';
    opacity: 0.8;
}

table.dataTable thead .sorting,
table.dataTable thead .sorting_asc,
table.dataTable thead .sorting_desc,
table.dataTable thead .sorting_asc_disabled,
table.dataTable thead .sorting_desc_disabled  {
    padding-right: 30px !important;
}

table.dataTable thead .sorting.text-right,
table.dataTable thead .sorting_asc.text-right,
table.dataTable thead .sorting_desc.text-right,
table.dataTable thead .sorting_asc_disabled.text-right,
table.dataTable thead .sorting_desc_disabled.text-right  {
    padding-right: 0 !important;
}
```

Result:

Body:
I'm using this template from Creative-Tim.com.

Here is a link to the file:  drive.google.com/open?id=1EPLpOmM9bNj2-HH-v9rF6HvSoNtTqJtQ

The file is: BS3/examples/new_table.html.

I'm using datatables table and when the browswer window width is descrease, the column headers become responsive where longest table header names appear on top of the sorting arrow, which causes them to look staggered and crooked as not all of them do this because the header names are of different length. How can I keep them all static? I currently have the table set to responsive = false, and have a scrollX bar.

 var table = $('#datatables').DataTable({
     "scrollX": true,
     orderCellsTop: true,
     fixedHeader: true,
     "pageLength": 10,
     responsive: false,
     sDom: 'lrtip'
 });

I just want there to be a decent space between columns and for them to stay that way and use scroll for when the page narrows.

Body:
If I understood your question correctly, then adding the following CSS will do the trick for you:

table.dataTable thead .sorting:after,
table.dataTable thead .sorting_asc:after,
table.dataTable thead .sorting_desc:after,
table.dataTable thead .sorting_asc_disabled:after,
table.dataTable thead .sorting_desc_disabled:after {
    position: absolute;
    display: block;
    bottom: 8px;
    right: 8px;
    font-family: 'FontAwesome';
    opacity: 0.8;
}

table.dataTable thead .sorting,
table.dataTable thead .sorting_asc,
table.dataTable thead .sorting_desc,
table.dataTable thead .sorting_asc_disabled,
table.dataTable thead .sorting_desc_disabled  {
    padding-right: 30px !important;
}

table.dataTable thead .sorting.text-right,
table.dataTable thead .sorting_asc.text-right,
table.dataTable thead .sorting_desc.text-right,
table.dataTable thead .sorting_asc_disabled.text-right,
table.dataTable thead .sorting_desc_disabled.text-right  {
    padding-right: 0 !important;
}

Result:


问:
Translation of this Python Line
I am relatively new to Python and having problem translating the following one line:

```<code>diffList = [key for key in set(dict1n.keys() + dict2.keys()) if dict1.get(key) != dict2t.get(key)]
</code>```

Can someone please rewrite it for me - break it down into multiple lines in a "normal" nice format?

I think - and I am not sure - what the line is trying to do is to compare two dictionaries and output the differences to a list.

Thanks.

UPDATE: I had typos in the line - there should only be dict1 and dict2:

```<code>diffList = [key for key in set(dict1.keys() + dict2.keys()) if dict1.get(key) != dict2.get(key
</code>```

答:
In English:

Get all keys and store them into a set -> set(dict1n.keys() + dict2.keys())

Iterate through them -> key for key in set(...)

Get these keys, that have different values in the different maps: if dict1.get(key) != dict2t.get(key)

(only the keys, that are in both sets : because dictX.get(key) will return None, if the key is not in dictX, but the same key will be in the other set then )

These keys are stored into a list: diffList = [ key ... ]

Title: Translation of this Python Line

Body:
I am relatively new to Python and having problem translating the following one line:

diffList = [key for key in set(dict1n.keys() + dict2.keys()) if dict1.get(key) != dict2t.get(key)]

Can someone please rewrite it for me - break it down into multiple lines in a "normal" nice format?

I think - and I am not sure - what the line is trying to do is to compare two dictionaries and output the differences to a list.

Thanks.

UPDATE: I had typos in the line - there should only be dict1 and dict2:

diffList = [key for key in set(dict1.keys() + dict2.keys()) if dict1.get(key) != dict2.get(key


问:
Python - Determine if Item is in a List Using a Function
I'm trying to write a function in Python to determine whether or not an item is in a list. I've been trying variations of this code.

No matter how I try it, it always returns a FALSE Boolean value. Even if I put the print commands inside the functions, it only prints with the results for a false value. I'm pretty sure I'm passing the list to the function properly, but I can't figure out why it only determines FALSE values. Any ideas?

```<code>def newFunction(x, y, z):
   z = 0
   if y in x:
      z = True
   else:
      z = False
   return (z)

newList = [2,4,6,8,10]
r = input ('Enter a number: ')
s = 0
newFunction(newList, r, s)
if s == True:
   print ('The no. IS in the list.')
else:
   print ('The no. IS NOT in the list.')
</code>```

答:
You should save the result of your function and convert the input to an integer for it to work.

```<code>def newFunction(x, y, z):
   z = 0
   if y in x:
      z = True
   else:
      z = False
   return (z)

newList = [2,4,6,8,10]
r = input ('Enter a number: ')
s = 0
found = newFunction(newList, int(r), s)
print(found)
if found == True:
   print ('The no. IS in the list.')
else:
   print ('The no. IS NOT in the list.')
</code>```

You can also improve your current implementation by having a simpler function.

```<code>def newFunction(valueList, userInput):
   return userInput in valueList
</code>```

Body:
I'm trying to write a function in Python to determine whether or not an item is in a list. I've been trying variations of this code.

No matter how I try it, it always returns a FALSE Boolean value. Even if I put the print commands inside the functions, it only prints with the results for a false value. I'm pretty sure I'm passing the list to the function properly, but I can't figure out why it only determines FALSE values. Any ideas?

def newFunction(x, y, z):
   z = 0
   if y in x:
      z = True
   else:
      z = False
   return (z)

newList = [2,4,6,8,10]
r = input ('Enter a number: ')
s = 0
newFunction(newList, r, s)
if s == True:
   print ('The no. IS in the list.')
else:
   print ('The no. IS NOT in the list.')

Body:
You should save the result of your function and convert the input to an integer for it to work.

def newFunction(x, y, z):
   z = 0
   if y in x:
      z = True
   else:
      z = False
   return (z)

newList = [2,4,6,8,10]
r = input ('Enter a number: ')
s = 0
found = newFunction(newList, int(r), s)
print(found)
if found == True:
   print ('The no. IS in the list.')
else:
   print ('The no. IS NOT in the list.')

You can also improve your current implementation by having a simpler function.

def newFunction(valueList, userInput):
   return userInput in valueList


问:
How to send 'Some' with argument in a function
I am trying to send the result of a match to a function Foo, but the result of the match is type Some()

How can I send it as an argument to the Foo function?

```<code>struct Person {
    name: Option<String>,
    lastname: Option<String>,
}

fn Foo(x: Option<String>) {
    println!("{:?}", x);
}

fn main() {
    let name = "Steve".to_string();
    let lastname = "Alvarez".to_string();
    let mut x: Option<Person> = Some(Person {
        name: Some(name),
        lastname: Some(lastname),
    });

    match x {
        Some(Person {
            name: ref a @ Some(_),
            lastname: ref b @ _,
        }) => Foo(a),
        _ => {}
    }
}
</code>```

答:
Step 1

First, your match x { Some(Person{...})... looks wrong. Unwrap it as Some(person) => foo(person.name).

struct Person {
    name: Option<String>,
    lastname: Option<String>,
}

fn foo(x: Option<String>) {
    println!("{:?}", x);
}

fn main() {
    let name = "Steve".to_string();
    let lastname = "Alvarez".to_string();
    let x: Option<Person> = Some(Person {
        name: Some(name),
        lastname: Some(lastname),
    });

    match x {
        Some(person) => foo(person.name),
        _ => {}
    }
}
```

<h1>Step 2: Make it nicer</h1>

<p>Taking an <code>Option</code> as a function argument is not very Rust-like, I believe. (I might be wrong, since I am new to Rust as well.)</p>

<p>Also, the <code>match</code> where the <code>None</code> option is not taken is also an antipattern, I believe. Instead, use a combinator (<code>map</code> or <code>and_then</code>).</p>

<pre class="lang-rust prettyprint-override"><code>struct Person {
    name: Option<String>,
    lastname: Option<String>,
}

fn foo(x: String) {
    println!("{:}", x);
}

fn main() {
    let name = "Steve".to_string();
    let lastname = "Alvarez".to_string();
    let x: Option<Person> = Some(Person {
        name: Some(name),
        lastname: Some(lastname),
    });

    x.and_then(|person| person.name) // person.name is an Option -> thus use `and_then`
        .map(|n| foo(n));
}
</code>```

Live Playground

Body:
I am trying to send the result of a match to a function Foo, but the result of the match is type Some()

How can I send it as an argument to the Foo function?

struct Person {
    name: Option<String>,
    lastname: Option<String>,
}

fn Foo(x: Option<String>) {
    println!("{:?}", x);
}

fn main() {
    let name = "Steve".to_string();
    let lastname = "Alvarez".to_string();
    let mut x: Option<Person> = Some(Person {
        name: Some(name),
        lastname: Some(lastname),
    });

    match x {
        Some(Person {
            name: ref a @ Some(_),
            lastname: ref b @ _,
        }) => Foo(a),
        _ => {}
    }
}

Body:
Step 1

First, your match x { Some(Person{...})... looks wrong. Unwrap it as Some(person) => foo(person.name).

struct Person {
    name: Option<String>,
    lastname: Option<String>,
}

fn foo(x: Option<String>) {
    println!("{:?}", x);
}

fn main() {
    let name = "Steve".to_string();
    let lastname = "Alvarez".to_string();
    let x: Option<Person> = Some(Person {
        name: Some(name),
        lastname: Some(lastname),
    });

    match x {
        Some(person) => foo(person.name),
        _ => {}
    }
}

Step 2: Make it nicer

Taking an Option as a function argument is not very Rust-like, I believe. (I might be wrong, since I am new to Rust as well.)

Also, the match where the None option is not taken is also an antipattern, I believe. Instead, use a combinator (map or and_then).

struct Person {
    name: Option<String>,
    lastname: Option<String>,
}

fn foo(x: String) {
    println!("{:}", x);
}

fn main() {
    let name = "Steve".to_string();
    let lastname = "Alvarez".to_string();
    let x: Option<Person> = Some(Person {
        name: Some(name),
        lastname: Some(lastname),
    });

    x.and_then(|person| person.name) // person.name is an Option -> thus use `and_then`
        .map(|n| foo(n));
}

Live Playground


问:
OnActivityResult dont works in xamarin
I'm trying to write app with bluetooth connection. When I got request about turning on bluetooth, I have to choose yes or no, and when I do it then it should show little message like toast, but it doesn't show. I tried to do toast inside function without if still doesn't work, please help

```<code>        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;

        if (bluetoothAdapter == null)
        {
            Toast.MakeText(Application.Context, "xxx ", ToastLength.Short).Show();
        }

        if (!bluetoothAdapter.IsEnabled)
        {
            Intent wlaczbt = new Intent(BluetoothAdapter.ActionRequestEnable);
            StartActivityForResult(wlaczbt, REQUEST_ENABLE_BT);
            //OnActivityResult(REQUEST_ENABLE_BT, Result.Ok, wlaczbt);
        }
        else
        {
            Toast.MakeText(Application.Context, "xxx ", ToastLength.Short).Show();
        }
</code>```

OnActivity:

```<code>public void OnActivityResult(int requestCode,int resultCode,Intent data)
{
    base.OnActivityResult(requestCode, Result.Ok , data);
    Toast.MakeText(Application.Context, "xx ", ToastLength.Short).Show();
    if (requestCode == REQUEST_ENABLE_BT)
    {
        if(resultCode.Equals(Result.Ok))
        {
            Toast.MakeText(Application.Context, "xx ",ToastLength.Short).Show();
        }
        else
        {
            Toast.MakeText(Application.Context, "xx ", ToastLength.Short).Show();
        }
    }
}
</code>```

答:
I write a demo about it work as normal. Here is running GIF.

Here is my code.

```<code>      [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        Button button1;
        int DISCOVERABLE_DURATION = 300;
        int DISCOVERABLE_BT_REQUEST_CODE = 1001;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
             button1 = FindViewById<Button>(Resource.Id.button1);
            button1.Click += Button1_Click;
        }

        private void Button1_Click(object sender, System.EventArgs e)
        {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ActionRequestDiscoverable);
            discoverableIntent.PutExtra(BluetoothAdapter.ExtraDiscoverableDuration, DISCOVERABLE_DURATION);
            StartActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
        }

        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            Toast.MakeText(Application.Context, "xx ", ToastLength.Short).Show();
            if (requestCode == DISCOVERABLE_BT_REQUEST_CODE)
            {
                if (resultCode.Equals(Result.Ok))
                {
                    Toast.MakeText(Application.Context, "xx ", ToastLength.Short).Show();
                }
                else
                {
                    Toast.MakeText(Application.Context, "xx ", ToastLength.Short).Show();
                }
            }
            //base.OnActivityResult(requestCode, resultCode, data);
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
</code>```

I add two permission in AndroidManifest.xml.

```<code><uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
</code>```

Here is my demo, you can download it.

https://github.com/851265601/XAndroidBlueTooth

This is a helpful article about it, you can refer to it.
https://www.codeproject.com/Articles/814814/Android-Connectivity

Title: OnActivityResult dont works in xamarin

Body:
I'm trying to write app with bluetooth connection. When I got request about turning on bluetooth, I have to choose yes or no, and when I do it then it should show little message like toast, but it doesn't show. I tried to do toast inside function without if still doesn't work, please help

        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;

        if (bluetoothAdapter == null)
        {
            Toast.MakeText(Application.Context, "xxx ", ToastLength.Short).Show();
        }

        if (!bluetoothAdapter.IsEnabled)
        {
            Intent wlaczbt = new Intent(BluetoothAdapter.ActionRequestEnable);
            StartActivityForResult(wlaczbt, REQUEST_ENABLE_BT);
            //OnActivityResult(REQUEST_ENABLE_BT, Result.Ok, wlaczbt);
        }
        else
        {
            Toast.MakeText(Application.Context, "xxx ", ToastLength.Short).Show();
        }

OnActivity:

public void OnActivityResult(int requestCode,int resultCode,Intent data)
{
    base.OnActivityResult(requestCode, Result.Ok , data);
    Toast.MakeText(Application.Context, "xx ", ToastLength.Short).Show();
    if (requestCode == REQUEST_ENABLE_BT)
    {
        if(resultCode.Equals(Result.Ok))
        {
            Toast.MakeText(Application.Context, "xx ",ToastLength.Short).Show();
        }
        else
        {
            Toast.MakeText(Application.Context, "xx ", ToastLength.Short).Show();
        }
    }
}

Body:
I write a demo about it work as normal. Here is running GIF.

Here is my code.

      [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        Button button1;
        int DISCOVERABLE_DURATION = 300;
        int DISCOVERABLE_BT_REQUEST_CODE = 1001;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
             button1 = FindViewById<Button>(Resource.Id.button1);
            button1.Click += Button1_Click;
        }

        private void Button1_Click(object sender, System.EventArgs e)
        {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ActionRequestDiscoverable);
            discoverableIntent.PutExtra(BluetoothAdapter.ExtraDiscoverableDuration, DISCOVERABLE_DURATION);
            StartActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
        }

        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            Toast.MakeText(Application.Context, "xx ", ToastLength.Short).Show();
            if (requestCode == DISCOVERABLE_BT_REQUEST_CODE)
            {
                if (resultCode.Equals(Result.Ok))
                {
                    Toast.MakeText(Application.Context, "xx ", ToastLength.Short).Show();
                }
                else
                {
                    Toast.MakeText(Application.Context, "xx ", ToastLength.Short).Show();
                }
            }
            //base.OnActivityResult(requestCode, resultCode, data);
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

I add two permission in AndroidManifest.xml.

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

Here is my demo, you can download it.

https://github.com/851265601/XAndroidBlueTooth

This is a helpful article about it, you can refer to it.
https://www.codeproject.com/Articles/814814/Android-Connectivity


问:
Lambda function that returns before its background tasks complete
I'm trying to create a Lambda function that will restart Apache on an arbitrary number of EC2s. There should be a 15 second delay in between each restart operation. This Lambda will be triggered via an ELB and an HTTP request. To avoid the request timing out, I'd like the code to return a response as soon as I get the instance IDs that I want to restart Apache on, but so far, it's only doing one. Is this possible?

My code is below

```<code>'use strict'

const AWS = require('aws-sdk')
const ssm = new AWS.SSM()
const ec2 = new AWS.EC2()
const documentName = 'reloadApache'
// Amount of time to wait in between restarting Apache instances
const waitTime = process.env.WAIT_TIME

// Bind prefix to log levels
console.debug = console.log.bind(null, '[DEBUG]')
console.log = console.log.bind(null, '[LOG]')
console.info = console.info.bind(null, '[INFO]')
console.warn = console.warn.bind(null, '[WARN]')
console.error = console.error.bind(null, '[ERROR]')

/*
 * This is intended to communicate with an Amazon ELB. Request / response from
 * https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html
 *
 * It expects the "event" object to have a member, "path", containing the URL path the function
 * was called from. This path is expected to match either "/apachereload/all" or
 * "/apachereload/<IP>", where <IP> is an IPv4 address in dotted quad (e.g. 10.154.1.1) notation
 */
module.exports.apachereload = async event => {
  const [service, ip] = event.path.split('/').slice(1)

  const ok = {
    isBase64Encoded: false,
    statusCode: 200,
    statusDescription: '200 OK',
    headers: {
      'Set-cookie': 'cookies',
      'Content-Type': 'application/json'
    },
    body: ''
  }

  const badRequest = {
    isBase64Encoded: false,
    statusCode: 400,
    statusDescription: '400 Bad Request',
    headers: {
      'Set-cookie': 'cookies',
      'Content-Type': 'text/html; charset=utf-8'
    },
    body: '<html><head><title>Bad Request</title></head>' +
      '<body><p>Your browser sent a request this server could not understand.</p></body></html>'
  }

  const internalServerError = {
    isBase64Encoded: false,
    statusCode: 500,
    statusDescription: '500 Internal Server Error',
    headers: {
      'Set-cookie': 'cookies',
      'Content-Type': 'text/html; charset=utf-8'
    },
    body: '<html><head><title>It\'s not you, it\'s us</title></head>' +
      '<body><p>Well, this is embarrassing. Looks like there\'s a problem on ' +
      'our end. We\'ll get it sorted ASAP.</p></body></html>'
  }

  const notFound = {
    isBase64Encoded: false,
    statusCode: 404,
    statusDescription: '404 Not Found',
    headers: {
      'Set-cookie': 'cookies',
      'Content-Type': 'text/html; charset=utf-8'
    },
    body: '<html><head><title>Not Found</title></head>' +
      '<body><p>No resources were found matching your query</p></body></html>'
  }

  let response
  console.info('Request ' + event.path)
  // Send 400 back on an unexpected service
  if (service !== 'apachereload') {
    console.info('Rejecting request; invalid service "' + service + '"')
    response = badRequest
  } else if (ip !== 'all' && !ip.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)) {
    console.info('Rejecting request; expected IP address or "all", got "' + ip + '"')
    response = badRequest
  }

  console.log('Event: ' + JSON.stringify(event, null, 2) + '\n')
  console.log('IP: ' + ip + '\n')

  const instanceIds = await getMatchingInstances(ip)

  if (instanceIds.length === 0) {
    response = notFound
    return response
  }

  response = ok
  response.body = JSON.stringify({ instanceIds: instanceIds })
  return Promise.resolve(response).then(reloadInstances(instanceIds))
}

/*
 * Reload Apache on the EC2 instance with the given IP.
 *
 * params:
 * * ip - IP address of the EC2 to reload Apache on. Pass "all" to restart
 *        all EC2s marked as Apache boxen (i.e. with tag "apache" having value "true")
 *
 * returns Promise chaining the AWS EC2 "describe-instances" request and the SSM
 *         "send-command" request
 */
const getMatchingInstances = (ip) => {
  const params = { Filters: [] }
  if (ip === 'all') {
    params.Filters.push({ Name: 'tag:okToRestart', Values: ['true'] })
  } else {
    params.Filters.push({ Name: 'private-ip-address', Values: [ip] })
  }
  console.log('describeInstances params: ' + JSON.stringify(params, null, 2) + '\n')

  /*
   * Retrieve a list of EC2 instance IDs matching the parameters above
   */
  return ec2.describeInstances(params).promise()
    // build a list of instance IDs
    .then((awsResponse) => {
      console.log('describeInstances response: ' + JSON.stringify(awsResponse, null, 2) + '\n')

      const instanceIds = []
      awsResponse.Reservations.forEach((reservation) => {
        reservation.Instances.forEach((instance) => {
          const instanceId = instance.InstanceId
          console.log('Found instance ID ' + instanceId + '\n')
          instanceIds.push(instanceId)
        })
      })
      return instanceIds
    })
}

/*
 * Build a promise chain for each EC2 instance Apache is to be restarted on.
 * For each instance in the list, we will wait process.env.WAIT_TIME ms before going
 * on to the next instance.
 */
const reloadInstances = async instanceIds => {
  return instanceIds.reduce(async (promiseChain, nextInstanceId, i) => {
    await promiseChain
    const waitTime = i < (instanceIds.length - 1) ? process.env.WAIT_TIME : 0
    return restartApacheOnInstance(nextInstanceId)
      .delay(waitTime)
  }, Promise.resolve('INIITAL'))
}

/*
 * restart Apache on one or more EC2 instances. Helper method for apacheReload()
 *
 * params:
 * * instanceIds - array of EC2 instance IDs to send the "restart Apache" command to
 *
 * returns Promise containing AWS SSM "send-command" request for the given instance IDs
 *
 */
const restartApacheOnInstance = async instanceId => {
  console.info('Restart Apache on instance(s) ' + instanceId + '\n')
  const params = {
    DocumentName: documentName,
    InstanceIds: [instanceId],
    TimeoutSeconds: process.env.SSM_SEND_COMMAND_TIMEOUT
  }

  return ssm.sendCommand(params).promise().then(result => {
    console.debug('SSM sendCommand result: ' + JSON.stringify(result, null, 2) + '\n')
    return result
  })
}

/*
 * Returns a promise that waits a given amount of time before resolving
 *
 * Args:
 * * time:  Amount of time, in ms, to wait
 * * value: Optional value that the returned promise will resolve with
 */
// https://stackoverflow.com/questions/39538473/using-settimeout-on-promise-chain
function delay (time, value) {
  console.debug('delay args: ' + JSON.stringify({ time: time, value: value }))
  return new Promise(resolve => {
    console.debug('Wait ' + time + ' ms')
    setTimeout(resolve.bind(null, value), time)
  })
}

/*
 * Attach delay() to all Promises
 */
Promise.prototype.delay = function (time) {
  return this.then(function (value) {
    return delay(time, value)
  })
}
</code>```

答:
To achieve that, you have two options (per my knowledge)

1- You need to schedule the task of restarting EC2 to another lambda function. So, the lambda invoked by REST will collect instances' ids and trigger another lambda to restart EC2 (using direct async invoke, SNS, SQS, Step Functions, etc) before responding to the REST caller.

2- (NOT REST) Use a WebSocket API in the API Gateway where you can report the progress to the caller who invoked the lambda by writing to a URL.

Hope that helps.

Body:
I'm trying to create a Lambda function that will restart Apache on an arbitrary number of EC2s. There should be a 15 second delay in between each restart operation. This Lambda will be triggered via an ELB and an HTTP request. To avoid the request timing out, I'd like the code to return a response as soon as I get the instance IDs that I want to restart Apache on, but so far, it's only doing one. Is this possible?

My code is below

'use strict'

const AWS = require('aws-sdk')
const ssm = new AWS.SSM()
const ec2 = new AWS.EC2()
const documentName = 'reloadApache'
// Amount of time to wait in between restarting Apache instances
const waitTime = process.env.WAIT_TIME

// Bind prefix to log levels
console.debug = console.log.bind(null, '[DEBUG]')
console.log = console.log.bind(null, '[LOG]')
console.info = console.info.bind(null, '[INFO]')
console.warn = console.warn.bind(null, '[WARN]')
console.error = console.error.bind(null, '[ERROR]')

/*
 * This is intended to communicate with an Amazon ELB. Request / response from
 * https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html
 *
 * It expects the "event" object to have a member, "path", containing the URL path the function
 * was called from. This path is expected to match either "/apachereload/all" or
 * "/apachereload/<IP>", where <IP> is an IPv4 address in dotted quad (e.g. 10.154.1.1) notation
 */
module.exports.apachereload = async event => {
  const [service, ip] = event.path.split('/').slice(1)

  const ok = {
    isBase64Encoded: false,
    statusCode: 200,
    statusDescription: '200 OK',
    headers: {
      'Set-cookie': 'cookies',
      'Content-Type': 'application/json'
    },
    body: ''
  }

  const badRequest = {
    isBase64Encoded: false,
    statusCode: 400,
    statusDescription: '400 Bad Request',
    headers: {
      'Set-cookie': 'cookies',
      'Content-Type': 'text/html; charset=utf-8'
    },
    body: '<title>Bad Request</title>' +
      '
Your browser sent a request this server could not understand.
'
  }

  const internalServerError = {
    isBase64Encoded: false,
    statusCode: 500,
    statusDescription: '500 Internal Server Error',
    headers: {
      'Set-cookie': 'cookies',
      'Content-Type': 'text/html; charset=utf-8'
    },
    body: '<title>It\'s not you, it\'s us</title>' +
      '
Well, this is embarrassing. Looks like there\'s a problem on ' +
      'our end. We\'ll get it sorted ASAP.
'
  }

  const notFound = {
    isBase64Encoded: false,
    statusCode: 404,
    statusDescription: '404 Not Found',
    headers: {
      'Set-cookie': 'cookies',
      'Content-Type': 'text/html; charset=utf-8'
    },
    body: '<title>Not Found</title>' +
      '
No resources were found matching your query
'
  }

  let response
  console.info('Request ' + event.path)
  // Send 400 back on an unexpected service
  if (service !== 'apachereload') {
    console.info('Rejecting request; invalid service "' + service + '"')
    response = badRequest
  } else if (ip !== 'all' && !ip.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)) {
    console.info('Rejecting request; expected IP address or "all", got "' + ip + '"')
    response = badRequest
  }

  console.log('Event: ' + JSON.stringify(event, null, 2) + '\n')
  console.log('IP: ' + ip + '\n')

  const instanceIds = await getMatchingInstances(ip)

  if (instanceIds.length === 0) {
    response = notFound
    return response
  }

  response = ok
  response.body = JSON.stringify({ instanceIds: instanceIds })
  return Promise.resolve(response).then(reloadInstances(instanceIds))
}

/*
 * Reload Apache on the EC2 instance with the given IP.
 *
 * params:
 * * ip - IP address of the EC2 to reload Apache on. Pass "all" to restart
 *        all EC2s marked as Apache boxen (i.e. with tag "apache" having value "true")
 *
 * returns Promise chaining the AWS EC2 "describe-instances" request and the SSM
 *         "send-command" request
 */
const getMatchingInstances = (ip) => {
  const params = { Filters: [] }
  if (ip === 'all') {
    params.Filters.push({ Name: 'tag:okToRestart', Values: ['true'] })
  } else {
    params.Filters.push({ Name: 'private-ip-address', Values: [ip] })
  }
  console.log('describeInstances params: ' + JSON.stringify(params, null, 2) + '\n')

  /*
   * Retrieve a list of EC2 instance IDs matching the parameters above
   */
  return ec2.describeInstances(params).promise()
    // build a list of instance IDs
    .then((awsResponse) => {
      console.log('describeInstances response: ' + JSON.stringify(awsResponse, null, 2) + '\n')

      const instanceIds = []
      awsResponse.Reservations.forEach((reservation) => {
        reservation.Instances.forEach((instance) => {
          const instanceId = instance.InstanceId
          console.log('Found instance ID ' + instanceId + '\n')
          instanceIds.push(instanceId)
        })
      })
      return instanceIds
    })
}

/*
 * Build a promise chain for each EC2 instance Apache is to be restarted on.
 * For each instance in the list, we will wait process.env.WAIT_TIME ms before going
 * on to the next instance.
 */
const reloadInstances = async instanceIds => {
  return instanceIds.reduce(async (promiseChain, nextInstanceId, i) => {
    await promiseChain
    const waitTime = i < (instanceIds.length - 1) ? process.env.WAIT_TIME : 0
    return restartApacheOnInstance(nextInstanceId)
      .delay(waitTime)
  }, Promise.resolve('INIITAL'))
}

/*
 * restart Apache on one or more EC2 instances. Helper method for apacheReload()
 *
 * params:
 * * instanceIds - array of EC2 instance IDs to send the "restart Apache" command to
 *
 * returns Promise containing AWS SSM "send-command" request for the given instance IDs
 *
 */
const restartApacheOnInstance = async instanceId => {
  console.info('Restart Apache on instance(s) ' + instanceId + '\n')
  const params = {
    DocumentName: documentName,
    InstanceIds: [instanceId],
    TimeoutSeconds: process.env.SSM_SEND_COMMAND_TIMEOUT
  }

  return ssm.sendCommand(params).promise().then(result => {
    console.debug('SSM sendCommand result: ' + JSON.stringify(result, null, 2) + '\n')
    return result
  })
}

/*
 * Returns a promise that waits a given amount of time before resolving
 *
 * Args:
 * * time:  Amount of time, in ms, to wait
 * * value: Optional value that the returned promise will resolve with
 */
// https://stackoverflow.com/questions/39538473/using-settimeout-on-promise-chain
function delay (time, value) {
  console.debug('delay args: ' + JSON.stringify({ time: time, value: value }))
  return new Promise(resolve => {
    console.debug('Wait ' + time + ' ms')
    setTimeout(resolve.bind(null, value), time)
  })
}

/*
 * Attach delay() to all Promises
 */
Promise.prototype.delay = function (time) {
  return this.then(function (value) {
    return delay(time, value)
  })
}


问:
Data rendering in django
Each user has certain vacations that he adds. I want to render his vacations and not anyone else's. What should I do?

The view below shows all vacations, but I only want to show the vacations of a particular user.

def all_vacations(request):
    vacations = Vacation.objects.all()
    return render(request, 'homePage.html', {'vacations': vacations})
```

答:
You have to do something like this:

Your URLs:

path('users', views.users_view, name='users')
path('vacation/<int:pk>/', views.user_vacations, name='user_vacation')
```

<ul>
<li>Create a view:</li>
</ul>

<pre class="lang-py prettyprint-override"><code># You have to create a view to list users
# List your users
def users_view(request):
    users = User.objects.all()
    return render(request, 'your_template.html', {'users': users})
</code>```

Create a template to list users:

{% for user in users %}

{{ user}}

{% empty %}

{% endfor %}
```

<ul>
<li>Lastly, you return what you want:</li>
</ul>

<pre class="lang-py prettyprint-override"><code>def user_vacations(request, id):
    vacations = Vacation.objects.get(author__id=id)
    return render(request, 'homepage.html', {'vacations': vacations})

</code>```

Title: Data rendering in django

Body:
You have to do something like this:

Your URLs:

path('users', views.users_view, name='users')
path('vacation/<int:pk>/', views.user_vacations, name='user_vacation')

Create a view:

# You have to create a view to list users
# List your users
def users_view(request):
    users = User.objects.all()
    return render(request, 'your_template.html', {'users': users})

Create a template to list users:

<!--In your template:-->

{% for user in users %}
<ul>
    <li><a href="{% url 'user_vacation' user.id %}">{{ user}}</a></li>
<ul>
{% empty %}
    <!-- Do something -->
{% endfor %}

Lastly, you return what you want:

def user_vacations(request, id):
    vacations = Vacation.objects.get(author__id=id)
    return render(request, 'homepage.html', {'vacations': vacations})


问:
How to hide Creation Date from WHOIS?
Amazon Route53 hides most of the contact information by default, however that doesn't include the Creation Date property. Is there an option to hide that piece of information as well? I do not want the public to know when I created my website.</p>

答: Unfortunately, you did not mention the top level domain (TLD) you're referring to. In case of e.g. .com (or another gTLD), you can not avoid having the creation date in WHOIS. See Appendix F of the Temporary Specification for gTLD Registration Data, being effective as of 25 May 2018, for more details.</p>

Title: How to hide Creation Date from WHOIS?