问:
all outlets are correct, this class is not key value coding-compliant for the key listTitle
I kept getting this class is not key value coding-compliant for the key listTitle error, but all my outlets are correct.

I tried to reconnect all the outlets and make sure nothing goes wrong, but this error is still here.

```<code>@IBOutlet weak var listTitle: UILabel!
@IBOutlet weak var itemTextField: UITextField!
@IBOutlet weak var likeRate: UILabel!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var counter: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    listTitle.text = addedListTitle

    slider.value = 1
    likeRate.text = "1"
}

@IBAction func addPressed(_ sender: Any) {

    if (itemTextField.text!==""){
        counter.text = "You must enter a name for the item"
    }
    else {

        elementCount += 1
        addedItem[itemTextField.text!] = elementRate

        if elementCount < 2
        {
           counter.text = "You have \(elementCount) element in the list"
        }
        else
        {
            counter.text = "You have \(elementCount) elements in the list"
        }
        itemTextField.text = ""
        slider.value = 1
        likeRate.text = "1"
        elementRate = 1
    }
}
@IBAction func finishPressed(_ sender: Any) {

    if (elementCount == 0){
        counter.text  = "You must enter at least one element"
    }
    else{
        addTitle()
        addItems()

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

@IBAction func cancelPressed(_ sender: Any) {

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

func addTitle() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let newList = NSEntityDescription.insertNewObject(forEntityName: "Lists", into: context)

    newList.setValue(addedListTitle, forKey: "listTitle")

    do
    {
        try context.save()
        print("SAVED")
    }
    catch
    {
    }
}

func addItems() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let newItemList = NSEntityDescription.insertNewObject(forEntityName: "Items", into: context)

    for item in addedItem {
        newItemList.setValue(item.key, forKey: "itemName")
        newItemList.setValue(item.value, forKey: "rate")
        newItemList.setValue(addedListTitle, forKey: "listTitle")
    }

    do
    {
        try context.save()
        print("SAVED")
    }
    catch
    {

    }
}
</code>```

}

```<code>    2019-05-26 03:05:15.230138-0400 Selector[4391:283284] *** Terminating
    app due to uncaught exception 'NSUnknownKeyException', reason:
    '[<NSFetchRequest 0x600001c089a0> valueForUndefinedKey:]: this class
    is not key value coding-compliant for the key listTitle.'
</code>```

答:
You have the problem in loadData method of FirstTableViewController class.
You are trying to get the value from request NSFetchRequest object. You should get the value from the NSManagedObject object result.

Change

```<code>if let listTitle = request.value(forKey: "listTitle") as? String {
</code>```

to

```<code>if let listTitle = result.value(forKey: "listTitle") as? String {
</code>```

Body:
I kept getting this class is not key value coding-compliant for the key listTitle error, but all my outlets are correct.

I tried to reconnect all the outlets and make sure nothing goes wrong, but this error is still here.

@IBOutlet weak var listTitle: UILabel!
@IBOutlet weak var itemTextField: UITextField!
@IBOutlet weak var likeRate: UILabel!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var counter: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    listTitle.text = addedListTitle

    slider.value = 1
    likeRate.text = "1"
}

@IBAction func addPressed(_ sender: Any) {

    if (itemTextField.text!==""){
        counter.text = "You must enter a name for the item"
    }
    else {

        elementCount += 1
        addedItem[itemTextField.text!] = elementRate

        if elementCount < 2
        {
           counter.text = "You have \(elementCount) element in the list"
        }
        else
        {
            counter.text = "You have \(elementCount) elements in the list"
        }
        itemTextField.text = ""
        slider.value = 1
        likeRate.text = "1"
        elementRate = 1
    }
}
@IBAction func finishPressed(_ sender: Any) {

    if (elementCount == 0){
        counter.text  = "You must enter at least one element"
    }
    else{
        addTitle()
        addItems()

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

@IBAction func cancelPressed(_ sender: Any) {

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

func addTitle() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let newList = NSEntityDescription.insertNewObject(forEntityName: "Lists", into: context)

    newList.setValue(addedListTitle, forKey: "listTitle")

    do
    {
        try context.save()
        print("SAVED")
    }
    catch
    {
    }
}

func addItems() {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let newItemList = NSEntityDescription.insertNewObject(forEntityName: "Items", into: context)

    for item in addedItem {
        newItemList.setValue(item.key, forKey: "itemName")
        newItemList.setValue(item.value, forKey: "rate")
        newItemList.setValue(addedListTitle, forKey: "listTitle")
    }

    do
    {
        try context.save()
        print("SAVED")
    }
    catch
    {

    }
}

}

    2019-05-26 03:05:15.230138-0400 Selector[4391:283284] *** Terminating
    app due to uncaught exception 'NSUnknownKeyException', reason:
    '[<NSFetchRequest 0x600001c089a0> valueForUndefinedKey:]: this class
    is not key value coding-compliant for the key listTitle.'

Body:
You have the problem in loadData method of FirstTableViewController class.
You are trying to get the value from request NSFetchRequest object. You should get the value from the NSManagedObject object result.

Change

if let listTitle = request.value(forKey: "listTitle") as? String {

to

if let listTitle = result.value(forKey: "listTitle") as? String {


来源: stackexchange

问:
Get generated SQL for a DbContext.SaveChanges in Entity Framework Core
In Entity Framework Core, is it possible to see the SQL that will be applied when the SaveChanges() method is called on the DbContext?

答:
you can use console logger "EF Core logging automatically integrates with the logging mechanisms of .NET Core "
you can read about here :
https://www.entityframeworktutorial.net/efcore/logging-in-entityframework-core.aspx</p>

ContentLicense: CC BY-SA 4.0


问:
how to query an array of objects in laravel
i have an array of objects in laravel that i want to use where query on them so here is my code below :

```<code>  array:18 [▼
  0 => RoomPricingHistory {#498 ▼
    #fillable: array:19 [▶]
    #connection: "mysql"
    #table: "room_pricing_histories"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: false
    #attributes: array:22 [▶]
    #original: array:22 [▼
      "id" => 326
      "accommodation_room_id" => 1
      "net_price" => null
      "sales_price" => 3660000
      "extra_bed_price" => null
      "half_charge_price" => null
      "half_board_price" => null
      "full_board_price" => null
      "foreign_net_price" => null
      "foreign_sales_price" => null
      "foreign_extra_bed_price" => null
      "foreign_half_charge_price" => null
      "foreign_half_board_price" => null
      "foreign_full_board_price" => null
      "operator_id" => 11
      "commission_percent" => null
      "discount_percent" => 5.0
      "from_date" => "2019-05-25 09:00:00"
      "to_date" => "2019-08-30 09:00:00"
      "is_deleted" => 0
      "created_at" => "2019-05-25 09:00:00"
      "updated_at" => "2019-05-25 09:00:00"
    ]
    #changes: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #guarded: array:1 [▶]
  }
  1 => RoomPricingHistory {#506 ▶}
  2 => RoomPricingHistory {#513 ▶}
  3 => RoomPricingHistory {#520 ▶}
  4 => RoomPricingHistory {#527 ▶}
  5 => RoomPricingHistory {#534 ▶}
  6 => RoomPricingHistory {#541 ▶}
  7 => RoomPricingHistory {#548 ▶}
  8 => RoomPricingHistory {#555 ▶}
  9 => RoomPricingHistory {#562 ▶}
  10 => RoomPricingHistory {#569 ▶}
  11 => RoomPricingHistory {#576 ▶}
  12 => RoomPricingHistory {#583 ▶}
  13 => RoomPricingHistory {#590 ▶}
  14 => RoomPricingHistory {#597 ▶}
  15 => RoomPricingHistory {#604 ▶}
  16 => RoomPricingHistory {#611 ▶}
  17 => RoomPricingHistory {#618 ▶}
]
</code>```

so here now for example i have 17 rooms here 5 with of 1, 5 with id of 2 , and 7 with id of 3 in this result and i want to get the last sales_price for each room so i in the end i would have 3 result with room id of 1 -2 -3 and with thier last price . just to mention i sorted them by date before the result

答:
let's say you have the data in the variable called $collection then you can execute the following code to filter data:

we first group data by id then select the last record.

```<code>$grouped = $collection->groupBy('id')->last();

$grouped->toArray();
</code>```

Body:
i have an array of objects in laravel that i want to use where query on them so here is my code below :

  array:18 [▼
  0 => RoomPricingHistory {#498 ▼
    #fillable: array:19 [▶]
    #connection: "mysql"
    #table: "room_pricing_histories"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: false
    #attributes: array:22 [▶]
    #original: array:22 [▼
      "id" => 326
      "accommodation_room_id" => 1
      "net_price" => null
      "sales_price" => 3660000
      "extra_bed_price" => null
      "half_charge_price" => null
      "half_board_price" => null
      "full_board_price" => null
      "foreign_net_price" => null
      "foreign_sales_price" => null
      "foreign_extra_bed_price" => null
      "foreign_half_charge_price" => null
      "foreign_half_board_price" => null
      "foreign_full_board_price" => null
      "operator_id" => 11
      "commission_percent" => null
      "discount_percent" => 5.0
      "from_date" => "2019-05-25 09:00:00"
      "to_date" => "2019-08-30 09:00:00"
      "is_deleted" => 0
      "created_at" => "2019-05-25 09:00:00"
      "updated_at" => "2019-05-25 09:00:00"
    ]
    #changes: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #guarded: array:1 [▶]
  }
  1 => RoomPricingHistory {#506 ▶}
  2 => RoomPricingHistory {#513 ▶}
  3 => RoomPricingHistory {#520 ▶}
  4 => RoomPricingHistory {#527 ▶}
  5 => RoomPricingHistory {#534 ▶}
  6 => RoomPricingHistory {#541 ▶}
  7 => RoomPricingHistory {#548 ▶}
  8 => RoomPricingHistory {#555 ▶}
  9 => RoomPricingHistory {#562 ▶}
  10 => RoomPricingHistory {#569 ▶}
  11 => RoomPricingHistory {#576 ▶}
  12 => RoomPricingHistory {#583 ▶}
  13 => RoomPricingHistory {#590 ▶}
  14 => RoomPricingHistory {#597 ▶}
  15 => RoomPricingHistory {#604 ▶}
  16 => RoomPricingHistory {#611 ▶}
  17 => RoomPricingHistory {#618 ▶}
]

so here now for example i have 17 rooms here 5 with of 1, 5 with id of 2 , and 7 with id of 3 in this result and i want to get the last sales_price for each room so i in the end i would have 3 result with room id of 1 -2 -3 and with thier last price . just to mention i sorted them by date before the result

Body:
let's say you have the data in the variable called $collection then you can execute the following code to filter data:

we first group data by id then select the last record.

$grouped = $collection->groupBy('id')->last();

$grouped->toArray();


问:
How to use token-based authentication with axios and react
There is 401 error(Invalid or not provided access token), How to pass token correctly with axios, This is my code &
API documentation: https://trefle.io

答:
It all depends on how your API is setup to consume the token. Generally speaking though you can pass in a token through the headers property in axios.</p>

```<code>axios.get("https://trefle.io//api/plants/${id}", {
   headers: {
      Authorization : yourtoken
   }
})
</code>```

Body:
It all depends on how your API is setup to consume the token. Generally speaking though you can pass in a token through the headers property in axios.

axios.get("https://trefle.io//api/plants/${id}", {
   headers: {
      Authorization : yourtoken
   }
})


问:
exact difference between "name" and "value" attribute in input tag
I know that it might be so easy
but I cant understand the exact difference between name and value attributes in an input tag (html).
what do they do?!</p>

答:
actually, the value is the property that defines the input data while the name property defines the input field name that can be used for form handling in backend languages like PHP, ...

the name should be unique (in some cases it can be an array of names like multiple checkboxes use case) while the value can be dynamic and repeatable for all inputs.


问:
WebRTC onicecandidate NEVER fires in chrome
My webrtc web app never fies onicecandidate.
When I look into my local(Webrtc Object) object,  localdescription and remotedescription are setted.
In firefox, it fires onicecandidate but event.candidate is null

I tried to solve this problem for several hours, but I couldn't

Can anybody solve this problem?

How can I make onicecandidate event to be fired?

```<code>  let local = new RTCPeerConnection();
  let remote = new RTCPeerConnection();
  try {
    local.createOffer().then(function(sdp) {
      console.log("Offer Created by Local: " + sdp.sdp);
      local.setLocalDescription(sdp);
      remote.setRemoteDescription(sdp);

      remote.createAnswer().then(function(sdp){
        console.log("Answer Created by Remote: " + sdp.sdp);
        remote.setLocalDescription(sdp);
        local.setRemoteDescription(sdp);
        local.onicecandidate = localicecandidate;
        remote.onicecandidate = remoteicecandidate;

        let channel = local.createDataChannel("channel");
        channel.onopen = function(event) {
          console.log("Channel opened");
        }
        channel.onmessgae = function(event) {
          console.log(event.data);
        }

        remote.ondatachannel = function(event) {
          let channel = event.channel;
          channel.onopen = function(event) {
            channel.send("Hi!");
          }
        }

        function localicecandidate (event) {
          console.log("Local got new Ice Candidate: " + event.candidate);
          remote.addIceCandidate(new RTCIceCandidate(event.candidate));
        }
        function remoteicecandidate (event) {
          console.log("Remote got new Ice Candidate: " + event);
          local.addIceCandidate(new RTCIceCandidate(event.candidate));
        }

      });
    })
  }

  catch (e) {
    console.log("Got Error" + e);
  }
</code>```

答:
You are not calling createDataChannel before calling createOffer so you SDP contains no m=lines. Without m-lines there is nothing for ICE to negotiate.

Move let channel = local.createDataChannel("channel"); before createOffer.

Body:
My webrtc web app never fies onicecandidate.
When I look into my local(Webrtc Object) object,  localdescription and remotedescription are setted.
In firefox, it fires onicecandidate but event.candidate is null

I tried to solve this problem for several hours, but I couldn't

Can anybody solve this problem?

How can I make onicecandidate event to be fired?

  let local = new RTCPeerConnection();
  let remote = new RTCPeerConnection();
  try {
    local.createOffer().then(function(sdp) {
      console.log("Offer Created by Local: " + sdp.sdp);
      local.setLocalDescription(sdp);
      remote.setRemoteDescription(sdp);

      remote.createAnswer().then(function(sdp){
        console.log("Answer Created by Remote: " + sdp.sdp);
        remote.setLocalDescription(sdp);
        local.setRemoteDescription(sdp);
        local.onicecandidate = localicecandidate;
        remote.onicecandidate = remoteicecandidate;

        let channel = local.createDataChannel("channel");
        channel.onopen = function(event) {
          console.log("Channel opened");
        }
        channel.onmessgae = function(event) {
          console.log(event.data);
        }

        remote.ondatachannel = function(event) {
          let channel = event.channel;
          channel.onopen = function(event) {
            channel.send("Hi!");
          }
        }

        function localicecandidate (event) {
          console.log("Local got new Ice Candidate: " + event.candidate);
          remote.addIceCandidate(new RTCIceCandidate(event.candidate));
        }
        function remoteicecandidate (event) {
          console.log("Remote got new Ice Candidate: " + event);
          local.addIceCandidate(new RTCIceCandidate(event.candidate));
        }

      });
    })
  }

  catch (e) {
    console.log("Got Error" + e);
  }


问:
Traversing an array to find the second largest element in linear time
Is there a way in linear time by which we can find which is the second largest element of an array ?
Array elements can be positive, negative or zero.
Elements can be repetitive.
No STLs allowed.
Python can be used.

Solution : Sort the array and take the second element but Sorting not allowed

Modification : By definition second largest element will be the one which is numerically smaller. Like if we have

Arr = {5,5,4,3,1}
Then second largest is 4

Addition
Lets say if i want to generalize the question to kth largest and complexity less than linear like nlogn, what can be the solution.

答:
create a temporary array of size 3,

copy first 3 elements there,

sort the temporary array,

replace the last one in the temporary array with the 4th element from the source array,

sort the temporary array,

replace the last one in the temporary array with the 5th element from the source array,

sort the temporary array,

etc.

Sorting array of size 3 is constant time and you do that once for each element of the source array, hence linear overall time.

ContentLicense: CC BY-SA 3.0


问:
FirebaseRemoteConfig Error "No value of type 'String' exists for parameter key"
I am using Firebase Core and some other Features, but not Remote Config. Multiple times a second the following Output is on Logcat.

Where can I disable the Remote Config functionality or even set those non-existing values?

Dependencies:

```<code>// Project
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.google.gms:google-services:4.2.0'
classpath 'com.google.firebase:firebase-plugins:1.2.0'

classpath 'io.fabric.tools:gradle:1.26.1'

// Module
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-vector-drawable:28.0.0'
implementation 'com.android.support:preference-v7:28.0.0'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'org.jsoup:jsoup:1.11.3'
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
implementation 'com.android.support:cardview-v7:28.0.0'

implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-messaging:17.5.0'
implementation 'com.google.firebase:firebase-perf:16.2.4'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.jsibbold:zoomage:1.2.0'
implementation 'com.android.support:exifinterface:28.0.0'
implementation 'com.squareup.picasso:picasso:2.71828'

implementation 'com.crashlytics.sdk.android:crashlytics:2.9.9'
</code>```

```<code>W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_max_length_minutes'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_max_length_minutes'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_feature_enabled'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_max_length_minutes'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'fpr_vc_trace_sampling_rate'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_feature_enabled'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'fpr_vc_trace_sampling_rate'.
</code>```

It is not causing any problems I think, just annoying that it spams the Console.

答:
This might be related to, or a result of:

```<code>W/zzd: Application name is not set. Call Builder#setApplicationName
</code>```

disabling perf-plugin & firebase-perf removes the annoying log entries:

```<code>// classpath "com.google.firebase:perf-plugin:1.2.1"
// apply plugin: "com.google.firebase.firebase-perf"
// implementation "com.google.firebase:firebase-perf:17.0.0"
</code>```

firebase-config works fine on it's own.

Body:
I am using Firebase Core and some other Features, but not Remote Config. Multiple times a second the following Output is on Logcat.

Where can I disable the Remote Config functionality or even set those non-existing values?

Dependencies:

// Project
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.google.gms:google-services:4.2.0'
classpath 'com.google.firebase:firebase-plugins:1.2.0'

classpath 'io.fabric.tools:gradle:1.26.1'

// Module
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-vector-drawable:28.0.0'
implementation 'com.android.support:preference-v7:28.0.0'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'org.jsoup:jsoup:1.11.3'
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
implementation 'com.android.support:cardview-v7:28.0.0'

implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.google.firebase:firebase-messaging:17.5.0'
implementation 'com.google.firebase:firebase-perf:16.2.4'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.jsibbold:zoomage:1.2.0'
implementation 'com.android.support:exifinterface:28.0.0'
implementation 'com.squareup.picasso:picasso:2.71828'

implementation 'com.crashlytics.sdk.android:crashlytics:2.9.9'

W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_max_length_minutes'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_max_length_minutes'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_feature_enabled'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_max_length_minutes'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'fpr_vc_trace_sampling_rate'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_feature_enabled'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'fpr_vc_trace_sampling_rate'.

It is not causing any problems I think, just annoying that it spams the Console.

Body:
This might be related to, or a result of:

W/zzd: Application name is not set. Call Builder#setApplicationName

disabling perf-plugin & firebase-perf removes the annoying log entries:

// classpath "com.google.firebase:perf-plugin:1.2.1"
// apply plugin: "com.google.firebase.firebase-perf"
// implementation "com.google.firebase:firebase-perf:17.0.0"

firebase-config works fine on it's own.


问:
How to remove left and right padding from the canvas/chart?
At the left and right side of the white container, you can see the graph isn't touching entirely on either side, there's a small amount of padding, and I cannot remove it at all.

I tried setting the layout.padding.left to a negative value, but that had no affect, however positive value does move the chart inward, same applies for top and bottom padding.

The only solution that I came up with was adding another div inside the container, and making the canvas width bigger and then using a left negative margin position it, making the line touch the .container corners. Like this jsfiddle but it's only a temporary solution.

JSFIDDLE

var options = {
  type: 'line',
  data: {
    labels: ['', 'november', 'december', 'january', 'february', 'march', 'may', ''],
    datasets: [{
      data: [80, 100, 100, 115, 119, 105, 100, 90],
      pointRadius: [0, 5, 5, 5, 5, 5, 5 , 0],
      pointHoverRadius: [0, 7, 7, 7, 7, 7, 7, 0],

      borderColor: '#3ca2e0',
      backgroundColor: 'rgba(60, 162, 224, .1)',
      lineTension: 0.6,

      // points
      pointBackgroundColor: '#3ca2e0',
      pointHoverBackgroundColor: '#3ca2e0',

      pointBorderColor: '#ffffff',
      pointHoverBorderColor: '#ffffff',

      pointBorderWidth: 2.5,

      pointHitRadius: 10,
      radius: 5,

      borderWidth: 2.5
    }],
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          display: false,

        },
        gridLines: {
          drawBorder: false,
          display: false,
          drawTicks: false
        }
      }],
      xAxes: [{
        gridLines: {
          drawBorder: false,
          display: false
        },
        ticks:{
          fontColor: '#858585'
        }
      }]
    },
    layout: {
      padding: {
       top: 10,
      }
    }
  },
}

var ctx = document.getElementById('chartJSContainer');
new Chart(ctx, options);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { background-color: #1c2128 }

.container {
  width: 500px;
  background-color: #ffffff;
  margin: 20px auto;
  height: 200px;
}</code>```

     <canvas id="chartJSContainer" width="500" height="200"></canvas>

```

答:
One solution would be to use a second container.

The canvas seems to resize based on its parent width.

      <canvas id="chartJSContainer" width="500" height="200"></canvas>

```

<pre class="lang-css prettyprint-override"><code>* {
  padding: 0;
  margin: 0;
}

body {
  background-color: #1c2128;
}

.container {
  width: 490px;
  overflow: hidden;
  margin: 20px auto;
}

.canvas-container {
  width: 500px;
  background-color: #ffffff;
  height: 200px;
  margin-left: -5px;
}
</code>```

Body:
At the left and right side of the white container, you can see the graph isn't touching entirely on either side, there's a small amount of padding, and I cannot remove it at all.

I tried setting the layout.padding.left to a negative value, but that had no affect, however positive value does move the chart inward, same applies for top and bottom padding.

The only solution that I came up with was adding another div inside the container, and making the canvas width bigger and then using a left negative margin position it, making the line touch the .container corners. Like this jsfiddle but it's only a temporary solution.

JSFIDDLE

var options = {
  type: 'line',
  data: {
    labels: ['', 'november', 'december', 'january', 'february', 'march', 'may', ''],
    datasets: [{
      data: [80, 100, 100, 115, 119, 105, 100, 90],
      pointRadius: [0, 5, 5, 5, 5, 5, 5 , 0],
      pointHoverRadius: [0, 7, 7, 7, 7, 7, 7, 0],

      borderColor: '#3ca2e0',
      backgroundColor: 'rgba(60, 162, 224, .1)',
      lineTension: 0.6,

      // points
      pointBackgroundColor: '#3ca2e0',
      pointHoverBackgroundColor: '#3ca2e0',

      pointBorderColor: '#ffffff',
      pointHoverBorderColor: '#ffffff',

      pointBorderWidth: 2.5,

      pointHitRadius: 10,
      radius: 5,

      borderWidth: 2.5
    }],
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          display: false,

        },
        gridLines: {
          drawBorder: false,
          display: false,
          drawTicks: false
        }
      }],
      xAxes: [{
        gridLines: {
          drawBorder: false,
          display: false
        },
        ticks:{
          fontColor: '#858585'
        }
      }]
    },
    layout: {
      padding: {
       top: 10,
      }
    }
  },
}

var ctx = document.getElementById('chartJSContainer');
new Chart(ctx, options);

body { background-color: #1c2128 }

.container {
  width: 500px;
  background-color: #ffffff;
  margin: 20px auto;
  height: 200px;
}

     <canvas id="chartJSContainer" width="500" height="200"></canvas>

Body:
One solution would be to use a second container.

The canvas seems to resize based on its parent width.

<body>
  <div class="container">
    <div class="canvas-container">
      <canvas id="chartJSContainer" width="500" height="200"></canvas>
    </div>
  </div>
</body>

* {
  padding: 0;
  margin: 0;
}

body {
  background-color: #1c2128;
}

.container {
  width: 490px;
  overflow: hidden;
  margin: 20px auto;
}

.canvas-container {
  width: 500px;
  background-color: #ffffff;
  height: 200px;
  margin-left: -5px;
}


问:
How do I check if a string is composed only of letters and numbers? (PHP)
Title says it all: I am checking to see if a user's username contains anything that isn't a number or letter, such as €{¥]^}+<€, punctuation, spaces or even things like âæłęč. Is this possible in php?</p>

答:
PHP does REGEX

What you want to do is fairly trivial, PHP has a number of regex functions

Testing a String For a Character

If all you want is to know IF a string contains non-alphanumeric characters, then just use preg_match():

```<code>preg_match( '/[^A-Za-z0-9]*/', $userName );
</code>```

This will return 1 if the username contains anything other than alphanumeric (A-Z or a-z or 0to9), it returns 0 if it doesn't contain a non-alphanumeric.

Regex Pattern Elements

Regex PCRE patterns open and close with a delimiter such as a slash/, and that needs to be treated like a string (quoted):'/myPattern/' Some other key features are:

[ brackets contain match sets ]

[a-z]  // means match any lowercase letter
This pattern means check the current character in the $String relative to the pattern in these brackets, in this case match any lowercase letter a to z.

^ Caret (Meta-Character)

[^a-z]  // means no lowercase letters If the caret ^ (aka hat) is the first character inside brackets, it NEGATES the pattern inside brackets so [^A7] means match anything EXCEPT uppercase A and the numeral 7. (Note: when outside brackets, the caret ^ means the start of the string.)

\w\W\d\D\s\S. Meta-Characters (WildCards)

\w  // match all alphanumeric An escaped (i.e. preceded by a backslash \ ) lowercase w means match any "word" character, i.e. alphanumeric and the underscore _, this is shorthand for [A-Za-z0-9_]. The uppercase \W is the NOT word character, equivalent to [^A-Za-z0-9_] or [^\w]

```<code>.   // (dot) match ANY single character except return/newline
\w  // match any word character [A-Za-z0-9_]
\W  // NOT any word character [^A-Za-z0-9_]
\d  // match any digit [0-9]
\D  // NOT any digit [^0-9].
\s  // match any whitespace (tab, space, newline)
\S  // NOT any whitespace
</code>```

.*+?| Meta-Characters (Quantifiers))

These modify the behavior outside of a set []

```<code>*   // match previous character or [set] zero or more times,
    // so .* means match everything (including nothing) until reaching a return/newline.
+   // match previous at least one or more times.
?   // match previous only zero or one time (i.e. optional).
|   // means logical OR eg.: com|net means match either literal "com" or "net"
</code>```

Not shown: capture groups, backreferences, substitution (the real power of regex). See https://www.phpliveregex.com/#tab-preg-match for more including a live pattern-match playground that is based on the PHP functions, and delivers results as arrays.

Back To Your StringCleaning

So for your pattern, to match all non-letters and numbers (including underscores) you need either: '/[^A-Za-z0-9]*/'  or  '/[\W_]*/'

Strip Search

If instead you want to STRIP all the non-alpha characters from a string then use preg_replace( $Regex, $Replacement, $StringToClean )

```<code><?php
    $username = 'Svéñ déGööfinøff';
    echo preg_replace('/[\W_]*/', '', $username);
?>
</code>```

The output is: SvdGfinff If you'd prefer to replace certain accented letters with standard latin ones to keep the names reasonably readable, then I believe you'd need a lookup table (array). There is one ready to use at the PHP site

Body:
PHP does REGEX

What you want to do is fairly trivial, PHP has a number of regex functions

Testing a String For a Character

If all you want is to know IF a string contains non-alphanumeric characters, then just use preg_match():

preg_match( '/[^A-Za-z0-9]*/', $userName );

This will return 1 if the username contains anything other than alphanumeric (A-Z or a-z or 0to9), it returns 0 if it doesn't contain a non-alphanumeric.

Regex Pattern Elements

Regex PCRE patterns open and close with a delimiter such as a slash/, and that needs to be treated like a string (quoted):'/myPattern/' Some other key features are:

[ brackets contain match sets ]

[a-z]  // means match any lowercase letter
This pattern means check the current character in the $String relative to the pattern in these brackets, in this case match any lowercase letter a to z.

^ Caret (Meta-Character)

[^a-z]  // means no lowercase letters If the caret ^ (aka hat) is the first character inside brackets, it NEGATES the pattern inside brackets so [^A7] means match anything EXCEPT uppercase A and the numeral 7. (Note: when outside brackets, the caret ^ means the start of the string.)

\w\W\d\D\s\S. Meta-Characters (WildCards)

\w  // match all alphanumeric An escaped (i.e. preceded by a backslash \ ) lowercase w means match any "word" character, i.e. alphanumeric and the underscore _, this is shorthand for [A-Za-z0-9_]. The uppercase \W is the NOT word character, equivalent to [^A-Za-z0-9_] or [^\w]

.   // (dot) match ANY single character except return/newline
\w  // match any word character [A-Za-z0-9_]
\W  // NOT any word character [^A-Za-z0-9_]
\d  // match any digit [0-9]
\D  // NOT any digit [^0-9].
\s  // match any whitespace (tab, space, newline)
\S  // NOT any whitespace

.*+?| Meta-Characters (Quantifiers))

These modify the behavior outside of a set []

*   // match previous character or [set] zero or more times,
    // so .* means match everything (including nothing) until reaching a return/newline.
+   // match previous at least one or more times.
?   // match previous only zero or one time (i.e. optional).
|   // means logical OR eg.: com|net means match either literal "com" or "net"

Not shown: capture groups, backreferences, substitution (the real power of regex). See https://www.phpliveregex.com/#tab-preg-match for more including a live pattern-match playground that is based on the PHP functions, and delivers results as arrays.

Back To Your StringCleaning

So for your pattern, to match all non-letters and numbers (including underscores) you need either: '/[^A-Za-z0-9]*/'  or  '/[\W_]*/'

Strip Search

If instead you want to STRIP all the non-alpha characters from a string then use preg_replace( $Regex, $Replacement, $StringToClean )

<?php
    $username = 'Svéñ déGööfinøff';
    echo preg_replace('/[\W_]*/', '', $username);
?>

The output is: SvdGfinff If you'd prefer to replace certain accented letters with standard latin ones to keep the names reasonably readable, then I believe you'd need a lookup table (array). There is one ready to use at the PHP site


问:
how how iloc[:,1:] works ? can any one explain [:,1:] params
What is the meaning of below lines., especially confused about how iloc[:,1:] is working ? and also data[:,:1]

```<code>data = np.asarray(train_df_mv_norm.iloc[:,1:])
X, Y = data[:,1:],data[:,:1]
</code>```

Here train_df_mv_norm is a dataframe --

答:
Definition: pandas iloc

.iloc[] is primarily integer position based (from 0 to length-1 of the
  axis), but may also be used with a boolean array.

For example:

```<code>df.iloc[:3] # slice your object, i.e. first three rows of your dataframe
df.iloc[0:3] # same
df.iloc[0, 1] # index both axis. Select the element from the first row, second column.
df.iloc[:, 0:5] # first five columns of data frame with all rows
</code>```

So, your dataframe train_df_mv_norm.iloc[:,1:] will select all rows but your first column will be excluded.

Note that:

df.iloc[:,:1] select all rows and columns from 0 (included) to 1 (excluded).

df.iloc[:,1:] select all rows and columns, but exclude column 1.

Body:
What is the meaning of below lines., especially confused about how iloc[:,1:] is working ? and also data[:,:1]

data = np.asarray(train_df_mv_norm.iloc[:,1:])
X, Y = data[:,1:],data[:,:1]

Here train_df_mv_norm is a dataframe --

Body:
Definition: pandas iloc

.iloc[] is primarily integer position based (from 0 to length-1 of the
  axis), but may also be used with a boolean array.

For example:

df.iloc[:3] # slice your object, i.e. first three rows of your dataframe
df.iloc[0:3] # same
df.iloc[0, 1] # index both axis. Select the element from the first row, second column.
df.iloc[:, 0:5] # first five columns of data frame with all rows

So, your dataframe train_df_mv_norm.iloc[:,1:] will select all rows but your first column will be excluded.

Note that:

df.iloc[:,:1] select all rows and columns from 0 (included) to 1 (excluded).

df.iloc[:,1:] select all rows and columns, but exclude column 1.


问:
How to draw a path with rounded corners
I should draw a CustomView like this shot.

but they are not the same. corner strokes are different.

I use 2 separated Path to draw the top shape:
first one  for yellow background:

```<code>   private val paint = Paint().apply {
        isAntiAlias = false                    // pass true does not make change
        color = Color.YELLOW
        style = Paint.Style.FILL_AND_STROKE    // pass only FILL does not make change
        }
</code>```

and the second is:

```<code>private val strokePaint = Paint().apply {
        isAntiAlias = false                   // pass true does not make change
        color = Color.BLACK
        strokeWidth = 2.toPx().toFloat()
        style = Paint.Style.STROKE
    }
</code>```

and in onDraw() function I draw by them:

```<code>override fun onDraw(canvas: Canvas) {
        drawPath()

        canvas.drawPath(path, paint)
        canvas.drawPath(path, strokePaint)

        // at the end, draw text and default things to avoid overlapping with background
        super.onDraw(canvas)

    }
</code>```

Update:
now I drew this that has 2 sides for its pointer.

and used this path to draw:

```<code> private fun drawPath() {
    path.run {
        moveTo(left + radius, top)

        if (_side == SIDE_TOP) {
            lineTo(pointerX - pointerSize / 2, top)
            lineTo(pointerX, rect.top)
            lineTo(pointerX + pointerSize / 2, top)
        }
        lineTo(right - radius, top)

        arcTo(topRightRect, 270F, 90F, false)
        lineTo(right, bottom - radius)
        arcTo(bottomRightRect, 0F, 90F, false)

        if (_side == SIDE_BOTTOM) {
            lineTo(pointerX + pointerSize / 2, bottom)
            lineTo(pointerX, rect.bottom)
            lineTo(pointerX - pointerSize / 2, bottom)
        }
        lineTo(left + radius, bottom)

        arcTo(bottomLeftRect, 90F, 90F, false)
        lineTo(left, top + radius)
        arcTo(topLeftRect, 180F, 90F, false)
        close()
    }
}
</code>```

答:
Canvas has some pre-defined methods for drawing common shapes like circle and rectangle. In your scenario, you can use drawRoundRect which needs a RectF to draw a rectangle.

Here is an example:

```<code>class RoundedRect @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val roundCorner = 32f

    private val paint = Paint().apply {
        color = Color.YELLOW
        style = Paint.Style.FILL
        isAntiAlias = true
    }

    private val strokePaint = Paint().apply {
        color = Color.BLACK
        strokeWidth = 4f
        style = Paint.Style.STROKE
        isAntiAlias = true
    }

    private var rect = RectF(0f, 0f, 0f, 0f)

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)

        rect = RectF(0f, 0f, w.toFloat(), h.toFloat())
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        canvas.drawRoundRect(rect, roundCorner, roundCorner, paint)
        canvas.drawRoundRect(rect, roundCorner, roundCorner, strokePaint)
    }
}
</code>```

BTW, If you want to draw rounded corners using a path, you must set pathEffect with CornerPathEffect.

Here is an example:

```<code>
class RoundedRectUsingPath @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val roundCorner = 32f

    private val paint = Paint().apply {
        color = Color.YELLOW
        isAntiAlias = true
        pathEffect = CornerPathEffect(roundCorner)
        strokeCap = Paint.Cap.ROUND
    }

    private val strokePaint = Paint().apply {
        color = Color.BLACK
        strokeWidth = 4f
        isAntiAlias = true
        style = Paint.Style.STROKE
        pathEffect = CornerPathEffect(roundCorner)
    }

    private var path = Path()
    private val offset = 50f

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        path = Path().apply {
            moveTo(offset, offset)
            lineTo(w.toFloat() - offset, offset)
            lineTo(w.toFloat() - offset, h.toFloat() - offset)
            lineTo(offset, h.toFloat() - offset)
        }
        path.close()

    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        canvas.drawPath(path, paint)
        canvas.drawPath(path, strokePaint)
    }
}
</code>```

Title: How to draw a path with rounded corners

Body:
I should draw a CustomView like this shot.

but they are not the same. corner strokes are different.

I use 2 separated Path to draw the top shape:
first one  for yellow background:

   private val paint = Paint().apply {
        isAntiAlias = false                    // pass true does not make change
        color = Color.YELLOW
        style = Paint.Style.FILL_AND_STROKE    // pass only FILL does not make change
        }

and the second is:

private val strokePaint = Paint().apply {
        isAntiAlias = false                   // pass true does not make change
        color = Color.BLACK
        strokeWidth = 2.toPx().toFloat()
        style = Paint.Style.STROKE
    }

and in onDraw() function I draw by them:

override fun onDraw(canvas: Canvas) {
        drawPath()

        canvas.drawPath(path, paint)
        canvas.drawPath(path, strokePaint)

        // at the end, draw text and default things to avoid overlapping with background
        super.onDraw(canvas)

    }

Update:
now I drew this that has 2 sides for its pointer.

and used this path to draw:

 private fun drawPath() {
    path.run {
        moveTo(left + radius, top)

        if (_side == SIDE_TOP) {
            lineTo(pointerX - pointerSize / 2, top)
            lineTo(pointerX, rect.top)
            lineTo(pointerX + pointerSize / 2, top)
        }
        lineTo(right - radius, top)

        arcTo(topRightRect, 270F, 90F, false)
        lineTo(right, bottom - radius)
        arcTo(bottomRightRect, 0F, 90F, false)

        if (_side == SIDE_BOTTOM) {
            lineTo(pointerX + pointerSize / 2, bottom)
            lineTo(pointerX, rect.bottom)
            lineTo(pointerX - pointerSize / 2, bottom)
        }
        lineTo(left + radius, bottom)

        arcTo(bottomLeftRect, 90F, 90F, false)
        lineTo(left, top + radius)
        arcTo(topLeftRect, 180F, 90F, false)
        close()
    }
}

Body:
Canvas has some pre-defined methods for drawing common shapes like circle and rectangle. In your scenario, you can use drawRoundRect which needs a RectF to draw a rectangle.

Here is an example:

class RoundedRect @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val roundCorner = 32f

    private val paint = Paint().apply {
        color = Color.YELLOW
        style = Paint.Style.FILL
        isAntiAlias = true
    }

    private val strokePaint = Paint().apply {
        color = Color.BLACK
        strokeWidth = 4f
        style = Paint.Style.STROKE
        isAntiAlias = true
    }

    private var rect = RectF(0f, 0f, 0f, 0f)

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)

        rect = RectF(0f, 0f, w.toFloat(), h.toFloat())
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        canvas.drawRoundRect(rect, roundCorner, roundCorner, paint)
        canvas.drawRoundRect(rect, roundCorner, roundCorner, strokePaint)
    }
}

BTW, If you want to draw rounded corners using a path, you must set pathEffect with CornerPathEffect.

Here is an example:

class RoundedRectUsingPath @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val roundCorner = 32f

    private val paint = Paint().apply {
        color = Color.YELLOW
        isAntiAlias = true
        pathEffect = CornerPathEffect(roundCorner)
        strokeCap = Paint.Cap.ROUND
    }

    private val strokePaint = Paint().apply {
        color = Color.BLACK
        strokeWidth = 4f
        isAntiAlias = true
        style = Paint.Style.STROKE
        pathEffect = CornerPathEffect(roundCorner)
    }

    private var path = Path()
    private val offset = 50f

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        path = Path().apply {
            moveTo(offset, offset)
            lineTo(w.toFloat() - offset, offset)
            lineTo(w.toFloat() - offset, h.toFloat() - offset)
            lineTo(offset, h.toFloat() - offset)
        }
        path.close()

    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        canvas.drawPath(path, paint)
        canvas.drawPath(path, strokePaint)
    }
}


问:
Running footer "element(footer)" in paged media appear only in last page
I am working on a paged css with running footers inside the margin boxes. Everything worked almost as expected until I was asked by the graphic designer to make a part of the footer bold and I could no longer use content:"text" for the footers.

I have decided to use content:element(footer) and I have added the footer at the end of my dynamically created html page, but it is only displayed on the last page. I have searched but everybody seems to have the opposite problem (they want it only on the last page and have it on all) or are not using CSS3 printed media styles.

```<code>    @page {
    size: 170mm 240mm;
    margin:  23.5mm 27.5mm 23mm;

    @bottom-center {
       content: element(footer);
        font: normal 8pt MyLucida;
    }
    }
    footer {position: running(footer);
  font-family: MyLucida;
  font-size: 8pt;}
</code>```

HTML

```<code>    <footer>
    My Journal Issue [<b>000</b>] Month Year
    </footer>
</code>```

I was expecting to find the footer on evey page but blank pages, but it only appear on the last page, in the right position inside the box. Changing "position: running(footer)" to "position: absolute" did not change anything. It seems that the footer is added only once at the end and not repeated at all. I had to repeat the style else it was not applying it. The html is for printing only, and it is generated from db datas. My pdf converter is PrinceXML.
I hope it makes sense!

答:
I figured it out myself: the problem was I had included the footer at the end of the file after all the content. If I just include it at the beginning it is repeated every page as supposed.
I moved the footer at the beginning of the body and now it works!</p>

Body:
I am working on a paged css with running footers inside the margin boxes. Everything worked almost as expected until I was asked by the graphic designer to make a part of the footer bold and I could no longer use content:"text" for the footers.

I have decided to use content:element(footer) and I have added the footer at the end of my dynamically created html page, but it is only displayed on the last page. I have searched but everybody seems to have the opposite problem (they want it only on the last page and have it on all) or are not using CSS3 printed media styles.

    @page {
    size: 170mm 240mm;
    margin:  23.5mm 27.5mm 23mm;

    @bottom-center {
       content: element(footer);
        font: normal 8pt MyLucida;
    }
    }
    footer {position: running(footer);
  font-family: MyLucida;
  font-size: 8pt;}

HTML

    My Journal Issue [000] Month Year

I was expecting to find the footer on evey page but blank pages, but it only appear on the last page, in the right position inside the box. Changing "position: running(footer)" to "position: absolute" did not change anything. It seems that the footer is added only once at the end and not repeated at all. I had to repeat the style else it was not applying it. The html is for printing only, and it is generated from db datas. My pdf converter is PrinceXML.
I hope it makes sense!


问:
How Rest Controller handle multiple request at same time for a single instance application?

If multiple request are hit to a single RestController at the same time in a application, how it is handle for different scenarios (Multiple request to a single endpoints (only GET), or Multiple requests for multiple endpoints(GET, POST, PUT...))

Is multi-threading concept utilized? If yes is it possible to handle the requests in FIFO pattern?

What is the maximum request a RestController can take ?

Does RestController scope affect handling of requests (behavior of request scope with default scope-singleton) ?

Also how it is handle by Application context (example with flow will be helpful)

Considering building Micro-services with Spring Boot 2.

答:
From the point of view of Spring (Application Context) rest controller is a singleton if not specified otherwise.

So the code of controller must be ready to be invoked by multiple threads simultaneously.

When a new request reaches the server, in a tradition thread-per-request model the web server (like tomcat) is responsible to allocate a thread from the predefined pool of threads to the request. Then the request gets processed by controller in the context of this thread.

The actual thread pool implementation can in general vary from server to server, but in general, its something that can be configured (number of threads per loop, queue size to store requests for future processing if the pool is full, etc.)

Now regarding the Scope of RestController. If the controller is stateless (and it should be for many cases, just keep it singleton). If you need the new Instance of controller to be created per request, than change the scope. Obviously each thread will have to use the same (in case of singleton scope) instance of rest controller or spring mvc will create a new instance of controller if you specify another scope.

All the answer above applies to a "traditional" thread-per-request model.

Note that since spring 5 / spring boot 2 spring also supports "Reactive" model with a webflux. It works on top of netty and doesn't utilize a thread-per-request model. Please specify in the question if you're interested in this model rather than a tradition model that I've tried to briefly describe.


问:
Vertically align inline, inline-block, and block elements
I have dynamically rendered elements that I need to align vertically. I only have editing control over the parent.

The elements don't have any white space or line break inbetween them.

I have tried with flex, but the block items contract. I have added a style attribute on the block elements to examplify this:

.parent {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <span>ITEM1</span><span>ITEM2</span><div style="background:pink;">ITEM3</div><div style="background:pink;">ITEM4</div><button>ITEM5</button><button>ITEM6</button>
</div></code>```

答:
As per Temani Afif's comment, the following is a working solution:

.parent {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

/* Setting all common block elements to width: 100% */
.parent > div,
.parent > h1,
.parent > h2,
.parent > h3,
.parent > h4,
.parent > h5,
.parent > h6
.parent > ol,
.parent > ul,
.parent > pre,
.parent > address,
.parent > blockquote,
.parent > dl,
.parent > fieldset,
.parent > form,
.parent > hr,
.parent > noscript,
.parent > table {
  width:100%
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <span>ITEM1</span><span>ITEM2</span><div style="background:pink;">ITEM3</div><div style="background:pink;">ITEM4</div><button>ITEM5</button><button>ITEM6</button>
</div></code>```

Body:
I have dynamically rendered elements that I need to align vertically. I only have editing control over the parent.

The elements don't have any white space or line break inbetween them.

I have tried with flex, but the block items contract. I have added a style attribute on the block elements to examplify this:

.parent {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

  ITEM1ITEM2
ITEM3

ITEM4
<button>ITEM5</button><button>ITEM6</button>

Body:
As per Temani Afif's comment, the following is a working solution:

.parent {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

/* Setting all common block elements to width: 100% */
.parent > div,
.parent > h1,
.parent > h2,
.parent > h3,
.parent > h4,
.parent > h5,
.parent > h6
.parent > ol,
.parent > ul,
.parent > pre,
.parent > address,
.parent > blockquote,
.parent > dl,
.parent > fieldset,
.parent > form,
.parent > hr,
.parent > noscript,
.parent > table {
  width:100%
}

<div class="parent">
  <span>ITEM1</span><span>ITEM2</span><div style="background:pink;">ITEM3</div><div style="background:pink;">ITEM4</div><button>ITEM5</button><button>ITEM6</button>
</div>


问:
Redirect action to mobile view
```<code>public ActionResult Home()
        {
            return View();
        }
</code>```

This is what I have for my current site within the HomeController. How can I detect if the action is called from a mobile device, and if it is, re-direct to MobileHome.aspx instead of Home.aspx.

I don't need to know the details of the device, because I am implementing the view in JQuery Mobile, which should adjust itself correctly depending on the view it's rendered in.

答: You may find the following blog post useful.</p>

Title: Redirect action to mobile view

Body:
public ActionResult Home()
        {
            return View();
        }

This is what I have for my current site within the HomeController. How can I detect if the action is called from a mobile device, and if it is, re-direct to MobileHome.aspx instead of Home.aspx.

I don't need to know the details of the device, because I am implementing the view in JQuery Mobile, which should adjust itself correctly depending on the view it's rendered in.


问:
Can you use variables for interface properties?
Let's say I have the classic example of discriminated union:

```<code>interface Circle {
  type: 'circle';
  radius: number;
}
interface Square {
  type: 'square';
  width: number;
}
type Shape = Circle | Square;
</code>```

And then I throw it in a switch case:

```<code>switch (shape.type) {
  case 'circle':
    ...
  case 'square':
    ...
}
</code>```

Is it possible to use variables to allow me to reference the discriminant in a singular way?

答:
You can use an enum. In typescript, variables are only used as values, whereas strings can act as both variables and types (e.g. 'circle'). See Declaration Merging for more info.

However enums also act as both variables and types, so in the example above, you could create an enum like so:

```<code>enum ShapeType {
  Circle = 'circle',
  Square = 'square',
}
</code>```

And replace the type in the interface accordingly, for example:

```<code>interface Circle {
  type: ShapeType.Circle;
  radius: number;
}
</code>```

and reference the enum in the switch case (e.g. case ShapeType.Circle: )

Body:
Let's say I have the classic example of discriminated union:

interface Circle {
  type: 'circle';
  radius: number;
}
interface Square {
  type: 'square';
  width: number;
}
type Shape = Circle | Square;

And then I throw it in a switch case:

switch (shape.type) {
  case 'circle':
    ...
  case 'square':
    ...
}

Is it possible to use variables to allow me to reference the discriminant in a singular way?

Body:
You can use an enum. In typescript, variables are only used as values, whereas strings can act as both variables and types (e.g. 'circle'). See Declaration Merging for more info.

However enums also act as both variables and types, so in the example above, you could create an enum like so:

enum ShapeType {
  Circle = 'circle',
  Square = 'square',
}

And replace the type in the interface accordingly, for example:

interface Circle {
  type: ShapeType.Circle;
  radius: number;
}

and reference the enum in the switch case (e.g. case ShapeType.Circle: )


问:
Custom font in Storyboard from Pod is not showing in the running app
I have created a CococoaPod framework for common UI to be used inside multiple projects. I have assigned Source Sans Pro to UILabels in the storyboard and Font files are added to the CocoaPod framework inside the resource folder.

When any app using this framework runs in the simulator, instead of  Source Sans Pro font, labels are showing Helvetica font.

If I apply font property explicitly in viewDidLoad to UILabel for which Source Sans Pro was set in Storyboard but Helvetica was showing, Source Sans Pro font is shown.

I want to know why appropriate fonts are not showing up from UIStoryboard file coming from Pod framework.

答:
You can set the font property of  UILabel in storyboard and as well as in code. It depends on how you set your font. If you are trying to set the different font in code than  the one which you already set in Storyboard, It will take the font that you set in Code.

Assume you set the Sans Pro to Label in storyboard and you are trying to set different font Helvetica in viewDidLoad means, it will take the Helvetica only.

It will be good if you consistently follow in any one manner, either in Storyboard or in the Code.
And you can set the attributes of UILabel in it's didSet property observer

```<code>@IBOutlet weak var myLabel: UILabel! {
    didSet {
        myLabel.font = UIFont.systemFont(ofSize: 20) // you can set your custom font as well
        myLabel.textColor = UIColor.white
    }
}
</code>```

Body:
You can set the font property of  UILabel in storyboard and as well as in code. It depends on how you set your font. If you are trying to set the different font in code than  the one which you already set in Storyboard, It will take the font that you set in Code.

Assume you set the Sans Pro to Label in storyboard and you are trying to set different font Helvetica in viewDidLoad means, it will take the Helvetica only.

It will be good if you consistently follow in any one manner, either in Storyboard or in the Code.
And you can set the attributes of UILabel in it's didSet property observer

@IBOutlet weak var myLabel: UILabel! {
    didSet {
        myLabel.font = UIFont.systemFont(ofSize: 20) // you can set your custom font as well
        myLabel.textColor = UIColor.white
    }
}


问:
How to delete digits-only lines from a text file?
Let's say I have a text file which contains both alphanumerical values and only numerical values of length 10 digits line by line, like the one shown below:

```<code>abcdefgh
0123456789
edf6543jewjew
9876543219
</code>```

I want to delete all the lines which contains only those random 10 digit numbers, i.e. expected output for the above example is the following:

```<code>abcdefgh
edf6543jewjew
</code>```

How can one do this in Python 3.x?

答:
```<code>import re
fh=open('Desktop\Python13.txt','r+')
content=fh.readlines()
fh.seek(0)
for line in content:
    if re.match(r'[0-9]{10}',line):
        content.remove(line)
fh.write(''.join(content))
fh.truncate()
fh.close()
</code>```

Body:
Let's say I have a text file which contains both alphanumerical values and only numerical values of length 10 digits line by line, like the one shown below:

abcdefgh
0123456789
edf6543jewjew
9876543219

I want to delete all the lines which contains only those random 10 digit numbers, i.e. expected output for the above example is the following:

abcdefgh
edf6543jewjew

How can one do this in Python 3.x?


问:
How to identify users which are connected to a windows server via remote desktop
At my workplace, we have lab machines that we use to do our testing.

The standard procedure to reserve a machine for testing was to walk around the office to make sure that no one was using the machine.

This is highly inefficient and time consuming.

At first, I set up a web page where people could reserve the lab machine but nobody was keeping the page updated so that turned up to be useless.

I finally found a solution using Microsoft log parser and wanted to share it to the stack overflow community.

It is a batch file that runs on the machine so the user can identify the last users that use the machine and easily IM them to ask if the machine is free.

Is there a better solution to do this?

答:
Use the built-in command qwinsta (Query Win Station) to figure out what sessions (including console) are active or inactive (disconnected) and then act on the given information (creds to krusty.ar btw for linking this already).

If you feel people are abusing the machine in question, refer to rwinsta to nuke their sessions into oblivion...

OwnerDisplayName: Julien Nephtali

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: sqook

OwnerDisplayName: Oskar Duveborn


问:
Prevent users from login to same system using different browsers (IE and FF)
We have a web application where users can login.

Now what we want is that the same user should not be able to login using different browsers.

Basically currently a user using two different browsers (IE and FF) can log in to the same account at the same time.  When you hit the login button, is it possible to invalidate all other logins for that account.

What is the best possible approach to do this?

PS: We are using Struts, Spring and Hibernate in our web application.

Thanks !

答:
Google uses some ip address mechanism to logout the user logged in another computer,instead of logging off in the same browser or tab.

May be we can use geoip database Geolitecity  to save the user's ip + Balusc answer of storing session using user as the key and the ip address for the solution .

Have a column isLoggedIn in database. Set to Y , if it logged, if the same user log's in from the another computer or brower, invalidate the session. Mind to set it to N ,if session expires.

* For  Best  Read the Balusc's answer *

prevent-multiple-login-using-the-same-user-name-and-password  using  HttpSessionBindingListener.


问:
Send datatable using SqlAdapter
I have DataSet method who receive sql string like:

```<code> public DataSet GetDataSet(string sql, string TableName)
        {
            this._Errors = false;
            SqlDataAdapter da = new SqlDataAdapter(sql.ToString(), this.dbconn);
            da.SelectCommand.CommandTimeout = 0;
            DataSet ds = new DataSet();
            try
            {
                da.Fill(ds, TableName);
                return ds;
            }
            catch (SqlException e)
            {
                this.HandleSQLError(e, "GetDataSet", sql);
                return null;
            }
        }
</code>```

This works correctly, but now I want to send DataTable to receive as Table Variable in sql

with SqlCommand is simple like:

```<code>SqlCommand cmd = new SqlCommand(sprocName, this.dbconn);

    cmd.Parameters.Add(new SqlParameter(customerTypeTableName, SqlDbType.Structured));
    cmd.Parameters[customerTypeTableName].Value = customerTypeList;
</code>```

How can I modify to do same with SqlAdapter method? Regards

答:
IMO you should write new function. There is no need to use DataAdapter. An object of type SqlCommand is quite enough as shown in the following snippet.</p>

```<code>    comm.Parameters.AddWithValue("@tvpEmails", dt); // dt is your DataTable
// your UDDT type should exist on your SQL instance under UDDT types
    comm.Parameters[comm.Parameters.Count - 1].TypeName = "your UDDT type";
    comm.Parameters[comm.Parameters.Count - 1].SqlDbType = SqlDbType.Structured;
    comm.ExecuteNonQuery();
</code>```

Title: Send datatable using SqlAdapter

Body:
I have DataSet method who receive sql string like:

 public DataSet GetDataSet(string sql, string TableName)
        {
            this._Errors = false;
            SqlDataAdapter da = new SqlDataAdapter(sql.ToString(), this.dbconn);
            da.SelectCommand.CommandTimeout = 0;
            DataSet ds = new DataSet();
            try
            {
                da.Fill(ds, TableName);
                return ds;
            }
            catch (SqlException e)
            {
                this.HandleSQLError(e, "GetDataSet", sql);
                return null;
            }
        }

This works correctly, but now I want to send DataTable to receive as Table Variable in sql

with SqlCommand is simple like:

SqlCommand cmd = new SqlCommand(sprocName, this.dbconn);

    cmd.Parameters.Add(new SqlParameter(customerTypeTableName, SqlDbType.Structured));
    cmd.Parameters[customerTypeTableName].Value = customerTypeList;

How can I modify to do same with SqlAdapter method? Regards

Body:
IMO you should write new function. There is no need to use DataAdapter. An object of type SqlCommand is quite enough as shown in the following snippet.

    comm.Parameters.AddWithValue("@tvpEmails", dt); // dt is your DataTable
// your UDDT type should exist on your SQL instance under UDDT types
    comm.Parameters[comm.Parameters.Count - 1].TypeName = "your UDDT type";
    comm.Parameters[comm.Parameters.Count - 1].SqlDbType = SqlDbType.Structured;
    comm.ExecuteNonQuery();


问:
Behavior of Arrays in bash scripting and zsh shell (Start Index 0 or 1?)
I need explenation about the following behavior of arrays in shell scripting:

Imagine the following is given:

```<code>arber@host ~> ls
fileA fileB script.sh
</code>```

Now i can do the following commands:

```<code>arber@host ~> ARR=($(ls -d file*))
arber@host ~> echo ${ARR[0]}          # start index 0

arber@host ~> echo ${ARR[1]}          # start index 1
fileA
arber@host ~> echo ${ARR[2]}          # start index 2
fileB
</code>```

But when I do this via script.sh it behaves different (Start Index = 0):

```<code>arber@host ~> cat script.sh
#!/bin/bash
ARR=($(ls -d file*))

# get length of an array
aLen=${#ARR[@]}

# use for loop read all items (START INDEX 0)
for (( i=0; i<${aLen}; i++ ));
do
  echo ${ARR[$i]}
done
</code>```

Here the result:

```<code>arber@host ~> ./script.sh
fileA
fileB
</code>```

I use Ubuntu 18.04 LTS and zsh. Can someone explain this?

答:
TL;DR:

bash array indexing starts at 0 (always)

zsh array indexing starts at 1 (unless option KSH_ARRAYS is set)

To always get consistent behaviour, use:

```<code>${array[@]:offset:length}
</code>```

Explanation

For code which works in both bash and zsh, you need to use the offset:length syntax rather than the [subscript] syntax.

Even for zsh-only code, you'll still need to do this (or use emulate -LR zsh) since zsh's array subscripting basis is determined by the KSH_ARRAYS option.

Eg, to reference the first element in an array:

```<code>${array[@]:0:1}
</code>```

Here, array[@] is all the elements, 0 is the offset (which always is 0-based), and 1 is the number of elements desired.

Body:
I need explenation about the following behavior of arrays in shell scripting:

Imagine the following is given:

arber@host ~> ls
fileA fileB script.sh

Now i can do the following commands:

arber@host ~> ARR=($(ls -d file*))
arber@host ~> echo ${ARR[0]}          # start index 0

arber@host ~> echo ${ARR[1]}          # start index 1
fileA
arber@host ~> echo ${ARR[2]}          # start index 2
fileB

But when I do this via script.sh it behaves different (Start Index = 0):

arber@host ~> cat script.sh
#!/bin/bash
ARR=($(ls -d file*))

# get length of an array
aLen=${#ARR[@]}

# use for loop read all items (START INDEX 0)
for (( i=0; i<${aLen}; i++ ));
do
  echo ${ARR[$i]}
done

Here the result:

arber@host ~> ./script.sh
fileA
fileB

I use Ubuntu 18.04 LTS and zsh. Can someone explain this?

Body:
TL;DR:

bash array indexing starts at 0 (always)

zsh array indexing starts at 1 (unless option KSH_ARRAYS is set)

To always get consistent behaviour, use:

${array[@]:offset:length}

Explanation

For code which works in both bash and zsh, you need to use the offset:length syntax rather than the [subscript] syntax.

Even for zsh-only code, you'll still need to do this (or use emulate -LR zsh) since zsh's array subscripting basis is determined by the KSH_ARRAYS option.

Eg, to reference the first element in an array:

${array[@]:0:1}

Here, array[@] is all the elements, 0 is the offset (which always is 0-based), and 1 is the number of elements desired.


问:
how to query an array of objects in laravel
i have an array of objects in laravel that i want to use where query on them so here is my code below :

```<code>  array:18 [▼
  0 => RoomPricingHistory {#498 ▼
    #fillable: array:19 [▶]
    #connection: "mysql"
    #table: "room_pricing_histories"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: false
    #attributes: array:22 [▶]
    #original: array:22 [▼
      "id" => 326
      "accommodation_room_id" => 1
      "net_price" => null
      "sales_price" => 3660000
      "extra_bed_price" => null
      "half_charge_price" => null
      "half_board_price" => null
      "full_board_price" => null
      "foreign_net_price" => null
      "foreign_sales_price" => null
      "foreign_extra_bed_price" => null
      "foreign_half_charge_price" => null
      "foreign_half_board_price" => null
      "foreign_full_board_price" => null
      "operator_id" => 11
      "commission_percent" => null
      "discount_percent" => 5.0
      "from_date" => "2019-05-25 09:00:00"
      "to_date" => "2019-08-30 09:00:00"
      "is_deleted" => 0
      "created_at" => "2019-05-25 09:00:00"
      "updated_at" => "2019-05-25 09:00:00"
    ]
    #changes: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #guarded: array:1 [▶]
  }
  1 => RoomPricingHistory {#506 ▶}
  2 => RoomPricingHistory {#513 ▶}
  3 => RoomPricingHistory {#520 ▶}
  4 => RoomPricingHistory {#527 ▶}
  5 => RoomPricingHistory {#534 ▶}
  6 => RoomPricingHistory {#541 ▶}
  7 => RoomPricingHistory {#548 ▶}
  8 => RoomPricingHistory {#555 ▶}
  9 => RoomPricingHistory {#562 ▶}
  10 => RoomPricingHistory {#569 ▶}
  11 => RoomPricingHistory {#576 ▶}
  12 => RoomPricingHistory {#583 ▶}
  13 => RoomPricingHistory {#590 ▶}
  14 => RoomPricingHistory {#597 ▶}
  15 => RoomPricingHistory {#604 ▶}
  16 => RoomPricingHistory {#611 ▶}
  17 => RoomPricingHistory {#618 ▶}
]
</code>```

so here now for example i have 17 rooms here 5 with of 1, 5 with id of 2 , and 7 with id of 3 in this result and i want to get the last sales_price for each room so i in the end i would have 3 result with room id of 1 -2 -3 and with thier last price . just to mention i sorted them by date before the result

答:
You can use this code for getting last record:</p>

```<code>    for ($f = 0; $f < count($room_id); $f++) {
        for ($i = 0; $i < count($dates); $i++) {
            $roomprice[$f] = RoomPricingHistory::
            Where('accommodation_room_id', $room_id[$f])
            ->whereDate('from_date', '<=', $dates[$i])
            ->whereDate('to_date', '>=', $dates[$i])
            ->orderBy('created_at', 'desc')->first();
    }
}
</code>```

Body:
i have an array of objects in laravel that i want to use where query on them so here is my code below :

  array:18 [▼
  0 => RoomPricingHistory {#498 ▼
    #fillable: array:19 [▶]
    #connection: "mysql"
    #table: "room_pricing_histories"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: false
    #attributes: array:22 [▶]
    #original: array:22 [▼
      "id" => 326
      "accommodation_room_id" => 1
      "net_price" => null
      "sales_price" => 3660000
      "extra_bed_price" => null
      "half_charge_price" => null
      "half_board_price" => null
      "full_board_price" => null
      "foreign_net_price" => null
      "foreign_sales_price" => null
      "foreign_extra_bed_price" => null
      "foreign_half_charge_price" => null
      "foreign_half_board_price" => null
      "foreign_full_board_price" => null
      "operator_id" => 11
      "commission_percent" => null
      "discount_percent" => 5.0
      "from_date" => "2019-05-25 09:00:00"
      "to_date" => "2019-08-30 09:00:00"
      "is_deleted" => 0
      "created_at" => "2019-05-25 09:00:00"
      "updated_at" => "2019-05-25 09:00:00"
    ]
    #changes: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #guarded: array:1 [▶]
  }
  1 => RoomPricingHistory {#506 ▶}
  2 => RoomPricingHistory {#513 ▶}
  3 => RoomPricingHistory {#520 ▶}
  4 => RoomPricingHistory {#527 ▶}
  5 => RoomPricingHistory {#534 ▶}
  6 => RoomPricingHistory {#541 ▶}
  7 => RoomPricingHistory {#548 ▶}
  8 => RoomPricingHistory {#555 ▶}
  9 => RoomPricingHistory {#562 ▶}
  10 => RoomPricingHistory {#569 ▶}
  11 => RoomPricingHistory {#576 ▶}
  12 => RoomPricingHistory {#583 ▶}
  13 => RoomPricingHistory {#590 ▶}
  14 => RoomPricingHistory {#597 ▶}
  15 => RoomPricingHistory {#604 ▶}
  16 => RoomPricingHistory {#611 ▶}
  17 => RoomPricingHistory {#618 ▶}
]

so here now for example i have 17 rooms here 5 with of 1, 5 with id of 2 , and 7 with id of 3 in this result and i want to get the last sales_price for each room so i in the end i would have 3 result with room id of 1 -2 -3 and with thier last price . just to mention i sorted them by date before the result

Body:
You can use this code for getting last record:

    for ($f = 0; $f < count($room_id); $f++) {
        for ($i = 0; $i < count($dates); $i++) {
            $roomprice[$f] = RoomPricingHistory::
            Where('accommodation_room_id', $room_id[$f])
            ->whereDate('from_date', '<=', $dates[$i])
            ->whereDate('to_date', '>=', $dates[$i])
            ->orderBy('created_at', 'desc')->first();
    }
}


问:
The background image for my website gets out of proportion when viewed in phones and other small screen sizes
I'm having issues with re-sizing my background image in CSS to fit other smaller screens than the intended screen size of my laptop

I have already tried 'background-size: contain' and 'background-repeat : no-repeat'. still, the background image blew out of proportion. I have a set of parameters for the image, which is 'height: 100vh;'

```<code>/* with this, only a fraction of image is seen in phone */

header {
    background - image: -webkit - linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - image: linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - size: cover;
    height: 100 vh;
    background - position: center;
    background - repeat: no - repeat;
    background - attachment: fixed;
}

/* with this a grey background appears in phone screens */
header {
    background - image: -webkit - linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - image: linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - size: contain;
    height: 100 vh;

    background - position: center;
    background - repeat: no - repeat;
    background - attachment: fixed;
}
</code>```

I expect the image to fit all screen sizes without zooming in and blurring, but the results always blew out of proportion.

答:
Assuming that

```<code>background-size:cover;
</code>```

is working
I would suggest that you create two versions of your background image- a landscape one for pc's and laptops that resizes with the screen (proportion of screens tend to remain similar) and a portrait one for mobile phones. Your image might get cut off at the corners because of varying phone screen proportions.

Body:
I'm having issues with re-sizing my background image in CSS to fit other smaller screens than the intended screen size of my laptop

I have already tried 'background-size: contain' and 'background-repeat : no-repeat'. still, the background image blew out of proportion. I have a set of parameters for the image, which is 'height: 100vh;'

/* with this, only a fraction of image is seen in phone */

header {
    background - image: -webkit - linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - image: linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - size: cover;
    height: 100 vh;
    background - position: center;
    background - repeat: no - repeat;
    background - attachment: fixed;
}

/* with this a grey background appears in phone screens */
header {
    background - image: -webkit - linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - image: linear - gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.7)), url(img / hero.jpg);
    background - size: contain;
    height: 100 vh;

    background - position: center;
    background - repeat: no - repeat;
    background - attachment: fixed;
}

I expect the image to fit all screen sizes without zooming in and blurring, but the results always blew out of proportion.

Body:
Assuming that

background-size:cover;

is working
I would suggest that you create two versions of your background image- a landscape one for pc's and laptops that resizes with the screen (proportion of screens tend to remain similar) and a portrait one for mobile phones. Your image might get cut off at the corners because of varying phone screen proportions.


问:
My SQL table is missing mysteriously
On the live server a table was not found mysteriously. I twas working normally but suddenly i got sql error of missing table. I looked through phpmyadmin i found that a table was really missing mysteriously. It happened first time in my MYSQL life.
Can you please tell me what happened, why the table vanished mysteriously?</p>

答: Maybe a SQL injection attack dropped the table?  Have you checked the database logs?</p>

Title: My SQL table is missing mysteriously