问:
Model Driven Form Nested FormArray Control in a FormGroup control
I have a form group like so:

```<code> this.form = fb.group({
  'teacher': [''],
  'schools': fb.array([
      fb.group({
        'school_name': [''],
        'school_description': [''],
        'events': fb.array([
          fb.group({
            'event_name': ['']
          })
        ])
      })
  ])
});
const control = (<FormArray>this.form.controls['schools']).controls[0]['events'];
</code>```

How do I get the nested array control 'events'?

```<code>const control = (<FormArray>this.form.controls['schools']).controls[0]['events'];
</code>```

答:
In case you want to change a value for a nested FormArray, for me this works:

(<FormArray>this.formModel.controls['schools']).at(el).patchValue({school_name:'your new value'});

el is the index element for which one you want to apply the patch value.

Body:
I have a form group like so:

 this.form = fb.group({
  'teacher': [''],
  'schools': fb.array([
      fb.group({
        'school_name': [''],
        'school_description': [''],
        'events': fb.array([
          fb.group({
            'event_name': ['']
          })
        ])
      })
  ])
});
const control = (<FormArray>this.form.controls['schools']).controls[0]['events'];

How do I get the nested array control 'events'?

const control = (<FormArray>this.form.controls['schools']).controls[0]['events'];


来源: stackexchange

问:
Read a text file in WP7
in order to test my WP7 application with the emulator, I have to read a text file with a large input.
I have some problem to read it and to use the isolate storage.
More in details, the application is not able to read the file from my local disk.
How can i put the txt file into isolate storage?
Many thanks </p>

答: A simple way to test this would be to package the file in the XAP. If you don't need to modify the file while your app is running you can leave it there and just read it. Alternatively you can load it down to isolated storage at a convenient time while your app is running.</p>

ContentLicense: CC BY-SA 2.5

Title: Read a text file in WP7


问:
Yesod database migration loop
I am running Yesod and accessing a MySQL database.

My model is:

```<code>User
    ident Text
    password Text Maybe
    UniqueUser ident
    deriving Typeable
Email
    email Text
    userId UserId Maybe
    verkey Text Maybe
    UniqueEmail email
Comment json -- Adding "json" causes ToJSON and FromJSON instances to be derived.
    message Text
    userId UserId Maybe
    deriving Eq
    deriving Show

 -- By default this file is used in Model.hs (which is imported by Foundation.hs)
</code>```

When I run the Yesod application, it repeats the following:

```<code>Starting devel application
Migrating: ALTER TABLE `user` ALTER COLUMN `password` DROP DEFAULT
28/Mar/2017:23:46:44 +0200 [Debug#SQL] ALTER TABLE `user` ALTER COLUMN `password` DROP DEFAULT; []
devel.hs: ConnectionError {errFunction = "query", errNumber = 1101, errMessage = "BLOB/TEXT column 'password' can't have a default value"}
Unexpected: child process exited with ExitFailure 1
Trying again
Starting devel application
Migrating: ALTER TABLE `user` ALTER COLUMN `password` DROP DEFAULT
28/Mar/2017:23:46:46 +0200 [Debug#SQL] ALTER TABLE `user` ALTER COLUMN `password` DROP DEFAULT; []
devel.hs: ConnectionError {errFunction = "query", errNumber = 1101, errMessage = "BLOB/TEXT column 'password' can't have a default value"}
Unexpected: child process exited with ExitFailure 1
Trying again
</code>```

It goes in a never ending loop.

A workaround is commenting the following line from Application.hs which means disabling database migration:

```<code>runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc
</code>```

But if I use the workaround, I get another error:

```<code>28/Mar/2017:23:56:28 +0200 [Error#yesod-core] Foundation.hs:(137,5)-(144,45): Non-exhaustive patterns in function isAuthorized
 @(yesod-core-1.4.32-6HthMZNCl0sEMRz6GJ4QO1:Yesod.Core.Class.Yesod ./Yesod/Core/Class/Yesod.hs:693:5)
28/Mar/2017:23:56:28 +0200 [Debug#SQL] SELECT `ident`,`password` FROM `user` WHERE `id`=? ; [PersistInt64 1]
GET /test
  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
  Status: 500 Internal Server Error 0.006514s
</code>```

答:
It seems like this bug related to migration and default values.

You can try this workaround to change the behaviour of MySQL In default values or maybe try changing the type of the column from text to varchar?

ContentLicense: CC BY-SA 3.0

Title: Yesod database migration loop

Body:
I am running Yesod and accessing a MySQL database.

My model is:

User
    ident Text
    password Text Maybe
    UniqueUser ident
    deriving Typeable
Email
    email Text
    userId UserId Maybe
    verkey Text Maybe
    UniqueEmail email
Comment json -- Adding "json" causes ToJSON and FromJSON instances to be derived.
    message Text
    userId UserId Maybe
    deriving Eq
    deriving Show

 -- By default this file is used in Model.hs (which is imported by Foundation.hs)

When I run the Yesod application, it repeats the following:

Starting devel application
Migrating: ALTER TABLE `user` ALTER COLUMN `password` DROP DEFAULT
28/Mar/2017:23:46:44 +0200 [Debug#SQL] ALTER TABLE `user` ALTER COLUMN `password` DROP DEFAULT; []
devel.hs: ConnectionError {errFunction = "query", errNumber = 1101, errMessage = "BLOB/TEXT column 'password' can't have a default value"}
Unexpected: child process exited with ExitFailure 1
Trying again
Starting devel application
Migrating: ALTER TABLE `user` ALTER COLUMN `password` DROP DEFAULT
28/Mar/2017:23:46:46 +0200 [Debug#SQL] ALTER TABLE `user` ALTER COLUMN `password` DROP DEFAULT; []
devel.hs: ConnectionError {errFunction = "query", errNumber = 1101, errMessage = "BLOB/TEXT column 'password' can't have a default value"}
Unexpected: child process exited with ExitFailure 1
Trying again

It goes in a never ending loop.

A workaround is commenting the following line from Application.hs which means disabling database migration:

runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc

But if I use the workaround, I get another error:

28/Mar/2017:23:56:28 +0200 [Error#yesod-core] Foundation.hs:(137,5)-(144,45): Non-exhaustive patterns in function isAuthorized
 @(yesod-core-1.4.32-6HthMZNCl0sEMRz6GJ4QO1:Yesod.Core.Class.Yesod ./Yesod/Core/Class/Yesod.hs:693:5)
28/Mar/2017:23:56:28 +0200 [Debug#SQL] SELECT `ident`,`password` FROM `user` WHERE `id`=? ; [PersistInt64 1]
GET /test
  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
  Status: 500 Internal Server Error 0.006514s


问:
Pandas: how to add missing columns to a DataFrame when assigning Series as row
I have a bunch of Pandas Series which are produced one at a time, and I want to assign each of them as a row in a DataFrame, with the columns of the DataFrame being the union of all Series index values.

For example:

```<code>import numpy as np
import pandas as pd

# the names of all series are known in advance
df = pd.DataFrame(index=['A', 'B'])

# in reality there are many long series, not just two
a = pd.Series({'v':0, 'w':1, 'x':2, 'y':3}, name='A')
b = pd.Series({              'x':4, 'y':5, 'z':6}, name='B')

# generate and assign each series as one row in the frame
for row in (a,b):
    # create new columns - this is what I want to eliminate
    for column in row.index.difference(df.columns):
        df[column] = np.nan

    df.loc[row.name] = row

print(df)
</code>```

This produces the desired result:

```<code>     v    w    x    y    z
A  0.0  1.0  2.0  3.0  NaN
B  NaN  NaN  4.0  5.0  6.0
</code>```

But without the for column loop, it produces an empty DataFrame with no columns.

I am looking to eliminate the for column loop.  I don't know all the columns ahead of time.  I also hoped to assign np.nan to all the new columns in a vectorized way, but that doesn't work due to an old issue I submitted here: https://github.com/pandas-dev/pandas/issues/13658

答:
You can pass the multiple series as list to the DataFrame constructor:

```<code>import pandas as pd

a = pd.Series({'v':0, 'w':1, 'x':2, 'y':3}, name='A')
b = pd.Series({              'x':4, 'y':5, 'z':6}, name='B')

df = pd.DataFrame([a, b])
print(df)

    v    w    x    y    z
A   0.0  1.0  2.0  3.0  NaN
B   NaN  NaN  4.0  5.0  6.0
</code>```

Body:
I have a bunch of Pandas Series which are produced one at a time, and I want to assign each of them as a row in a DataFrame, with the columns of the DataFrame being the union of all Series index values.

For example:

import numpy as np
import pandas as pd

# the names of all series are known in advance
df = pd.DataFrame(index=['A', 'B'])

# in reality there are many long series, not just two
a = pd.Series({'v':0, 'w':1, 'x':2, 'y':3}, name='A')
b = pd.Series({              'x':4, 'y':5, 'z':6}, name='B')

# generate and assign each series as one row in the frame
for row in (a,b):
    # create new columns - this is what I want to eliminate
    for column in row.index.difference(df.columns):
        df[column] = np.nan

    df.loc[row.name] = row

print(df)

This produces the desired result:

     v    w    x    y    z
A  0.0  1.0  2.0  3.0  NaN
B  NaN  NaN  4.0  5.0  6.0

But without the for column loop, it produces an empty DataFrame with no columns.

I am looking to eliminate the for column loop.  I don't know all the columns ahead of time.  I also hoped to assign np.nan to all the new columns in a vectorized way, but that doesn't work due to an old issue I submitted here: https://github.com/pandas-dev/pandas/issues/13658

Body:
You can pass the multiple series as list to the DataFrame constructor:

import pandas as pd

a = pd.Series({'v':0, 'w':1, 'x':2, 'y':3}, name='A')
b = pd.Series({              'x':4, 'y':5, 'z':6}, name='B')

df = pd.DataFrame([a, b])
print(df)

    v    w    x    y    z
A   0.0  1.0  2.0  3.0  NaN
B   NaN  NaN  4.0  5.0  6.0


问:
Can I use an if statement with multiple conditions? PHP
I bet I can, but would it work like this?

```<code>function dutchDateNames($) {
        $day = explode('-', $date)[2];
        $dutchday = ($day < 10) ? substr($day, 1) : $day;

        $month = explode('-', $date)[1];
        if ($month == '01' . '02') {
            $dutchmonth = 'Januari' . 'Februari';
        }

        $dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
        return $dutchdate
    }
</code>```

So, if $month is 01, $dutchmonth should be Januari. If $month is 02, $dutchmonth should be Februari, and so on.
I have the feeling I'm not doing this right?

答:
Like thatyou would not return any month cause you concatenate (mounth 0102 does not exist).

If i correctly understand your question i think an array will be better :

```<code>$month = explode('-', $date)[1]; //Ok you use this data like an index

$letterMonth = ['01' => 'Januari', '02' => 'Februari', ....]; // Create an array with correspondance number -> letter month

$dutchmonth = $letterMonth[$month]; Get the good month using your index
</code>```

Body:
I bet I can, but would it work like this?

function dutchDateNames($) {
        $day = explode('-', $date)[2];
        $dutchday = ($day < 10) ? substr($day, 1) : $day;

        $month = explode('-', $date)[1];
        if ($month == '01' . '02') {
            $dutchmonth = 'Januari' . 'Februari';
        }

        $dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
        return $dutchdate
    }

So, if $month is 01, $dutchmonth should be Januari. If $month is 02, $dutchmonth should be Februari, and so on.
I have the feeling I'm not doing this right?

Body:
Like thatyou would not return any month cause you concatenate (mounth 0102 does not exist).

If i correctly understand your question i think an array will be better :

$month = explode('-', $date)[1]; //Ok you use this data like an index

$letterMonth = ['01' => 'Januari', '02' => 'Februari', ....]; // Create an array with correspondance number -> letter month

$dutchmonth = $letterMonth[$month]; Get the good month using your index


问:
i run my application on android 6.0.1 and give thats type of error
```<code>FATAL EXCEPTION: IntentService[]
Process: com.frenzin.alert, PID: 5892
java.lang.SecurityException: getDeviceId: Neither user 10240 nor current process has android.permission.READ_PHONE_STATE.
at android.os.Parcel.readException(Parcel.java:1620)
at android.os.Parcel.readException(Parcel.java:1573)
at com.android.internal.telephony.ITelephony$Stub$Proxy.getDeviceId(ITelephony.java:4207)
at android.telephony.TelephonyManager.getDeviceId(TelephonyManager.java:706)
at com.frenzin.alert.RegistrationIntentService.onHandleIntent(RegistrationIntentService.java:44)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.os.HandlerThread.run(HandlerThread.java:61)
</code>```

答:
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. If the device is running Android 6.0 or higher, and your app's target SDK is 23 or higher: The app has to list the permissions in the manifest, and it must request each dangerous permission it needs while the app is running. The user can grant or deny each permission, and the app can continue to run with limited capabilities even if the user denies a permission request.

To request permission in runtime, go to https://developer.android.com/training/permissions/requesting.html


问:
How to show a marker tooltip that can overflow the map container?
In my map, I have to show some markers that have relatively large tooltips attached to them (a div with roughly 100x200px). The map container itself is about 350px in height, so you very often run into situations where your tooltips are cut off at the map borders.

From what I can see, the map container has overflow: hidden; set in its CSS, which is because of the way the tiles get shown (they move "under" the container). When I set the overflow to visible, it seems to work, but then the map floods the page.

Is there a plugin or some best practice to achieve the desired behaviour without completely changing leaflet under the hood?

答: Here is a possible solution, instead of appending the tootip to the map container, append it as the last child of document.body then just call getBoundingClientRect() on the marker DOM node on hover or on click and use it to position the tootip next to your marker node. That way, your tootip won't be constrained by the size of the map container.


问:
Current location title? Mapkit
I'm making an application with MapKit. Here's an image of how it looks:

And I want to change (Current location) title of the symbol current location from that pin.

Here's code:

```<code>import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate,    MKMapViewDelegate {

@IBOutlet weak var theMap: MKMapView!
let locationManager = CLLocationManager()

override func viewDidLoad()
{
    super.viewDidLoad()

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()

    let location = self.locationManager.location

    var latitude: Double = location.coordinate.latitude
    var longitude: Double = location.coordinate.longitude

    println("GPS Súradnice :: \(latitude), \(longitude)")

    theMap.delegate = self
    theMap.mapType = MKMapType.Standard
    theMap.showsUserLocation = true

}

override func didReceiveMemoryWarning()
{
    super.didReceiveMemoryWarning()

}

//--- Find Address of Current Location ---//

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
    //--- CLGeocode to get address of current location ---//
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in

        if (error != nil)
        {
            println("Reverse geocoder failed with error" + error.localizedDescription)
            return
        }

        if placemarks.count > 0
        {
            let pm = placemarks[0] as! CLPlacemark
            self.displayLocationInfo(pm)
        }
        else
        {
            println("Problem with the data received from geocoder")
        }
    })

}

func displayLocationInfo(placemark: CLPlacemark?)
{
    if let Placemark = placemark
    {
        //Stop updating kvôli vydrži baterke
        locationManager.stopUpdatingLocation()
        let adresa = (Placemark.thoroughfare != nil) ? Placemark.thoroughfare : "Ulica: "
        let cislo = (Placemark.subThoroughfare != nil) ? Placemark.subThoroughfare : "Číslo ulice:"
        let mesto = (Placemark.locality != nil) ? Placemark.locality : "Mesto: "
        let stat = (Placemark.country != nil) ? Placemark.country : "Štát: "

        var coordinates:CLLocationCoordinate2D = placemark!.location.coordinate

        var pointAnnotation:MKPointAnnotation = MKPointAnnotation()
        pointAnnotation.coordinate = coordinates
        pointAnnotation.title = "\(adresa) \(cislo)"
        pointAnnotation.subtitle = "\(adresa) \(cislo), \(mesto), \(stat)"

        self.theMap.addAnnotation(pointAnnotation)
        self.theMap.centerCoordinate = coordinates
        self.theMap.selectAnnotation(pointAnnotation, animated: true)

        println(mesto)
        println(adresa)
        println(cislo)
        println(stat)

    }

}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
{
    println("Chyba pri aktualizovaní lokácie " + error.localizedDescription)
}

}
</code>```

答:
//swift 3

```<code>let annotation = MKPointAnnotation()
annotation.coordinate = center
annotation.title = "title"
Annotation.subtitle = “Subtitle”
mapView.addAnnotation(annotation)
</code>```

I think,http://swift3devlopment.blogspot.in/ here you get more details of MapKit

Title: Current location title? Mapkit

Body:
I'm making an application with MapKit. Here's an image of how it looks:

And I want to change (Current location) title of the symbol current location from that pin.

Here's code:

import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate,    MKMapViewDelegate {

@IBOutlet weak var theMap: MKMapView!
let locationManager = CLLocationManager()

override func viewDidLoad()
{
    super.viewDidLoad()

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()

    let location = self.locationManager.location

    var latitude: Double = location.coordinate.latitude
    var longitude: Double = location.coordinate.longitude

    println("GPS Súradnice :: \(latitude), \(longitude)")

    theMap.delegate = self
    theMap.mapType = MKMapType.Standard
    theMap.showsUserLocation = true

}

override func didReceiveMemoryWarning()
{
    super.didReceiveMemoryWarning()

}

//--- Find Address of Current Location ---//

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
{
    //--- CLGeocode to get address of current location ---//
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in

        if (error != nil)
        {
            println("Reverse geocoder failed with error" + error.localizedDescription)
            return
        }

        if placemarks.count > 0
        {
            let pm = placemarks[0] as! CLPlacemark
            self.displayLocationInfo(pm)
        }
        else
        {
            println("Problem with the data received from geocoder")
        }
    })

}

func displayLocationInfo(placemark: CLPlacemark?)
{
    if let Placemark = placemark
    {
        //Stop updating kvôli vydrži baterke
        locationManager.stopUpdatingLocation()
        let adresa = (Placemark.thoroughfare != nil) ? Placemark.thoroughfare : "Ulica: "
        let cislo = (Placemark.subThoroughfare != nil) ? Placemark.subThoroughfare : "Číslo ulice:"
        let mesto = (Placemark.locality != nil) ? Placemark.locality : "Mesto: "
        let stat = (Placemark.country != nil) ? Placemark.country : "Štát: "

        var coordinates:CLLocationCoordinate2D = placemark!.location.coordinate

        var pointAnnotation:MKPointAnnotation = MKPointAnnotation()
        pointAnnotation.coordinate = coordinates
        pointAnnotation.title = "\(adresa) \(cislo)"
        pointAnnotation.subtitle = "\(adresa) \(cislo), \(mesto), \(stat)"

        self.theMap.addAnnotation(pointAnnotation)
        self.theMap.centerCoordinate = coordinates
        self.theMap.selectAnnotation(pointAnnotation, animated: true)

        println(mesto)
        println(adresa)
        println(cislo)
        println(stat)

    }

}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
{
    println("Chyba pri aktualizovaní lokácie " + error.localizedDescription)
}

}

Body:
//swift 3

let annotation = MKPointAnnotation()
annotation.coordinate = center
annotation.title = "title"
Annotation.subtitle = “Subtitle”
mapView.addAnnotation(annotation)

I think,http://swift3devlopment.blogspot.in/ here you get more details of MapKit


问:
Error saying Conversion failed when converting date and/or time from character string
I use the following query:

```<code>SELECT
    CONVERT(DATETIME, (RIGHT(b.dob, 4) + '-' +
                       SUBSTRING(b.dob, 3, 2) + '-' +
                       LEFT (b.dob, 2)), 111)
FROM [Load].[123_Qualification] AS b
</code>```

The Dob is a nvarchar column, and I want to convert it to a DateTime datatype, but I am  getting an error:

Conversion failed when converting date and/or time from character string.

答:
You really should change your table to store the dob in a date data type column. Read Aaron Bertrand's Bad habits to kick : choosing the wrong data type.

One way to solve it is to use the built in ISDATE function and a CTE:

Create and populate sample table: (Please save us this step in your future questions)

```<code>DECLARE @T AS TABLE
(
    dob varchar(8)
)

INSERT INTO @T VALUES
('23031971'),
('23131971'),
('12031999'),
('02031980'),
('29021972'),
('29021973'),
('29021974'),
('29021975'),
('31121976')
</code>```

Use a common table expression to format all dob values to yyyy-mm-dd (This is a standard format that sql server will recognize regardless of reginal, language and date format settings)

```<code>;WITH CTE AS
(
    SELECT (RIGHT(b.dob, 4) + '-' +
            SUBSTRING(b.dob, 3, 2) + '-' +
            LEFT (b.dob, 2)) As formatted_dob
    FROM @T AS b
)
</code>```

Select from the common table expression only those values that represents a valid date. (Note in the sample data there are multiple 29th of february, but only one in the results)

```<code>SELECT CAST(formatted_dob as DATE) As date_of_birth
FROM CTE
WHERE ISDATE(formatted_dob) = 1
</code>```

Results:

```<code>date_of_birth
23.03.1971 00:00:00
12.03.1999 00:00:00
02.03.1980 00:00:00
29.02.1972 00:00:00
31.12.1976 00:00:00
</code>```

See a live demo on rextester

Body:
I use the following query:

SELECT
    CONVERT(DATETIME, (RIGHT(b.dob, 4) + '-' +
                       SUBSTRING(b.dob, 3, 2) + '-' +
                       LEFT (b.dob, 2)), 111)
FROM [Load].[123_Qualification] AS b

The Dob is a nvarchar column, and I want to convert it to a DateTime datatype, but I am  getting an error:

Conversion failed when converting date and/or time from character string.

Body:
You really should change your table to store the dob in a date data type column. Read Aaron Bertrand's Bad habits to kick : choosing the wrong data type.

One way to solve it is to use the built in ISDATE function and a CTE:

Create and populate sample table: (Please save us this step in your future questions)

DECLARE @T AS TABLE
(
    dob varchar(8)
)

INSERT INTO @T VALUES
('23031971'),
('23131971'),
('12031999'),
('02031980'),
('29021972'),
('29021973'),
('29021974'),
('29021975'),
('31121976')

Use a common table expression to format all dob values to yyyy-mm-dd (This is a standard format that sql server will recognize regardless of reginal, language and date format settings)

;WITH CTE AS
(
    SELECT (RIGHT(b.dob, 4) + '-' +
            SUBSTRING(b.dob, 3, 2) + '-' +
            LEFT (b.dob, 2)) As formatted_dob
    FROM @T AS b
)

Select from the common table expression only those values that represents a valid date. (Note in the sample data there are multiple 29th of february, but only one in the results)

SELECT CAST(formatted_dob as DATE) As date_of_birth
FROM CTE
WHERE ISDATE(formatted_dob) = 1

Results:

date_of_birth
23.03.1971 00:00:00
12.03.1999 00:00:00
02.03.1980 00:00:00
29.02.1972 00:00:00
31.12.1976 00:00:00

See a live demo on rextester

ContentLicense: CC BY-SA 4.0


问:
TFS Migration from 2012 & 2017 to 2017
We have to upgrade TFS version from 2012 to 2017. The problem we are facing is we have some team projects in TFS 2017 lower environment and some team projects are in 2012 production instance. We want to migrate 2012 team projects and 2017 team projects to a new TFS 2017 production instance under one team project collection. We need some help in defining the upgrade/migration strategy keeping this scenario in consideration.  Please let us know if someone can lend help. </p>

答:
It supports to move collections from TFS 2012 to TFS 2017 directly follow the move collection document. You don't need to upgrade your TFS 2012 to TFS 2017 first. It does the upgrading When it attaches to the new TFS instance, just follow theses steps:

Detach the collection

Back up the collection database

Move the collection database

Attach the collection

Configure Features for team projects(option)

Note: The step5 is done when you move TFS 2012 collection. If you move TFS 2017 collection to your new TFS 2017. This step doesn't need to do.

And you want these 2 collection to merge to one collection totally. This is not support currently. There are two many conflicts: changeset numbers, work item IDs, builds,etc. And it also doesn't support to move team project from one collection to another. Here is a user voice about move team projects between collections which has many votes already:

We still plan to evaluate picking this work up and possibly getting it into the following next major release. We’ll provide an update once a decision has been reached.

Title: TFS Migration from 2012 & 2017 to 2017


问:
stream volume in SoundPool vs volume in AudioManager
I am so confused...

SoundPool.play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)

volume here is from 0.0 to 1.0

Tutorials I've seen recommend to calculate stream volume as:

```<code>AudioManager mgr = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);

int streamVolume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);

streamVolume = streamVolume / AudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
</code>```

which makes sense.

I would assume that this volume would override global media volume set by user in phone and I can change volume for my app independently by changing stream volume in soundPool.

But in reality it works like multiplier - if I set 0.5 for volume in soundpool, the actual volume will be always half of the global one. Very easy to reproduce:

set global media volume in
phone settings to max

set volume in activity using soundpool.play to 0.5 - play sound

set volume in soundpool.play to 1 - play sound, it will be two times louder

Can somebody explain why it works like that? is volume passed to SoundPool.play method really a multiplier to the global volume?

答: Yes, the volume parameters are with respect to the global volume.  If you want to play a sound at the current volume setting just pass "1" as the volume.</p>

Body:
I am so confused...

SoundPool.play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)

volume here is from 0.0 to 1.0

Tutorials I've seen recommend to calculate stream volume as:

AudioManager mgr = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);

int streamVolume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);

streamVolume = streamVolume / AudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);

which makes sense.

I would assume that this volume would override global media volume set by user in phone and I can change volume for my app independently by changing stream volume in soundPool.

But in reality it works like multiplier - if I set 0.5 for volume in soundpool, the actual volume will be always half of the global one. Very easy to reproduce:

set global media volume in
phone settings to max

set volume in activity using soundpool.play to 0.5 - play sound

set volume in soundpool.play to 1 - play sound, it will be two times louder

Can somebody explain why it works like that? is volume passed to SoundPool.play method really a multiplier to the global volume?


问:
Creating a new key with values within a sub dictionary of a dictionary
I have a dictionary:

```<code>my_dictionary = {'Kyle': {'benz':2, 'ford':1, 'bmw':5, 'gmc':6, 'subaru':3}
              'Jim': {'benz':5, 'ford':9, 'bmw':3, 'gmc':1, 'subaru':2}
              'Tom': {'benz':3, 'ford':4, 'bmw':8, 'gmc':2, 'subaru':10}
              'Eric: {'benz':6, 'ford':7, 'bmw':9, 'gmc':5, 'subaru':3}
             }
</code>```

My objective is to create a new key called: 'german_cars'

Which takes the sum of the keys 'bmw' and 'benz'.

I want to have the newly created key 'german_cars' within my_dictionary like this:

```<code>my_dictionary = {'Kyle': {'benz':2, 'ford':1, 'bmw':5, 'gmc':6, 'subaru':3, 'german_cars':7}
              'Jim': {'benz':5, 'ford':9, 'bmw':3, 'gmc':1, 'subaru':2, 'german_cars':8}
              'Tom': {'benz':3, 'ford':4, 'bmw':8, 'gmc':2, 'subaru':10, 'german_cars':11}
              'Eric: {'benz':6, 'ford':7, 'bmw':9, 'gmc':5, 'subaru':3, 'german_cars':15}
             }
</code>```

I would like to know an automated way of doing this using for loops.

答:
You can loop over the outer dictionary and then modify the inner dicts directly:

```<code>for owner, cars in my_dictionary.items():
    cars['german_cars'] = cars.get('bmw', 0) + cars.get('benz', 0)
</code>```

FWIW, I used dict.get() so the lookups would not fail if either "bmw" or "benz" was missing.

Body:
I have a dictionary:

my_dictionary = {'Kyle': {'benz':2, 'ford':1, 'bmw':5, 'gmc':6, 'subaru':3}
              'Jim': {'benz':5, 'ford':9, 'bmw':3, 'gmc':1, 'subaru':2}
              'Tom': {'benz':3, 'ford':4, 'bmw':8, 'gmc':2, 'subaru':10}
              'Eric: {'benz':6, 'ford':7, 'bmw':9, 'gmc':5, 'subaru':3}
             }

My objective is to create a new key called: 'german_cars'

Which takes the sum of the keys 'bmw' and 'benz'.

I want to have the newly created key 'german_cars' within my_dictionary like this:

my_dictionary = {'Kyle': {'benz':2, 'ford':1, 'bmw':5, 'gmc':6, 'subaru':3, 'german_cars':7}
              'Jim': {'benz':5, 'ford':9, 'bmw':3, 'gmc':1, 'subaru':2, 'german_cars':8}
              'Tom': {'benz':3, 'ford':4, 'bmw':8, 'gmc':2, 'subaru':10, 'german_cars':11}
              'Eric: {'benz':6, 'ford':7, 'bmw':9, 'gmc':5, 'subaru':3, 'german_cars':15}
             }

I would like to know an automated way of doing this using for loops.

Body:
You can loop over the outer dictionary and then modify the inner dicts directly:

for owner, cars in my_dictionary.items():
    cars['german_cars'] = cars.get('bmw', 0) + cars.get('benz', 0)

FWIW, I used dict.get() so the lookups would not fail if either "bmw" or "benz" was missing.


问:
Opening tsv file via Notepad++ and save it in text format
I'm trying to automate a process that where in a folder there are 50+ tsv files. They have to be opened via notepad++ and save it as .txt file in the same folder.

Using the below code i'm opening the tsv file in notepad++.

```<code>MyTxtFile = Shell("C:\Program Files (x86)\Notepad++\notepad++.exe I:\Test\Sample.tsv", 1)
</code>```

However, i have no idea how to save it as txt file by using VBA. Is it doable? If yes kindly teach me how.

Thank you in advance :)

答:
If you only want to rename the files from *.tsv to *.txt you could use the command line</p>

```<code>ren *.tsv *.txt
</code>```

Body:
I'm trying to automate a process that where in a folder there are 50+ tsv files. They have to be opened via notepad++ and save it as .txt file in the same folder.

Using the below code i'm opening the tsv file in notepad++.

MyTxtFile = Shell("C:\Program Files (x86)\Notepad++\notepad++.exe I:\Test\Sample.tsv", 1)

However, i have no idea how to save it as txt file by using VBA. Is it doable? If yes kindly teach me how.

Thank you in advance :)

Body:
If you only want to rename the files from *.tsv to *.txt you could use the command line

ren *.tsv *.txt


问:
How to Mock a service inside Controller Advice for Unit Testing
The problem is I cannot unit test/mock this because the messageByLocaleService is null in the Controller Advice. Please suggest any way to inject the mock of messageByLocaleSerI have a set up like this:

ExceptionControllerAdvice class:

```<code>@Autowired
private MessageByLocaleService messageByLocaleService; //CANNOT MOCK THIS

@ControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<String> handleUnexpectedException(HttpServletRequest request, Exception e) {

        //build response as below
        String s = messageByLocaleService.buildMessage(HttpStatus.ERROR,"User Not Valid"); // GETTING NULL HERE
        //and send the response back to the client here
    }
}
</code>```

Controller method:

```<code>@RequestMapping(value = "${foo.controller.requestMappingUrl.login}",
                                 method = RequestMethod.POST)
public ResponseMessage<String> loginUser(
            @RequestParam("username") String username,
               HttpServletRequest httpServletRequest,
               HttpServletResponse httpServletResponse) throws Exception {

       return fooService.login(username);
}
</code>```

JUnit setup & test methods:

```<code>@InjectMocks
private ProjectController projectController;

@Mock
private FooService fooService;

@Mock
private MessageByLocaleService messageByLocaleService;

@Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.standaloneSetup(projectController)
                .setMessageConverters(new MappingJackson2HttpMessageConverter())
                .setControllerAdvice(new ExceptionControllerAdvice()).build();
}

@SuppressWarnings("unchecked")
@Test
    public void testControllerUserNotFoundException() throws Exception {
        Response resp = new Response();
        resp.setStatusCode(StatusCode.UserNotFoundErrorCode);
        when(fooService.login(any(String.class)).
        thenThrow(UserNotFoundException.class);

        mockMvc.perform(post("/service-user/1.0/auth/login?&username=test")
                        .contentType(contentType)).
     andExpect(status().isNotAcceptable())
                .andExpect(jsonPath("$.statusCode", is("ERRORCODE144")));
}
</code>```

答:
It's a little hard to tell from the code that you've shown, but presumeably you are testing ExceptionControllerAdvice and create an instance somewhere in your Unit Test. If you do, try the following

@InjectMocks private ExceptionControllerAdvice  unitUnderTest;
@Mock private MessageByLocaleService messageByLocaleService;

I believe that Mockito will create a Mock of the MessageByLocaleService and auto inject it into your ExceptionControllerAdvice.

Body:
The problem is I cannot unit test/mock this because the messageByLocaleService is null in the Controller Advice. Please suggest any way to inject the mock of messageByLocaleSerI have a set up like this:

ExceptionControllerAdvice class:

@Autowired
private MessageByLocaleService messageByLocaleService; //CANNOT MOCK THIS

@ControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<String> handleUnexpectedException(HttpServletRequest request, Exception e) {

        //build response as below
        String s = messageByLocaleService.buildMessage(HttpStatus.ERROR,"User Not Valid"); // GETTING NULL HERE
        //and send the response back to the client here
    }
}

Controller method:

@RequestMapping(value = "${foo.controller.requestMappingUrl.login}",
                                 method = RequestMethod.POST)
public ResponseMessage<String> loginUser(
            @RequestParam("username") String username,
               HttpServletRequest httpServletRequest,
               HttpServletResponse httpServletResponse) throws Exception {

       return fooService.login(username);
}

JUnit setup & test methods:

@InjectMocks
private ProjectController projectController;

@Mock
private FooService fooService;

@Mock
private MessageByLocaleService messageByLocaleService;

@Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    mockMvc = MockMvcBuilders.standaloneSetup(projectController)
                .setMessageConverters(new MappingJackson2HttpMessageConverter())
                .setControllerAdvice(new ExceptionControllerAdvice()).build();
}

@SuppressWarnings("unchecked")
@Test
    public void testControllerUserNotFoundException() throws Exception {
        Response resp = new Response();
        resp.setStatusCode(StatusCode.UserNotFoundErrorCode);
        when(fooService.login(any(String.class)).
        thenThrow(UserNotFoundException.class);

        mockMvc.perform(post("/service-user/1.0/auth/login?&username=test")
                        .contentType(contentType)).
     andExpect(status().isNotAcceptable())
                .andExpect(jsonPath("$.statusCode", is("ERRORCODE144")));
}


问:
Editing data in multiple columns from front-end
I have a table in the database, I can edit a column of particular row at a time. but, i want to edit multiple columns of a single row at a time with an option of edit and then save it to the database ,we can do it from back-end by editing in the database itself. But, i want to do it from front-end .Now i am able to display the data in the table. I am new to coding , so can anyone help me where to start for this particular task of editing multiple columns at the same time.
Here is the code for displaying the data..</p>

```<code><?php
include('db.php');
include 'header.php';
include 'gobacktomenu.php';
$TND_ID =  $_GET['TND_ID'];
$sql = "SELECT * FROM new_tnds WHERE TND_ID = ('".$TND_ID."')";
$result = $link->query($sql);
echo "<div style='overflow-x:auto;'><table border = '1'><font size = '2' face='verdana'>
<th>TND ID</th><th>Site name S1</th><th>Site name S2</th><th>Call sign S1</th><th>Idea ID S1</th><th>Call sign S2</th><th>Idea ID S2</th><th>Site to integrate</th><th>True azimuth (°) S1</th><th>True azimuth (°) S2</th><th>Pathlength (km)</th><th>TR Antenna diameter (m)</th><th>TR Antenna height (m) S1</th><th>TR Antenna height (m) S2</th><th>Channel ID S1</th><th>Channel ID S2</th><th>Design frequency S1</th><th>Design frequency S2</th><th>Polarization</th><th>Radio model</th><th>TX power (dBm)</th><th>Receive signal (dBm)</th><th>Planning Remarks</th><th>Projects Remarks Uploaded by</th><th>O & M Remarks Uploaded by</th><th>Planning Remarks Uploaded by</th><th>TXN NOC Remarks Uploaded by</th></tr>";

if ($result->num_rows > 0) {
    // output data of each row
    $row = $result->fetch_assoc();

        echo "<tr><td>".$row["TND_ID"]."</td><td>".$row["Site_name_S1"]."</td><td>".$row["Site_name_S2"]."</td><td>".$row["Call_sign_S1"]."</td><td>".$row["Idea_ID_S1"]."</td><td>".$row["Call_sign_S2"]."</td><td>".$row["Idea_ID_S2"]."</td><td>".$row["Site_to_integrate"]."</td><td>".$row["True_azimuth_S1"]."</td><td>".$row["True_azimuth_S2"]."</td><td>".$row["Path_length_(km)"]."</td><td>".$row["TR_Antenna_diameter_(m)_S1"]."</td><td>".$row["TR_Antenna_height_(m)_S1"]."</td><td>".$row["TR_Antenna_height_(m)_S2"]."</td><td>".$row["#1_Channel_ID_S1"]."</td><td>".$row["#1_Channel_ID_S2"]."</td><td>".$row["#1_Design_frequency_S1"]."</td><td>".$row["#1_Design_frequency_S2"]."</td><td>".$row["Polarization"]."</td><td>".$row["Radio_model_S1"]."</td><td>".$row["TX_power_(dBm)_S1"]."</td><td>".$row["Receive_signal_(dBm)_S1"]."</td><td>".$row["Planning_Remarks"]."</td><td>".$row["Projects_remarksupdated_user_name"]."</td><td>".$row["O_M_remarksupdated_user_name"]."</td><td>".$row["Planning_remarksupdated_user_name"]."</td><td>".$row["txn_noc_remarksupdated_user_name"]."</td></tr>";

}
echo "</table></div>";
$link->close();
?>
</code>```

答:
You need use form instead of table while editing and pass the fetched values on input of form and write update query on form submit.

```<code>if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
}
if(isset($_POST['submit']))
{
$query = "update details set Site_name_S1='$_POST['submit']',Site_name_S2='$_POST['Site_name_S2']',Call_sign_S1='$_POST['Call_sign_S1']',Idea_ID_S1='$_POST['Idea_ID_S1'] where TND_ID=$_POST['TND_ID']";

$res = mysql_query($query);
}
<form method="post">
<input type="text" name="id" value="<?php echo $row['TND_ID'] ;?>" >
<input type="text" name="Site_name_S1" value="<?php echo $row['Site_name_S1'] ;?>" >
<input type="text" name="Site_name_S2" value="<?php echo $row['Site_name_S2'] ;?>" >
<input type="text" name="Call_sign_S1" value="<?php echo $row['Call_sign_S1'] ;?>" >
<input type="text" name="Idea_ID_S1" value="<?php echo $row['Idea_ID_S1'] ;?>" >
<input type="submit" name="submit">
</form>
</code>```

Just check the quotes while writing update query.

Body:
I have a table in the database, I can edit a column of particular row at a time. but, i want to edit multiple columns of a single row at a time with an option of edit and then save it to the database ,we can do it from back-end by editing in the database itself. But, i want to do it from front-end .Now i am able to display the data in the table. I am new to coding , so can anyone help me where to start for this particular task of editing multiple columns at the same time.
Here is the code for displaying the data..

<?php
include('db.php');
include 'header.php';
include 'gobacktomenu.php';
$TND_ID =  $_GET['TND_ID'];
$sql = "SELECT * FROM new_tnds WHERE TND_ID = ('".$TND_ID."')";
$result = $link->query($sql);
echo "

TND ID	Site name S1	Site name S2	Call sign S1	Idea ID S1	Call sign S2	Idea ID S2	Site to integrate	True azimuth (°) S1	True azimuth (°) S2	Pathlength (km)	TR Antenna diameter (m)	TR Antenna height (m) S1	TR Antenna height (m) S2	Channel ID S1	Channel ID S2	Design frequency S1	Design frequency S2	Polarization	Radio model	TX power (dBm)	Receive signal (dBm)	Planning Remarks	Projects Remarks Uploaded by	O & M Remarks Uploaded by	Planning Remarks Uploaded by	TXN NOC Remarks Uploaded by
";

if ($result->num_rows > 0) {
    // output data of each row
    $row = $result->fetch_assoc();

        echo "
".$row["TND_ID"]."	".$row["Site_name_S1"]."	".$row["Site_name_S2"]."	".$row["Call_sign_S1"]."	".$row["Idea_ID_S1"]."	".$row["Call_sign_S2"]."	".$row["Idea_ID_S2"]."	".$row["Site_to_integrate"]."	".$row["True_azimuth_S1"]."	".$row["True_azimuth_S2"]."	".$row["Path_length_(km)"]."	".$row["TR_Antenna_diameter_(m)_S1"]."	".$row["TR_Antenna_height_(m)_S1"]."	".$row["TR_Antenna_height_(m)_S2"]."	".$row["#1_Channel_ID_S1"]."	".$row["#1_Channel_ID_S2"]."	".$row["#1_Design_frequency_S1"]."	".$row["#1_Design_frequency_S2"]."	".$row["Polarization"]."	".$row["Radio_model_S1"]."	".$row["TX_power_(dBm)_S1"]."	".$row["Receive_signal_(dBm)_S1"]."	".$row["Planning_Remarks"]."	".$row["Projects_remarksupdated_user_name"]."	".$row["O_M_remarksupdated_user_name"]."	".$row["Planning_remarksupdated_user_name"]."	".$row["txn_noc_remarksupdated_user_name"]."
";

}
echo "

";
$link->close();
?>

Body:
You need use form instead of table while editing and pass the fetched values on input of form and write update query on form submit.

if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
}
if(isset($_POST['submit']))
{
$query = "update details set Site_name_S1='$_POST['submit']',Site_name_S2='$_POST['Site_name_S2']',Call_sign_S1='$_POST['Call_sign_S1']',Idea_ID_S1='$_POST['Idea_ID_S1'] where TND_ID=$_POST['TND_ID']";

$res = mysql_query($query);
}
<form method="post">
<input type="text" name="id" value="<?php echo $row['TND_ID'] ;?>" >
<input type="text" name="Site_name_S1" value="<?php echo $row['Site_name_S1'] ;?>" >
<input type="text" name="Site_name_S2" value="<?php echo $row['Site_name_S2'] ;?>" >
<input type="text" name="Call_sign_S1" value="<?php echo $row['Call_sign_S1'] ;?>" >
<input type="text" name="Idea_ID_S1" value="<?php echo $row['Idea_ID_S1'] ;?>" >
<input type="submit" name="submit">
</form>

Just check the quotes while writing update query.


问:
Remove XML comments using Regex in bash
I want to remove XML comments in bash using regex (awk, sed, grep...)
I have looked at other questions about this but they are missing something. Here's my xml code

```<code><Table>
    <!--
   to be removed bla bla bla bla bla bl............

    removeee

    to be removeddddd
    -->

<row>
        <column name="example"  value="1" ></column>
    </row>
</Table>
</code>```

So I'm comparing 2 xml files but I don't want the comparison to take into account the comments. I do this

```<code>diff file1.xml file2.xml | sed '/<!--/,/-->/d'
</code>```

but that only removes the line that starts with

答:
The most simple solution to remove all comments from a textfile I could come up with is:

```<code>sed 's/<!--/\x0<!--/g;s/-->/-->\x0/g' | grep -zv '^<!--' | tr -d '\0'
</code>```

To explain:

The sed will put in a null char like this:

```<code><Table>
    \0<!--
   to be removed bla bla bla bla bla bl............

    removeee

    to be removeddddd
    -->\0

<row>
        <column name="example"  value="1" ></column>
    </row>
</Table>
</code>```

Than the grep -z will treat that character as "line separator"

\n

\n\n<row>\n        <column name="example"  value="1" ></column>\n    </row>\n
\n

grep -v will remove the middle part.

And finally tr -d will remove the \0 again.

In this case it should be applied to both files before comparing e.g.:

```<code>diff <(sed 's/<!--/\x0<!--/g;s/-->/-->\x0/g' file1.xml | grep -zv '^<!--' | tr -d '\0') <(sed 's/<!--/\x0<!--/g;s/-->/-->\x0/g' file2.xml | grep -zv '^<!--' | tr -d '\0')
</code>```

or more readable with a function:

```<code>stripcomments() {cat "$@" | sed 's/<!--/\x0<!--/g;s/-->/-->\x0/g' | grep -zv '^<!--' | tr -d '\0'}

diff <(stripcomments file1.xml) <(stripcomments file2.xml)
</code>```

In theory there might be some issues with CDATA blocks, as they can be used to have unbalanced comments, and there is a higher probability of them having important null-characters, but I have never seen such an xml file in real life.

So for most valid xml-files this should work.

Title: Remove XML comments using Regex in bash

Body:
I want to remove XML comments in bash using regex (awk, sed, grep...)
I have looked at other questions about this but they are missing something. Here's my xml code

<row>
        <column name="example"  value="1" ></column>
    </row>

So I'm comparing 2 xml files but I don't want the comparison to take into account the comments. I do this

diff file1.xml file2.xml | sed '//d'

but that only removes the line that starts with

Body:
The most simple solution to remove all comments from a textfile I could come up with is:

sed 's/<!--/\x0<!--/g;s/-->/-->\x0/g' | grep -zv '^<!--' | tr -d '\0'

To explain:

The sed will put in a null char like this:

<Table>
    \0<!--
   to be removed bla bla bla bla bla bl............

    removeee

    to be removeddddd
    -->\0

<row>
        <column name="example"  value="1" ></column>
    </row>
</Table>

Than the grep -z will treat that character as "line separator"

<Table>\n

<!--\n   to be removed bla bla bla bla bla bl............\n\n        removeee\n\n    to be removeddddd\n    -->

\n\n<row>\n        <column name="example"  value="1" ></column>\n    </row>\n</Table>\n

grep -v will remove the middle part.

And finally tr -d will remove the \0 again.

In this case it should be applied to both files before comparing e.g.:

diff <(sed 's/<!--/\x0<!--/g;s/-->/-->\x0/g' file1.xml | grep -zv '^<!--' | tr -d '\0') <(sed 's/<!--/\x0<!--/g;s/-->/-->\x0/g' file2.xml | grep -zv '^<!--' | tr -d '\0')

or more readable with a function:

stripcomments() {cat "$@" | sed 's/<!--/\x0<!--/g;s/-->/-->\x0/g' | grep -zv '^<!--' | tr -d '\0'}

diff <(stripcomments file1.xml) <(stripcomments file2.xml)

In theory there might be some issues with CDATA blocks, as they can be used to have unbalanced comments, and there is a higher probability of them having important null-characters, but I have never seen such an xml file in real life.

So for most valid xml-files this should work.


问:
Sonata User Bundle security roles template override
I am using symphony 2.8 with sonata admin/user/fosuser bundle. Everything is working fine. I just want to override the security roles template because the roles title is not in meaningful. I have followed the below solution.

https://github.com/dianuj89/Sonata-admin-user-friendly-view-for-security-roles

But it's not working I also have done to customization but getting following error.

Catchable Fatal Error: Argument 1 passed to Sonata\UserBundle\Form\Type\SecurityRolesType::__construct() must be an instance of Sonata\UserBundle\Security\EditableRolesBuilder, none given, called in D:\xampp\htdocs\energyvalue\vendor\sonata-project\core-bundle\Form\Extension\DependencyInjectionExtension.php on line 94 and defined

Your help is much appreciated. Thanks

答:
The simplest way is to provide translation messages for the role names.</p>

```<code>#Resources/translations/messages.en.yml

ROLE_SONATA_ADMIN: 'My custom label'
</code>```

Body:
The simplest way is to provide translation messages for the role names.

#Resources/translations/messages.en.yml

ROLE_SONATA_ADMIN: 'My custom label'


问:
Intermittent bugs - sometimes this code works and sometimes it doesn't!
This code intermittently works. It's running on a small microcontroller. It will work fine even after restarting the processor, but if I change some part of the code, it breaks. This makes me think that it's some kind of pointer bug or memory corruption. What's happening is the coordinate, p_res.pos.x is sometimes read as 0 (the incorrect value) and 96 (the correct value) when it is passed to write_circle_outlined. y seems to be correct most of the time. If anyone can spot anything obviously wrong please point it out!

```<code>int demo_game()
{
    long int d;
    int x, y;
    struct WorldCamera p_viewer;
    struct Point3D_LLA p_subj;
    struct Point2D_CalcRes p_res;
    p_viewer.hfov = 27;
    p_viewer.vfov = 32;
    p_viewer.width = 192;
    p_viewer.height = 128;
    p_viewer.p.lat = 51.26f;
    p_viewer.p.lon = -1.0862f;
    p_viewer.p.alt = 100.0f;
    p_subj.lat = 51.20f;
    p_subj.lon = -1.0862f;
    p_subj.alt = 100.0f;
    while(1)
    {
        fill_buffer(draw_buffer_mask, 0x0000);
        fill_buffer(draw_buffer_level, 0xffff);
        compute_3d_transform(&p_viewer, &p_subj, &p_res, 10000.0f);
        x = p_res.pos.x;
        y = p_res.pos.y;
        write_circle_outlined(x, y, 1.0f / p_res.est_dist, 0, 0, 0, 1);
        p_viewer.p.lat -= 0.0001f;
        //p_viewer.p.alt -= 0.00001f;
        d = 20000;
        while(d--);
    }
    return 1;
}
</code>```

The code for compute_3d_transform is:

```<code>void compute_3d_transform(struct WorldCamera *p_viewer, struct Point3D_LLA *p_subj, struct Point2D_CalcRes *res, float cliph)
{
    // Estimate the distance to the waypoint. This isn't intended to replace
    // proper lat/lon distance algorithms, but provides a general indication
    // of how far away our subject is from the camera. It works accurately for
    // short distances of less than 1km, but doesn't give distances in any
    // meaningful unit (lat/lon distance?)
    res->est_dist = hypot2(p_viewer->p.lat - p_subj->lat, p_viewer->p.lon - p_subj->lon);
    // Save precious cycles if outside of visible world.
    if(res->est_dist > cliph)
        goto quick_exit;
    // Compute the horizontal angle to the point.
    // atan2(y,x) so atan2(lon,lat) and not atan2(lat,lon)!
    res->h_angle = RAD2DEG(angle_dist(atan2(p_viewer->p.lon - p_subj->lon, p_viewer->p.lat - p_subj->lat), p_viewer->yaw));
    res->small_dist = res->est_dist * 0.0025f; // by trial and error this works well.
    // Using the estimated distance and altitude delta we can calculate
    // the vertical angle.
    res->v_angle = RAD2DEG(atan2(p_viewer->p.alt - p_subj->alt, res->est_dist));
    // Normalize the results to fit in the field of view of the camera if
    // the point is visible. If they are outside of (0,hfov] or (0,vfov]
    // then the point is not visible.
    res->h_angle += p_viewer->hfov / 2;
    res->v_angle += p_viewer->vfov / 2;
    // Set flags.
    if(res->h_angle < 0 || res->h_angle > p_viewer->hfov)
        res->flags |= X_OVER;
    if(res->v_angle < 0 || res->v_angle > p_viewer->vfov)
        res->flags |= Y_OVER;
    res->pos.x = (res->h_angle / p_viewer->hfov) * p_viewer->width;
    res->pos.y = (res->v_angle / p_viewer->vfov) * p_viewer->height;
    return;
quick_exit:
    res->flags |= X_OVER | Y_OVER;
    return;
}
</code>```

Structure for the results:

```<code>typedef struct Point2D_Pixel { unsigned int x, y; };

// Structure for storing calculated results (from camera transforms.)
typedef struct Point2D_CalcRes
{
    struct Point2D_Pixel pos;
    float h_angle, v_angle, est_dist, small_dist;
    int flags;
};
</code>```

The code is part of an open source project of mine so it's okay to post a lot of code here.

答:
Whenever the output differs, it possibly means some value is not initialized and the outcome depends on the garbage value present in a variable. Keeping that in mind, I looked for uninitialized variables. the structure p_res is not initialized.

```<code>if(res->est_dist > cliph)
        goto quick_exit;
</code>```

that means if condition may turn out to be true or false depending on what garbage value is stored in res->est_dist. When if condition turns out to true, it goes straight to quick_exit label and doesn't update  p_res.pos.x. If condition turned out to be false then its updated.

Body:
This code intermittently works. It's running on a small microcontroller. It will work fine even after restarting the processor, but if I change some part of the code, it breaks. This makes me think that it's some kind of pointer bug or memory corruption. What's happening is the coordinate, p_res.pos.x is sometimes read as 0 (the incorrect value) and 96 (the correct value) when it is passed to write_circle_outlined. y seems to be correct most of the time. If anyone can spot anything obviously wrong please point it out!

int demo_game()
{
    long int d;
    int x, y;
    struct WorldCamera p_viewer;
    struct Point3D_LLA p_subj;
    struct Point2D_CalcRes p_res;
    p_viewer.hfov = 27;
    p_viewer.vfov = 32;
    p_viewer.width = 192;
    p_viewer.height = 128;
    p_viewer.p.lat = 51.26f;
    p_viewer.p.lon = -1.0862f;
    p_viewer.p.alt = 100.0f;
    p_subj.lat = 51.20f;
    p_subj.lon = -1.0862f;
    p_subj.alt = 100.0f;
    while(1)
    {
        fill_buffer(draw_buffer_mask, 0x0000);
        fill_buffer(draw_buffer_level, 0xffff);
        compute_3d_transform(&p_viewer, &p_subj, &p_res, 10000.0f);
        x = p_res.pos.x;
        y = p_res.pos.y;
        write_circle_outlined(x, y, 1.0f / p_res.est_dist, 0, 0, 0, 1);
        p_viewer.p.lat -= 0.0001f;
        //p_viewer.p.alt -= 0.00001f;
        d = 20000;
        while(d--);
    }
    return 1;
}

The code for compute_3d_transform is:

void compute_3d_transform(struct WorldCamera *p_viewer, struct Point3D_LLA *p_subj, struct Point2D_CalcRes *res, float cliph)
{
    // Estimate the distance to the waypoint. This isn't intended to replace
    // proper lat/lon distance algorithms, but provides a general indication
    // of how far away our subject is from the camera. It works accurately for
    // short distances of less than 1km, but doesn't give distances in any
    // meaningful unit (lat/lon distance?)
    res->est_dist = hypot2(p_viewer->p.lat - p_subj->lat, p_viewer->p.lon - p_subj->lon);
    // Save precious cycles if outside of visible world.
    if(res->est_dist > cliph)
        goto quick_exit;
    // Compute the horizontal angle to the point.
    // atan2(y,x) so atan2(lon,lat) and not atan2(lat,lon)!
    res->h_angle = RAD2DEG(angle_dist(atan2(p_viewer->p.lon - p_subj->lon, p_viewer->p.lat - p_subj->lat), p_viewer->yaw));
    res->small_dist = res->est_dist * 0.0025f; // by trial and error this works well.
    // Using the estimated distance and altitude delta we can calculate
    // the vertical angle.
    res->v_angle = RAD2DEG(atan2(p_viewer->p.alt - p_subj->alt, res->est_dist));
    // Normalize the results to fit in the field of view of the camera if
    // the point is visible. If they are outside of (0,hfov] or (0,vfov]
    // then the point is not visible.
    res->h_angle += p_viewer->hfov / 2;
    res->v_angle += p_viewer->vfov / 2;
    // Set flags.
    if(res->h_angle < 0 || res->h_angle > p_viewer->hfov)
        res->flags |= X_OVER;
    if(res->v_angle < 0 || res->v_angle > p_viewer->vfov)
        res->flags |= Y_OVER;
    res->pos.x = (res->h_angle / p_viewer->hfov) * p_viewer->width;
    res->pos.y = (res->v_angle / p_viewer->vfov) * p_viewer->height;
    return;
quick_exit:
    res->flags |= X_OVER | Y_OVER;
    return;
}

Structure for the results:

typedef struct Point2D_Pixel { unsigned int x, y; };

// Structure for storing calculated results (from camera transforms.)
typedef struct Point2D_CalcRes
{
    struct Point2D_Pixel pos;
    float h_angle, v_angle, est_dist, small_dist;
    int flags;
};

The code is part of an open source project of mine so it's okay to post a lot of code here.

Body:
Whenever the output differs, it possibly means some value is not initialized and the outcome depends on the garbage value present in a variable. Keeping that in mind, I looked for uninitialized variables. the structure p_res is not initialized.

if(res->est_dist > cliph)
        goto quick_exit;

that means if condition may turn out to be true or false depending on what garbage value is stored in res->est_dist. When if condition turns out to true, it goes straight to quick_exit label and doesn't update  p_res.pos.x. If condition turned out to be false then its updated.


问:
How to fix test failing with "No ModelAndView found"?
This class is in the top of my tests hierarchy:

```<code>@TestPropertySource("/test.properties")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public abstract class ApplicationAbstractTest {
}
</code>```

And few more test classes:

```<code>@WebAppConfiguration
@ActiveProfiles("mysql")
abstract public class AbstractControllerTest extends ApplicationAbstractTest {

    protected MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @PostConstruct
    private void postConstruct() {
        mockMvc = MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .apply(springSecurity())
                .build();
    }
}
</code>```

JsonUserServiceTest:

```<code>@ActiveProfiles("json")
public class JsonUserServiceTest extends ApplicationAbstractTest {
    @Before
    public void setUp() throws Exception {
        ...
    }
}
</code>```

ContactControllerTest:

```<code>public class ContactControllerTest extends AbstractControllerTest {
    @Test
    public void testGet() throws Exception {
        mockMvc.perform(get("/update-" + ID + "-contact")
                .with(userAuth(USER)))
//                .andExpect(status().isOk())
                .andDo(print())
                .andExpect(view().name("details"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/details.jsp"));
    }
}
</code>```

So, when I run ContactControllerTest along - it is successfull, and print method shows me:

```<code>Handler:
             Type = com.telecom.web.ContactController
           Method = public java.lang.String com.myApp.web.ContactController.details(java.lang.Integer,org.springframework.ui.ModelMap)
</code>```

But when I run all tests, so JsonUserServiceTest runs first, ContactControllerTest fails. And print shows:

```<code>Handler:
             Type = null
...
java.lang.AssertionError: No ModelAndView found
</code>```

What is wrong in configuration? Or how troubleshoot it?

UPD:
at the same time, test like this, allways works fine:

```<code>public class UserControllerTest extends AbstractControllerTest {
    @Test
    public void testRegister() throws Exception {
        mockMvc.perform(get("/register"))
                .andDo(print())
                .andExpect(view().name("profile"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/profile.jsp"));
    }
}
</code>```

UPD:
There is controller's method I'm testing:

```<code>@GetMapping("/update-{id}-contact")
public String details(@PathVariable Integer id, ModelMap model) {
    Integer userId = AuthorizedUser.id();
    LOG.info("get contact {} for User {}", id, userId);
    Contact contact = service.get(id, userId);
    model.addAttribute("contact", contact);
    return "details";
}
</code>```

I also have such bean:

```<code>@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/jsp/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}
</code>```

UPD: I've tried configure mockMvc in separate class:

```<code>@Configuration
public class TestConfig {

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Bean
    public MockMvc mockMvc() {
        return MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .apply(springSecurity())
                .build();
    }
}
</code>```

And added it here:

```<code>@WebAppConfiguration
@ContextConfiguration(classes = {TestConfig.class})
@ActiveProfiles("mysql")
abstract public class AbstractControllerTest extends ApplicationAbstractTest {
</code>```

but I've received:

java.lang.IllegalStateException: springSecurityFilterChain cannot be
  null. Ensure a Bean with the name springSecurityFilterChain
  implementing Filter is present or inject the Filter to be used.

答:
The WARN message doesn't cause the test cases to fail. It just says that  Entity manager factory is registered twice. This will only be an issue if you cluster your application using the same Entity Manager Factory. For test case run it is not a cause for concern.

The root cause of the testcase failure is in these two lines

```<code> .andExpect(view().name("details"))
 .andExpect(forwardedUrl("/WEB-INF/jsp/details.jsp"));
</code>```

Please check if the project has a view named "details" and the forwardded url is "/WEB-INF/jsp/details.jsp"

Update

Could you please try this

```<code>@Configuration
public class TestConfig {

@Autowired
private Filter springSecurityFilterChain;

@Autowired
private WebApplicationContext webApplicationContext;

@Bean
public MockMvc mockMvc() {
    return MockMvcBuilders
            .webAppContextSetup(webApplicationContext)
            .apply(springSecurityFilterChain)
            .build();
}
}
</code>```

Body:
This class is in the top of my tests hierarchy:

@TestPropertySource("/test.properties")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public abstract class ApplicationAbstractTest {
}

And few more test classes:

@WebAppConfiguration
@ActiveProfiles("mysql")
abstract public class AbstractControllerTest extends ApplicationAbstractTest {

    protected MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @PostConstruct
    private void postConstruct() {
        mockMvc = MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .apply(springSecurity())
                .build();
    }
}

JsonUserServiceTest:

@ActiveProfiles("json")
public class JsonUserServiceTest extends ApplicationAbstractTest {
    @Before
    public void setUp() throws Exception {
        ...
    }
}

ContactControllerTest:

public class ContactControllerTest extends AbstractControllerTest {
    @Test
    public void testGet() throws Exception {
        mockMvc.perform(get("/update-" + ID + "-contact")
                .with(userAuth(USER)))
//                .andExpect(status().isOk())
                .andDo(print())
                .andExpect(view().name("details"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/details.jsp"));
    }
}

So, when I run ContactControllerTest along - it is successfull, and print method shows me:

Handler:
             Type = com.telecom.web.ContactController
           Method = public java.lang.String com.myApp.web.ContactController.details(java.lang.Integer,org.springframework.ui.ModelMap)

But when I run all tests, so JsonUserServiceTest runs first, ContactControllerTest fails. And print shows:

Handler:
             Type = null
...
java.lang.AssertionError: No ModelAndView found

What is wrong in configuration? Or how troubleshoot it?

UPD:
at the same time, test like this, allways works fine:

public class UserControllerTest extends AbstractControllerTest {
    @Test
    public void testRegister() throws Exception {
        mockMvc.perform(get("/register"))
                .andDo(print())
                .andExpect(view().name("profile"))
                .andExpect(forwardedUrl("/WEB-INF/jsp/profile.jsp"));
    }
}

UPD:
There is controller's method I'm testing:

@GetMapping("/update-{id}-contact")
public String details(@PathVariable Integer id, ModelMap model) {
    Integer userId = AuthorizedUser.id();
    LOG.info("get contact {} for User {}", id, userId);
    Contact contact = service.get(id, userId);
    model.addAttribute("contact", contact);
    return "details";
}

I also have such bean:

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/jsp/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}

UPD: I've tried configure mockMvc in separate class:

@Configuration
public class TestConfig {

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Bean
    public MockMvc mockMvc() {
        return MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .apply(springSecurity())
                .build();
    }
}

And added it here:

@WebAppConfiguration
@ContextConfiguration(classes = {TestConfig.class})
@ActiveProfiles("mysql")
abstract public class AbstractControllerTest extends ApplicationAbstractTest {

but I've received:

java.lang.IllegalStateException: springSecurityFilterChain cannot be
  null. Ensure a Bean with the name springSecurityFilterChain
  implementing Filter is present or inject the Filter to be used.

Body:
The WARN message doesn't cause the test cases to fail. It just says that  Entity manager factory is registered twice. This will only be an issue if you cluster your application using the same Entity Manager Factory. For test case run it is not a cause for concern.

The root cause of the testcase failure is in these two lines

 .andExpect(view().name("details"))
 .andExpect(forwardedUrl("/WEB-INF/jsp/details.jsp"));

Please check if the project has a view named "details" and the forwardded url is "/WEB-INF/jsp/details.jsp"

Update

Could you please try this

@Configuration
public class TestConfig {

@Autowired
private Filter springSecurityFilterChain;

@Autowired
private WebApplicationContext webApplicationContext;

@Bean
public MockMvc mockMvc() {
    return MockMvcBuilders
            .webAppContextSetup(webApplicationContext)
            .apply(springSecurityFilterChain)
            .build();
}
}


问:
C Pointers about the different data type
Pointer always stores a integer value i.e address so why do we need to declare them with different data type.

Like

```<code>int a=3,*p=&a;
char c=r,*cha=&r;
</code>```

why can't we do like

```<code>int *c;
char r=a;
c=&r;
</code>```

答:
Essentially it's because

Pointer arithmetic would not work if the pointer types were not explicit.

The pointer to member operator would not work for struct pointer types.

The alignment requirements for types can differ. It might be possible to store a char at a location where it's not possible to store an int.

The sizes of pointers are not guaranteed to be the same by the C standard: i.e. sizeof(int*) is not necessarily the same as sizeof(char*). This allows C to be used on exotic architectures.

Body:
Pointer always stores a integer value i.e address so why do we need to declare them with different data type.

Like

int a=3,*p=&a;
char c=r,*cha=&r;

why can't we do like

int *c;
char r=a;
c=&r;


问:
Get Image size from 4 pixel position using JavaScript or PHP

Can anybody here who help me to find width and height from the four corners, like in this picture i have 4 places

```<code>W - Width
H - Height

1 - 156W/116H
2 - 337W/54H
3 - 136W/312H
4 - 244/279H
</code>```

Is there any one who can provide a formula for finding the width and height from four positions using JavaScript or PHP?

答:
If we talking about the rectangle (all corners = 90°). And if you 4 points coordinates calculate from left top corner of the parent object/container/page. The rectangle dimension will be:</p>

```<code>point_01 = {'x':156, 'y': 116};
point_02 = {'x':337, 'y': 54};
point_03 = {'x':136, 'y': 312};
point_04 = {'x':244, 'y': 279};

rectangle = {
   'height':  point_03.y - point_01.y,
   'width' : point_02.x - point_01.x
};
</code>```

Body:
Can anybody here who help me to find width and height from the four corners, like in this picture i have 4 places

W - Width
H - Height

1 - 156W/116H
2 - 337W/54H
3 - 136W/312H
4 - 244/279H

Is there any one who can provide a formula for finding the width and height from four positions using JavaScript or PHP?

Body:
If we talking about the rectangle (all corners = 90°). And if you 4 points coordinates calculate from left top corner of the parent object/container/page. The rectangle dimension will be:

point_01 = {'x':156, 'y': 116};
point_02 = {'x':337, 'y': 54};
point_03 = {'x':136, 'y': 312};
point_04 = {'x':244, 'y': 279};

rectangle = {
   'height':  point_03.y - point_01.y,
   'width' : point_02.x - point_01.x
};


问:
zsh shortcut 'ctrl + A' not working
I recently switch from bash to zsh shell. To be more precise, the oh-my-zsh
Very nice, but the shortcut I most often use; jumping to the beginning/end of the line doesn't work anymore. From the docs it should be

```<code>ctrl + A --> beginning
ctrl + E --> end
</code>```

However, when I do that I get the following

```<code>$~> my-command
$~> my-command^A   # did a ctrl + A here
</code>```

Although I see this working by everybody else, on my system something seems to be different. Any suggestions what that might be ?

答:
If you're wondering why this happened: You likely have $EDITOR or $VISUAL set to vi/vim which made zsh default to the vi keymap which doesn't use ctrl+a for moving the caret.

Adding bindkey -e to ~/.zshrc will restore the old behavior (emacs keymap).

Title: zsh shortcut 'ctrl + A' not working

Body:
I recently switch from bash to zsh shell. To be more precise, the oh-my-zsh
Very nice, but the shortcut I most often use; jumping to the beginning/end of the line doesn't work anymore. From the docs it should be

ctrl + A --> beginning
ctrl + E --> end

However, when I do that I get the following

$~> my-command
$~> my-command^A   # did a ctrl + A here

Although I see this working by everybody else, on my system something seems to be different. Any suggestions what that might be ?


问:
Interactive R Shiny plot with and without using ggplot
I modified the interactive R Shiny plot from the R Shiny gallery to plot an interactive standard curve. I would like to plot the interactive plot without using ggplot2 library with just using R base plotting functions.

```<code>library(ggplot2)

XYdata <- data.frame(cbind(Values = c(91.8, 95.3,   99.8,   123.3,  202.9,  619.8,  1214.2, 1519.1, 1509.2, 1523.3, 1595.2, 1625.1),
                           Concn = c(1000, 300,    100,    30, 10, 3,  1,  0.3,    0.1,    0.03,   0.01,   0)))
ui <- fluidPage(
  fluidRow(
    column(width = 6,
           plotOutput("plot1", height = 350,
                      click = "plot1_click",
                      brush = brushOpts(
                        id = "plot1_brush"
                      )
           ),
           actionButton("exclude_toggle", "Toggle points"),
           actionButton("exclude_reset", "Reset")
    )
  )
)

server <- function(input, output) {
  # For storing which rows have been excluded
  vals <- reactiveValues(
    keeprows = rep(TRUE, nrow(XYdata))
  )
  NonScientific <- function(l) {l <- format(l, scientific = FALSE); parse(text=l)}

  output$plot1 <- renderPlot({
    # Plot the kept and excluded points as two separate data sets

    XYdata <- data.frame(cbind(Values = c(91.8, 95.3,   99.8,   123.3,  202.9,  619.8,  1214.2, 1519.1, 1509.2, 1523.3, 1595.2, 1625.1),
                           Concn = c(1000, 300,    100,    30, 10, 3,  1,  0.3,    0.1,    0.03,   0.01,   0)))
    keep    <- XYdata[ vals$keeprows, , drop = FALSE]
    exclude <- XYdata[!vals$keeprows, , drop = FALSE]
    keep <- subset(keep, Concn > 0)
    exclude <- subset(exclude, Concn > 0)
    nls.fit <- nls(Values ~ (ymax* keep$Concn / (ec50 + keep$Concn)) + Ns*keep$Concn + ymin, data=keep,
                   start=list(ymax=max(keep$Values), ymin = min(keep$Values), ec50 = 3, Ns = 0.2045514))
    keep$nls.pred <- fitted(nls.fit)

    ggplot(keep, aes(y = Values,x = Concn))+geom_point(size = 5,colour="red")+
    geom_smooth(method = "loess",fullrange = F, se = T, aes(Concn, nls.pred),size = 1.5,colour="blue1")+
      geom_point(data = exclude, shape = 21, fill = NA, color = "black",size = 5, alpha = 0.7) +
      xlab('Concentration (nM)')+ ylab('Units')+
      scale_x_log10(labels=NonScientific)+ggtitle("Standard Curve")+theme_classic()+
      theme(panel.background = element_rect(colour = "black", size=1),
            plot.margin = margin(1, 3, 0.5, 1, "cm"),
            plot.title = element_text(hjust = 0, face="bold",color="#993333", size=16),
            axis.title = element_text(face="bold", color="#993333", size=14),
            axis.text.x = element_text(face="bold", color="#666666", size=12),
            axis.text.y = element_text(face="bold", color="#666666", size=12))
  })

  # Toggle points that are clicked
  observeEvent(input$plot1_click, {
    res <- nearPoints(XYdata, input$plot1_click, allRows = TRUE)

    vals$keeprows <- xor(vals$keeprows, res$selected_)
  })

  # Toggle points that are brushed, when button is clicked
  observeEvent(input$exclude_toggle, {
    res <- brushedPoints(XYdata, input$plot1_brush, allRows = TRUE)

    vals$keeprows <- xor(vals$keeprows, res$selected_)
  })

  # Reset all points
  observeEvent(input$exclude_reset, {
    vals$keeprows <- rep(TRUE, nrow(XYdata))
  })

}

shinyApp(ui, server)
</code>```

I tried replacing the plotting portion of the script with the following but I am not able to interactively plot. What am I doing wrong here?

```<code> plot(Values ~ Concn, keep, subset = Concn > 0, col = 4, cex = 2, log = "x")
 title(main = "XY Std curve")
 lines(predict(nls.fit, new = list(Concn = Concn)) ~ Concn, keep)
 points(Values ~ Concn, exclude, subset = Concn > 0, col = 1, cex = 2, log = "x")
</code>```

答:
The working code implementing @HubertL's suggestion for someone like me to use for interactive plotting and to knockout outliers by clicking on or by selecting the point(s) using mouse:

```<code>XYdata <- data.frame(cbind(Values = c(91.8, 95.3,   99.8,   123.3,  202.9,  619.8,  1214.2, 1519.1, 1509.2, 1523.3, 1595.2, 1625.1),
                           Concn = c(1000, 300, 100,30, 10, 3,  1,  0.3,    0.1, 0.03, 0.01, 0)))
ui <- fluidPage(
  fluidRow(
    column(width = 6,
           plotOutput("plot1", height = 350,click = "plot1_click", brush = brushOpts(id = "plot1_brush")),
           actionButton("exclude_reset", "Reset")
    )
  )
)

server <- function(input, output) {
  # For storing which rows have been excluded
  vals <- reactiveValues(
    keeprows = rep(TRUE, nrow(XYdata))
  )
  NonScientific <- function(l) {l <- format(l, scientific = FALSE); parse(text=l)}

  output$plot1 <- renderPlot({
    # Plot the kept and excluded points as two separate data sets

    XYdata <- data.frame(cbind(Values = c(91.8, 95.3,   99.8,   123.3,  202.9,  619.8,  1214.2, 1519.1, 1509.2, 1523.3, 1595.2, 1625.1),
                           Concn = c(1000, 300,    100,    30, 10, 3,  1,  0.3,    0.1,    0.03,   0.01,   0)))
    keep    <- XYdata[ vals$keeprows, , drop = FALSE]
    exclude <- XYdata[!vals$keeprows, , drop = FALSE]
    keep <- subset(keep, Concn > 0)
    exclude <- subset(exclude, Concn > 0)
    o <- order(keep$Concn)
    keep <- keep[o, ]
    fo <- Values ~ (ymax* Concn / (ec50 + Concn)) + Ns * Concn + ymin
    st <- list(ymax=max(keep$Values), ymin = min(keep$Values), ec50 = 3, Ns = 0.2045514)
    nls.fit <- nls(fo, data = keep, start = st)
    plot(Values ~ Concn, keep, subset = Concn > 0, type = 'p',pch = 16,cex = 2, axes = FALSE, frame.plot = TRUE,log = "x")
    title(main = "Interactive Std curve")
    logRange <- with(keep, log(range(Concn[Concn > 0])))
    x <- exp(seq(logRange[1], logRange[2], length = 250))
    lines(x, predict(nls.fit, new = list(Concn = x)))
    points(Values ~ Concn, exclude, subset = Concn > 0, col = 1, cex = 2)
    my.at <- 10^(-2:3)
    axis(1, at = my.at, labels = formatC(my.at, format = "fg"))
    axis(2)
  })

  # Toggle points that are clicked
  observeEvent(input$plot1_click, {

    res <- nearPoints(XYdata, input$plot1_click, xvar="Concn", yvar="Values", allRows = TRUE)
    vals$keeprows <- xor(vals$keeprows, res$selected_)
  })

  # Reset all points
  observeEvent(input$exclude_reset, {
    vals$keeprows <- rep(TRUE, nrow(XYdata))
  })
}

shinyApp(ui, server)
</code>```

Body:
I modified the interactive R Shiny plot from the R Shiny gallery to plot an interactive standard curve. I would like to plot the interactive plot without using ggplot2 library with just using R base plotting functions.

library(ggplot2)

XYdata <- data.frame(cbind(Values = c(91.8, 95.3,   99.8,   123.3,  202.9,  619.8,  1214.2, 1519.1, 1509.2, 1523.3, 1595.2, 1625.1),
                           Concn = c(1000, 300,    100,    30, 10, 3,  1,  0.3,    0.1,    0.03,   0.01,   0)))
ui <- fluidPage(
  fluidRow(
    column(width = 6,
           plotOutput("plot1", height = 350,
                      click = "plot1_click",
                      brush = brushOpts(
                        id = "plot1_brush"
                      )
           ),
           actionButton("exclude_toggle", "Toggle points"),
           actionButton("exclude_reset", "Reset")
    )
  )
)

server <- function(input, output) {
  # For storing which rows have been excluded
  vals <- reactiveValues(
    keeprows = rep(TRUE, nrow(XYdata))
  )
  NonScientific <- function(l) {l <- format(l, scientific = FALSE); parse(text=l)}

  output$plot1 <- renderPlot({
    # Plot the kept and excluded points as two separate data sets

    XYdata <- data.frame(cbind(Values = c(91.8, 95.3,   99.8,   123.3,  202.9,  619.8,  1214.2, 1519.1, 1509.2, 1523.3, 1595.2, 1625.1),
                           Concn = c(1000, 300,    100,    30, 10, 3,  1,  0.3,    0.1,    0.03,   0.01,   0)))
    keep    <- XYdata[ vals$keeprows, , drop = FALSE]
    exclude <- XYdata[!vals$keeprows, , drop = FALSE]
    keep <- subset(keep, Concn > 0)
    exclude <- subset(exclude, Concn > 0)
    nls.fit <- nls(Values ~ (ymax* keep$Concn / (ec50 + keep$Concn)) + Ns*keep$Concn + ymin, data=keep,
                   start=list(ymax=max(keep$Values), ymin = min(keep$Values), ec50 = 3, Ns = 0.2045514))
    keep$nls.pred <- fitted(nls.fit)

    ggplot(keep, aes(y = Values,x = Concn))+geom_point(size = 5,colour="red")+
    geom_smooth(method = "loess",fullrange = F, se = T, aes(Concn, nls.pred),size = 1.5,colour="blue1")+
      geom_point(data = exclude, shape = 21, fill = NA, color = "black",size = 5, alpha = 0.7) +
      xlab('Concentration (nM)')+ ylab('Units')+
      scale_x_log10(labels=NonScientific)+ggtitle("Standard Curve")+theme_classic()+
      theme(panel.background = element_rect(colour = "black", size=1),
            plot.margin = margin(1, 3, 0.5, 1, "cm"),
            plot.title = element_text(hjust = 0, face="bold",color="#993333", size=16),
            axis.title = element_text(face="bold", color="#993333", size=14),
            axis.text.x = element_text(face="bold", color="#666666", size=12),
            axis.text.y = element_text(face="bold", color="#666666", size=12))
  })

  # Toggle points that are clicked
  observeEvent(input$plot1_click, {
    res <- nearPoints(XYdata, input$plot1_click, allRows = TRUE)

    vals$keeprows <- xor(vals$keeprows, res$selected_)
  })

  # Toggle points that are brushed, when button is clicked
  observeEvent(input$exclude_toggle, {
    res <- brushedPoints(XYdata, input$plot1_brush, allRows = TRUE)

    vals$keeprows <- xor(vals$keeprows, res$selected_)
  })

  # Reset all points
  observeEvent(input$exclude_reset, {
    vals$keeprows <- rep(TRUE, nrow(XYdata))
  })

}

shinyApp(ui, server)

I tried replacing the plotting portion of the script with the following but I am not able to interactively plot. What am I doing wrong here?

 plot(Values ~ Concn, keep, subset = Concn > 0, col = 4, cex = 2, log = "x")
 title(main = "XY Std curve")
 lines(predict(nls.fit, new = list(Concn = Concn)) ~ Concn, keep)
 points(Values ~ Concn, exclude, subset = Concn > 0, col = 1, cex = 2, log = "x")

Body:
The working code implementing @HubertL's suggestion for someone like me to use for interactive plotting and to knockout outliers by clicking on or by selecting the point(s) using mouse:

XYdata <- data.frame(cbind(Values = c(91.8, 95.3,   99.8,   123.3,  202.9,  619.8,  1214.2, 1519.1, 1509.2, 1523.3, 1595.2, 1625.1),
                           Concn = c(1000, 300, 100,30, 10, 3,  1,  0.3,    0.1, 0.03, 0.01, 0)))
ui <- fluidPage(
  fluidRow(
    column(width = 6,
           plotOutput("plot1", height = 350,click = "plot1_click", brush = brushOpts(id = "plot1_brush")),
           actionButton("exclude_reset", "Reset")
    )
  )
)

server <- function(input, output) {
  # For storing which rows have been excluded
  vals <- reactiveValues(
    keeprows = rep(TRUE, nrow(XYdata))
  )
  NonScientific <- function(l) {l <- format(l, scientific = FALSE); parse(text=l)}

  output$plot1 <- renderPlot({
    # Plot the kept and excluded points as two separate data sets

    XYdata <- data.frame(cbind(Values = c(91.8, 95.3,   99.8,   123.3,  202.9,  619.8,  1214.2, 1519.1, 1509.2, 1523.3, 1595.2, 1625.1),
                           Concn = c(1000, 300,    100,    30, 10, 3,  1,  0.3,    0.1,    0.03,   0.01,   0)))
    keep    <- XYdata[ vals$keeprows, , drop = FALSE]
    exclude <- XYdata[!vals$keeprows, , drop = FALSE]
    keep <- subset(keep, Concn > 0)
    exclude <- subset(exclude, Concn > 0)
    o <- order(keep$Concn)
    keep <- keep[o, ]
    fo <- Values ~ (ymax* Concn / (ec50 + Concn)) + Ns * Concn + ymin
    st <- list(ymax=max(keep$Values), ymin = min(keep$Values), ec50 = 3, Ns = 0.2045514)
    nls.fit <- nls(fo, data = keep, start = st)
    plot(Values ~ Concn, keep, subset = Concn > 0, type = 'p',pch = 16,cex = 2, axes = FALSE, frame.plot = TRUE,log = "x")
    title(main = "Interactive Std curve")
    logRange <- with(keep, log(range(Concn[Concn > 0])))
    x <- exp(seq(logRange[1], logRange[2], length = 250))
    lines(x, predict(nls.fit, new = list(Concn = x)))
    points(Values ~ Concn, exclude, subset = Concn > 0, col = 1, cex = 2)
    my.at <- 10^(-2:3)
    axis(1, at = my.at, labels = formatC(my.at, format = "fg"))
    axis(2)
  })

  # Toggle points that are clicked
  observeEvent(input$plot1_click, {

    res <- nearPoints(XYdata, input$plot1_click, xvar="Concn", yvar="Values", allRows = TRUE)
    vals$keeprows <- xor(vals$keeprows, res$selected_)
  })

  # Reset all points
  observeEvent(input$exclude_reset, {
    vals$keeprows <- rep(TRUE, nrow(XYdata))
  })
}

shinyApp(ui, server)


问:
JSF throws argument type mismatch when binding
I'm trying to do the following: When the user enters a value in the rich:calendar component, then the h:inputText should have its required attributed set to true. I'm following the instructions in this post: Reference JSF control's attributes via JavaScript

Sorry for creating another post, but I couldn't figure out how to post the code into the comments area and make it readable. The page throws this error:

javax.el.ELException: /pages/overtime/overtime-n.xhtml @121,65 binding="#{oc.overtimeDate}": java.lang.IllegalArgumentException: argument type mismatch

The problem is that the binding is inside a c:forEach loop, and I'm trying to use the loop variable to bind to. The overtime.overtimeItems is defined as an ArrayList<OvertimeComponent> with each OvertimeComponent object having various properties (overtimeDate, overtimeDateId, id, overtimeHours, etc.).

```<code><c:forEach items="#{overtime.overtimeItems}" var="oc">
  <rich:calendar value="#{oc.overtimeDate}"
    requiredMessage="Date 1 is required."
    id="#{oc.overtimeDateId}"
    binding="#{oc.overtimeDate}"
    required="#{oc.id == 1 ? true : false}">
  </rich:calendar>
  <h:inputText value="#{oc.overtimeHours}"
    id="#{oc.overtimeHoursId}"
    requiredMessage="Hours is required."
    required="#{not empty oc.overtimeDate.value}" >
  </h:inputText>
  .....
</c:forEach>
</code>```

How do I make the h:inputText required if the rich:calendar object has a value? There's a way to do this using the binding property of the calendar, but I'm not sure how to do it inside a c:forEach. I can't use AJAX for this project. Thanks.

答:
Why do you have both value and component binding on the calendar pointing to the same el expression ? You cannot do componentbinding on a richfaces calendar with type date.

Also, have you tried using ui:repeat instead of c:foreach ?

https://rogerkeays.com/jsf-c-foreach-vs-ui-repeat

c:foreach is known to give problems in a facelets context related to the jsf and jsp lifecycle mismatch. Have a look at the post above for more info.

Body:
I'm trying to do the following: When the user enters a value in the rich:calendar component, then the h:inputText should have its required attributed set to true. I'm following the instructions in this post: Reference JSF control's attributes via JavaScript

Sorry for creating another post, but I couldn't figure out how to post the code into the comments area and make it readable. The page throws this error:

javax.el.ELException: /pages/overtime/overtime-n.xhtml @121,65 binding="#{oc.overtimeDate}": java.lang.IllegalArgumentException: argument type mismatch

The problem is that the binding is inside a c:forEach loop, and I'm trying to use the loop variable to bind to. The overtime.overtimeItems is defined as an ArrayList<OvertimeComponent> with each OvertimeComponent object having various properties (overtimeDate, overtimeDateId, id, overtimeHours, etc.).

<c:forEach items="#{overtime.overtimeItems}" var="oc">
  <rich:calendar value="#{oc.overtimeDate}"
    requiredMessage="Date 1 is required."
    id="#{oc.overtimeDateId}"
    binding="#{oc.overtimeDate}"
    required="#{oc.id == 1 ? true : false}">
  </rich:calendar>
  <h:inputText value="#{oc.overtimeHours}"
    id="#{oc.overtimeHoursId}"
    requiredMessage="Hours is required."
    required="#{not empty oc.overtimeDate.value}" >
  </h:inputText>
  .....
</c:forEach>

How do I make the h:inputText required if the rich:calendar object has a value? There's a way to do this using the binding property of the calendar, but I'm not sure how to do it inside a c:forEach. I can't use AJAX for this project. Thanks.


问:
Can I use an if statement with multiple conditions? PHP
I bet I can, but would it work like this?

```<code>function dutchDateNames($) {
        $day = explode('-', $date)[2];
        $dutchday = ($day < 10) ? substr($day, 1) : $day;

        $month = explode('-', $date)[1];
        if ($month == '01' . '02') {
            $dutchmonth = 'Januari' . 'Februari';
        }

        $dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
        return $dutchdate
    }
</code>```

So, if $month is 01, $dutchmonth should be Januari. If $month is 02, $dutchmonth should be Februari, and so on.
I have the feeling I'm not doing this right?

答:
You may do any of these:

if else

```<code>if ($month == "01") {
    $dutchmonth = "Januari";
} else if($month == "02"){
    $dutchmonth = "Februari";
}
</code>```

switch

```<code>switch($month) {
    case "01":
        $dutchmonth = "Januari";
        break;
    case "02":
        $dutchmonth = "Februari";
        break;
}
</code>```

Using array

```<code>$month_arr = array('01' => "Januari", '02' => "Februari");
$dutchmonth = $month_arr[$month];
</code>```

NOTE: To use multiple if conditions use logical operators && or ||

Body:
I bet I can, but would it work like this?

function dutchDateNames($) {
        $day = explode('-', $date)[2];
        $dutchday = ($day < 10) ? substr($day, 1) : $day;

        $month = explode('-', $date)[1];
        if ($month == '01' . '02') {
            $dutchmonth = 'Januari' . 'Februari';
        }

        $dutchdate = $dutchday . ' ' . $dutchmonth . ' ' . explode('-', $date)[0];
        return $dutchdate
    }

So, if $month is 01, $dutchmonth should be Januari. If $month is 02, $dutchmonth should be Februari, and so on.
I have the feeling I'm not doing this right?

Body:
You may do any of these:

if else

if ($month == "01") {
    $dutchmonth = "Januari";
} else if($month == "02"){
    $dutchmonth = "Februari";
}

switch

switch($month) {
    case "01":
        $dutchmonth = "Januari";
        break;
    case "02":
        $dutchmonth = "Februari";
        break;
}

Using array

$month_arr = array('01' => "Januari", '02' => "Februari");
$dutchmonth = $month_arr[$month];

NOTE: To use multiple if conditions use logical operators && or ||


问:
How to idiomatically test for non-null, non-empty strings in Kotlin?
I am new to Kotlin, and I am looking for help in rewriting the following code to be more elegant.

```<code>var s: String? = "abc"
if (s != null && s.isNotEmpty()) {
    // Do something
}
</code>```

If I use the following code:

```<code>if (s?.isNotEmpty()) {
</code>```

The compiler will complain that

```<code>Required: Boolean
Found: Boolean?
</code>```

Thanks.

答: Although I like the answer by @miensol very much, my answer would be (and that is why I do not put it in a comment): if (s != null && s.isNotEmpty()) { … } actually is the idiomatic way in Kotlin. Only this way will you get a smart cast to String inside the block, while with the way in the accepted answer you will have to use s!! inside the block.

Body:
I am new to Kotlin, and I am looking for help in rewriting the following code to be more elegant.

var s: String? = "abc"
if (s != null && s.isNotEmpty()) {
    // Do something
}

If I use the following code:

if (s?.isNotEmpty()) {

The compiler will complain that

Required: Boolean
Found: Boolean?

Thanks.


问:
NoMethodError in ReportsController#import undefined method `original_filename' for "students.xlsx":String
I want to import the student records but when i choose file it shows an error as
NoMethodError in ReportsController#import
undefined methodoriginal_filename' for "students.xlsx":String`

and i tried to debbug this and I got

[1] pry(#<ReportsController>)> Student.import(params[:file])
NoMethodError: undefined methodoriginal_filename' for "import.xlsx":String
from /home/dk/import_multiple/school/app/models/student.rb:283:in open_spreadsheet'

This is my code:

controller

```<code>def importer
  params[:role] == :guardian ? Guardian : Student
end

def import
  importer.import(params[:file])
  redirect_to import_reports_path, notice: "Students imported."
end
</code>```

student.rb

```<code>COLUMNS_TO_STRING = ["batch_id", "class_roll_no","phone1","phone2"]  # and so on
def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
  row = Hash[[header, spreadsheet.row(i)].transpose]
  row = clean_for row, COLUMNS_TO_STRING
  record = Student.find_by(:id => row["id"],:batch_id =>    row["batch_id"],:class_roll_no => row["class_roll_no"],:phone1 =>  row["phone1"],:phone2 => row["phone2"]) || new
  record.attributes = row.to_hash.slice(*row.to_hash.keys)
  record.save!
 end
end
def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path)
  when ".xls" then Roo::Excel.new(file.path)
  when ".xlsx" then Roo::Excelx.new(file.path)
  else raise "Unknown file type: #{file.original_filename}"
  end
 end
</code>```

guardian.rb

```<code>COLUMNS_TO_STRING = ["student_id"] # and so on
def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
  row = Hash[[header, spreadsheet.row(i)].transpose]
  row = clean_for row, COLUMNS_TO_STRING
  guardian = Guardian.find_by(:id => row["id"],:student_id => row["student_id"]) || new
  guardian.attributes = row.to_hash.slice(*row.to_hash.keys)
  guardian.save!
 end
end
def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path)
  when ".xls" then Roo::Excel.new(file.path)
  when ".xlsx" then Roo::Excelx.new(file.path)
  else raise "Unknown file type: #{file.original_filename}"
  end
 end
</code>```

view

```<code><h1>IMPORT</h1>
<div class = "well">
    <p>
        <%= form_tag import_reports_path do %>
        <%= file_field_tag :file%>
        <br>
        <%= submit_tag "Import",class: "btn btn-primary" %>
        <% end %>
    </p>
</div>
</code>```

答:
Your form_tag needs to know that it has a multipart file upload field in it - otherwise it will submit raw data, and not actually upload the file.

```<code>form_tag import_reports_path, multipart: true do
</code>```

Body:
I want to import the student records but when i choose file it shows an error as
NoMethodError in ReportsController#import
undefined methodoriginal_filename' for "students.xlsx":String`

and i tried to debbug this and I got

[1] pry(#<ReportsController>)> Student.import(params[:file])
NoMethodError: undefined methodoriginal_filename' for "import.xlsx":String
from /home/dk/import_multiple/school/app/models/student.rb:283:in open_spreadsheet'

This is my code:

controller

def importer
  params[:role] == :guardian ? Guardian : Student
end

def import
  importer.import(params[:file])
  redirect_to import_reports_path, notice: "Students imported."
end

student.rb

COLUMNS_TO_STRING = ["batch_id", "class_roll_no","phone1","phone2"]  # and so on
def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
  row = Hash[[header, spreadsheet.row(i)].transpose]
  row = clean_for row, COLUMNS_TO_STRING
  record = Student.find_by(:id => row["id"],:batch_id =>    row["batch_id"],:class_roll_no => row["class_roll_no"],:phone1 =>  row["phone1"],:phone2 => row["phone2"]) || new
  record.attributes = row.to_hash.slice(*row.to_hash.keys)
  record.save!
 end
end
def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path)
  when ".xls" then Roo::Excel.new(file.path)
  when ".xlsx" then Roo::Excelx.new(file.path)
  else raise "Unknown file type: #{file.original_filename}"
  end
 end

guardian.rb

COLUMNS_TO_STRING = ["student_id"] # and so on
def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
  row = Hash[[header, spreadsheet.row(i)].transpose]
  row = clean_for row, COLUMNS_TO_STRING
  guardian = Guardian.find_by(:id => row["id"],:student_id => row["student_id"]) || new
  guardian.attributes = row.to_hash.slice(*row.to_hash.keys)
  guardian.save!
 end
end
def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::CSV.new(file.path)
  when ".xls" then Roo::Excel.new(file.path)
  when ".xlsx" then Roo::Excelx.new(file.path)
  else raise "Unknown file type: #{file.original_filename}"
  end
 end

view

IMPORT

        <%= form_tag import_reports_path do %>
        <%= file_field_tag :file%>

        <%= submit_tag "Import",class: "btn btn-primary" %>
        <% end %>

Body:
Your form_tag needs to know that it has a multipart file upload field in it - otherwise it will submit raw data, and not actually upload the file.

form_tag import_reports_path, multipart: true do


问:
Django ignoring DEBUG value when I use os.environ, why?
In my Django settings I have the following:

DEBUG = os.environ['DEBUG_VALUE']

Where DEBUG_VALUE = False

However, Django continues to show full error messages when I do this. If I manual add DEBUG = False it works and shows 500 error.

For some reason Django is ignoring it when I use the os.environ value.

I have confirmed DEBUG_VALUE is False but outputting to a file.

I have even tried:

DEBUG = bool(os.environ['DEBUG_VALUE'])

and still shows full errors.

答:
Maybe you want something more forgiving. First allow the local definition for development purposes. And only if not defined, get it from environment variable, but use the case insensitive comparison (since the person doing the deployment might not be the developer writing this line of code).</p>

```<code>try:
    DEBUG = DEBUG_VALUE_LOCAL
except NameError:
    DEBUG = os.environ.get('DEBUG_VALUE').lower() == 'true'
</code>```

Body:
Maybe you want something more forgiving. First allow the local definition for development purposes. And only if not defined, get it from environment variable, but use the case insensitive comparison (since the person doing the deployment might not be the developer writing this line of code).

try:
    DEBUG = DEBUG_VALUE_LOCAL
except NameError:
    DEBUG = os.environ.get('DEBUG_VALUE').lower() == 'true'