问:
Why std::get does not work with variables?
I am running into a trouble of understanding how functions, especially template functions and local variables behave during the compilation time.

So this code works well with std::get:

```<code>enum class UserInfoFields{name, email, address};

using UserInfo = std::tuple<std::string, std::string, std::string>;

int main()
{
    UserInfo s{"Edmund", "edmund@page.me", "Denver street 19"};
    std::cout << std::get<static_cast<size_t>(UserInfoFields::name)>(s) << std::endl;
    return 0;
}
</code>```

This from my understanding is because std::get is a template function and it requires a template argument to be known during the compilation. That makes sense as static_cast<... gives us the value during the compilation time.

What I do not understand, if I change the main() code to this:

```<code> int main()
{
    UserInfo s{"Edmund", "edmund@page.me", "Denver street 19"};
    auto a = static_cast<size_t>(UserInfoFields::name);
    std::cout << std::get<a>(s) << std::endl;
    return 0;
}
</code>```

This is not allowed. I know that I have to use constexpr but I want to know, why exactly the second code does not work?

答:
You wrote yourself that

std::get is a template function and it requires a template argument to be known during the compilation

The value of a local variable is not (in the general case) known during compilation; a local variable's value is a runtime property. As such, a local variable cannot be used as a template argument.

If you want to use it as one, you have to make it a compile-time value. This is achieved by making it constexpr (as you've also stated in the question).

Body:
I am running into a trouble of understanding how functions, especially template functions and local variables behave during the compilation time.

So this code works well with std::get:

enum class UserInfoFields{name, email, address};

using UserInfo = std::tuple<std::string, std::string, std::string>;

int main()
{
    UserInfo s{"Edmund", "edmund@page.me", "Denver street 19"};
    std::cout << std::get<static_cast<size_t>(UserInfoFields::name)>(s) << std::endl;
    return 0;
}

This from my understanding is because std::get is a template function and it requires a template argument to be known during the compilation. That makes sense as static_cast<... gives us the value during the compilation time.

What I do not understand, if I change the main() code to this:

 int main()
{
    UserInfo s{"Edmund", "edmund@page.me", "Denver street 19"};
    auto a = static_cast<size_t>(UserInfoFields::name);
    std::cout << std::get(s) << std::endl;
    return 0;
}

This is not allowed. I know that I have to use constexpr but I want to know, why exactly the second code does not work?


来源: stackexchange

问:
Hibernate One To Many Relation Hbm Xml Error
I want to create relation between Definition (DEF) and Details (DET) table by foreign keys in Hibernate. In this case, one definition has multiple details.

Definition table has ID column as PK

Details table has ID column as PK and DEFINITION_ID as FK

When I connect these inside of hbm.xml I am getting an error such as;

ERROR

Caused by: org.hibernate.MappingException: Repeated column in mapping
  for entity: com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDet
  column: ID (should be mapped with insert="false" update="false")

DEFINITION HBM XML

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDef"
        table="CMS_EXEMPT_RESTRICT_DEF">
        <tuplizer class="com.ykb.hmn.inf.core.datamodel.IntfEntityTuplizer"
            entity-mode="pojo" />
        <id name="oid" type="java.lang.Long">
            <column name="ID" />
            <generator class="sequence">
                <param name="sequence">SEQ_CMS_EXEMPT_RESTRICT_DEF</param>
            </generator>
        </id>

        .
        .
        .

        <bag name="cmsExemptRestrictDetails" table="CMS_EXEMPT_RESTRICT_DET"
            inverse="true" lazy="true" fetch="select">
            <key>
                <column name="DEFINITION_ID" not-null="true" />
            </key>
            <one-to-many
                class="com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDet" />
        </bag>
    </class>
</hibernate-mapping>
</code>```

DETAIL HBM XML

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDet"
        table="CMS_EXEMPT_RESTRICT_DET">
        <tuplizer class="com.ykb.hmn.inf.core.datamodel.IntfEntityTuplizer"
            entity-mode="pojo" />
        <id name="oid" type="java.lang.Long">
            <column name="ID" />
            <generator class="sequence">
                <param name="sequence">SEQ_CMS_EXEMPT_RESTRICT_DET</param>
            </generator>
        </id>

        <many-to-one name="cmsExemptRestrictDefinition" class="com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDef" fetch="select">
            <column name="ID" not-null="true" />
        </many-to-one>

        <property name="definitionId" type="java.lang.Long">
            <column name="DEFINITION_ID" />
        </property>
    </class>
</hibernate-mapping>
</code>```

First - Do I need to define both many to one and one to many relation in each hbm xmls?

Second - Do I need to rename column ID of Detail something like DETAIL_ID?

Thanks.

答:
The property mapping  Definition_id is incorrect. The foreign key should not be mapped. Remove it and change the column name in manytoone mapping to definition_id:

Change the detail hbm xml to:

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDet"
        table="CMS_EXEMPT_RESTRICT_DET">
        <tuplizer class="com.ykb.hmn.inf.core.datamodel.IntfEntityTuplizer"
            entity-mode="pojo" />
        <id name="oid" type="java.lang.Long">
            <column name="ID" />
            <generator class="sequence">
                <param name="sequence">SEQ_CMS_EXEMPT_RESTRICT_DET</param>
            </generator>
        </id>

        <many-to-one name="cmsExemptRestrictDefinition" class="com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDef" fetch="select">
            <column name="DEFINITION_ID" not-null="true" />
        </many-to-one>

           </class>
</hibernate-mapping>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to create relation between Definition (DEF) and Details (DET) table by foreign keys in Hibernate. In this case, one definition has multiple details.

Definition table has ID column as PK

Details table has ID column as PK and DEFINITION_ID as FK

When I connect these inside of hbm.xml I am getting an error such as;

ERROR

Caused by: org.hibernate.MappingException: Repeated column in mapping
  for entity: com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDet
  column: ID (should be mapped with insert="false" update="false")

DEFINITION HBM XML

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDef"
        table="CMS_EXEMPT_RESTRICT_DEF">
        <tuplizer class="com.ykb.hmn.inf.core.datamodel.IntfEntityTuplizer"
            entity-mode="pojo" />
        <id name="oid" type="java.lang.Long">
            <column name="ID" />
            <generator class="sequence">
                <param name="sequence">SEQ_CMS_EXEMPT_RESTRICT_DEF</param>
            </generator>
        </id>

        .
        .
        .

        <bag name="cmsExemptRestrictDetails" table="CMS_EXEMPT_RESTRICT_DET"
            inverse="true" lazy="true" fetch="select">
            <key>
                <column name="DEFINITION_ID" not-null="true" />
            </key>
            <one-to-many
                class="com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDet" />
        </bag>
    </class>
</hibernate-mapping>

DETAIL HBM XML

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDet"
        table="CMS_EXEMPT_RESTRICT_DET">
        <tuplizer class="com.ykb.hmn.inf.core.datamodel.IntfEntityTuplizer"
            entity-mode="pojo" />
        <id name="oid" type="java.lang.Long">
            <column name="ID" />
            <generator class="sequence">
                <param name="sequence">SEQ_CMS_EXEMPT_RESTRICT_DET</param>
            </generator>
        </id>

        <many-to-one name="cmsExemptRestrictDefinition" class="com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDef" fetch="select">
            <column name="ID" not-null="true" />
        </many-to-one>

        <property name="definitionId" type="java.lang.Long">
            <column name="DEFINITION_ID" />
        </property>
    </class>
</hibernate-mapping>

First - Do I need to define both many to one and one to many relation in each hbm xmls?

Second - Do I need to rename column ID of Detail something like DETAIL_ID?

Thanks.

Body:
The property mapping  Definition_id is incorrect. The foreign key should not be mapped. Remove it and change the column name in manytoone mapping to definition_id:

Change the detail hbm xml to:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDet"
        table="CMS_EXEMPT_RESTRICT_DET">
        <tuplizer class="com.ykb.hmn.inf.core.datamodel.IntfEntityTuplizer"
            entity-mode="pojo" />
        <id name="oid" type="java.lang.Long">
            <column name="ID" />
            <generator class="sequence">
                <param name="sequence">SEQ_CMS_EXEMPT_RESTRICT_DET</param>
            </generator>
        </id>

        <many-to-one name="cmsExemptRestrictDefinition" class="com.ykb.hmn.cms.commission.datamodel.ICmsExemptRestrictDef" fetch="select">
            <column name="DEFINITION_ID" not-null="true" />
        </many-to-one>

           </class>
</hibernate-mapping>


问:
Laravel, how can I show the name field via foreign key
I have the User model and Consulta model, the consulta model have foreign key 'user_id' references id on user.

sorry for my English.

I need to show on user_id the user name in my list

Model  User

```<code>public function consultas()
{
    return $this->hasMany('App\Consulta','user_id');
}
</code>```

Model Consulta

```<code>public function usuarios()
{
return $this->hasMany('User');
}
</code>```

Controller, only '$registros' it works

```<code>$userteste = User::with('consultas')->get();
$registros = Consulta::all();
return view('consultas.index' , compact('registros','userteste'));
</code>```

And view

```<code><table>
<thead>
<tr>
<th>Nome</th>
<th>Data</th>
<th>Hora</th>
<th>Situação</th>
<th>Ação</th>
</tr>
</thead>
<tbody>
@foreach($registros as $registro)
@can('ver-consulta', $registro)
<tr>
<td>{{$registro -> user_id}} </td>
<td>{{$registro -> data}} </td>
<td>{{$registro -> hora}}</td>
<td>{{$registro -> situacao}} </td>
<td>
<a class="btn teal" href="/consultas/editar/{{$registro->id}}">
<i class="material-icons">local_printshop</i>
</a>
</td>
</tr>
@endcan
@endforeach
</tbody>
</table>
</code>```

I need in 'user_id' show the 'name' on table user, not number off id.
sorry for my English

```<code>in this case the results
nome = 1
I need in 'Nome' the name of user:
nome = luiz
</code>```

答:
User Model

```<code>public function consultas()
 {
    return $this->hasMany('App\Consulta');
 }
</code>```

Model Consulta

```<code>public function user()
  {
     return $this->belongsTo('App\User','user_id');
  }
</code>```

Controller

```<code>$registros = Consulta::all();
</code>```

View

```<code>@foreach(registros as registro)
  <tr>
    <td>{{ $registro->user->name }}</td>
  </tr>
@endforeach
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the User model and Consulta model, the consulta model have foreign key 'user_id' references id on user.

sorry for my English.

I need to show on user_id the user name in my list

Model  User

public function consultas()
{
    return $this->hasMany('App\Consulta','user_id');
}

Model Consulta

public function usuarios()
{
return $this->hasMany('User');
}

Controller, only '$registros' it works

$userteste = User::with('consultas')->get();
$registros = Consulta::all();
return view('consultas.index' , compact('registros','userteste'));

And view

Nome
Data
Hora
Situação
Ação

@foreach($registros as $registro)
@can('ver-consulta', $registro)

{{$registro -> user_id}}
{{$registro -> data}}
{{$registro -> hora}}
{{$registro -> situacao}}

id}}">
local_printshop

@endcan
@endforeach

I need in 'user_id' show the 'name' on table user, not number off id.
sorry for my English

in this case the results
nome = 1
I need in 'Nome' the name of user:
nome = luiz

Body:
User Model

public function consultas()
 {
    return $this->hasMany('App\Consulta');
 }

Model Consulta

public function user()
  {
     return $this->belongsTo('App\User','user_id');
  }

Controller

$registros = Consulta::all();

View

@foreach(registros as registro)
  <tr>
    <td>{{ $registro->user->name }}</td>
  </tr>
@endforeach


问:
additional text display when form field is clicked - react
i'm making a form in react and currently when the field is clicked it adds a blue border (which i would like to keep) but i would like some additional text to appear underneath, and i'm not sure how to do this?

basically, i have a field for first name and when its clicked i'd like "Enter your first name" to appear underneath this field.

here's what i currently have:

```<code><div className="form-group form-row">
    <label
       id="firstNameLabel"
       className="col-md-2 col-form-label text-md-right"
       htmlFor="firstName1"
       readOnly
    >
      First Name*
    </label>
    <div className="col-md-10">
         <input
         type="text"
         className="form-control"
         name="firstName1"
         ref="firstName1"
         placeholder="First Name"
         value={this.state.firstName1}
         onChange={this.handleChange}
         required
     />
     <div className="error" id="firstnameError" />
   </div>
 </div>
</code>```

答:
You could use the onFocus and onBlur events to achieve that, here is an example:

```<code><input
  onFocus={() => this.setState({inputFocused: true})}
  onBlur={() => this.setState({inputFocused: false})}
\>
{this.state.inputFocused && <div>Some message</div>}
</code>```

Body:
i'm making a form in react and currently when the field is clicked it adds a blue border (which i would like to keep) but i would like some additional text to appear underneath, and i'm not sure how to do this?

basically, i have a field for first name and when its clicked i'd like "Enter your first name" to appear underneath this field.

here's what i currently have:

      First Name*

         <input
         type="text"
         className="form-control"
         name="firstName1"
         ref="firstName1"
         placeholder="First Name"
         value={this.state.firstName1}
         onChange={this.handleChange}
         required
     />

Body:
You could use the onFocus and onBlur events to achieve that, here is an example:

<input
  onFocus={() => this.setState({inputFocused: true})}
  onBlur={() => this.setState({inputFocused: false})}
\>
{this.state.inputFocused && <div>Some message</div>}


问:
Swift: my destinationVC segue is showing nil
I'm having users fill out some profile information via texts fields (name, email, etc.), which is used to set my ProfileContoller.shared.profile values. When I get to my navigation segue to pass the data over, my destinationVC.profile will not set its value to the sending profile object and I get nil instead.

My sendingVC is embedded in a navigation controller, while my destinationVC is embedded in Tab Bar Controller.

Segue SendingVC

Attributes Inspector SendingVC

DestinationVC

```<code>// Sending View Controller:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let profile = ProfileController.shared.profile else { return }
    if segue.identifier == "signUpMemicTBC" {
        let destinationVC = segue.destination as? ProfileViewController
        destinationVC?.profile = profile

// Receiving ProfileViewController:
class ProfileViewController: UIViewController {

    // MARK: - IBOutlets
    @IBOutlet weak var fullNameLabel: UILabel!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!

    // MARK: - Landing Pad
    var profile : Profile? {
        didSet {
            updateViews()
        }
    }

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

    func updateViews () {
        guard let profile = profile else { return }
        fullNameLabel.text = profile.firstName + " " + profile.lastName
        usernameLabel.text = profile.username
        emailLabel.text = profile.email
    }
}

// ProfileController:
class ProfileController {

    // MARK: - Properties
    var profile : Profile?

    // MARK: - Singleton
    static let shared = ProfileController()

}
</code>```

My sending object has data:
    (lldb) po profile
    Profile: 0x600000c873c0

The destination object is unexpectedly nil:
    (lldb) po destinationVC?.profile
    nil

答:
I think all you have to do is call the updateViews() in the main thread.

```<code>didSet {
        print("did set profile called")
        DispatchQueue.main.async{[weak self] in
            guard let self = self else {
                return
            }
            self.updateViews()
        }
    }
</code>```

Another option would be to update the views in viewDidLoad()

```<code>override func viewDidLoad() {
    if let prof = self.profile {
        self.updateViews()
    }
}
</code>```

Body:
I'm having users fill out some profile information via texts fields (name, email, etc.), which is used to set my ProfileContoller.shared.profile values. When I get to my navigation segue to pass the data over, my destinationVC.profile will not set its value to the sending profile object and I get nil instead.

My sendingVC is embedded in a navigation controller, while my destinationVC is embedded in Tab Bar Controller.

Segue SendingVC

Attributes Inspector SendingVC

DestinationVC

// Sending View Controller:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let profile = ProfileController.shared.profile else { return }
    if segue.identifier == "signUpMemicTBC" {
        let destinationVC = segue.destination as? ProfileViewController
        destinationVC?.profile = profile

// Receiving ProfileViewController:
class ProfileViewController: UIViewController {

    // MARK: - IBOutlets
    @IBOutlet weak var fullNameLabel: UILabel!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!

    // MARK: - Landing Pad
    var profile : Profile? {
        didSet {
            updateViews()
        }
    }

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

    func updateViews () {
        guard let profile = profile else { return }
        fullNameLabel.text = profile.firstName + " " + profile.lastName
        usernameLabel.text = profile.username
        emailLabel.text = profile.email
    }
}

// ProfileController:
class ProfileController {

    // MARK: - Properties
    var profile : Profile?

    // MARK: - Singleton
    static let shared = ProfileController()

}

My sending object has data:
    (lldb) po profile
    Profile: 0x600000c873c0

The destination object is unexpectedly nil:
    (lldb) po destinationVC?.profile
    nil

Body:
I think all you have to do is call the updateViews() in the main thread.

didSet {
        print("did set profile called")
        DispatchQueue.main.async{[weak self] in
            guard let self = self else {
                return
            }
            self.updateViews()
        }
    }

Another option would be to update the views in viewDidLoad()

override func viewDidLoad() {
    if let prof = self.profile {
        self.updateViews()
    }
}


问:
How to add array of object to an entry of odata array
I want to add a array of objects to a specific entry of an odata array.
It is a JSON-Model in sapui5 and I wanted to do oModel.getData()[j].setProperty(""), but this does not. Can anyone help?

I have:

```<code>    [{
            attributes: (5) [{…}, {…}, {…}, {…}, {…}]
            creationDate: "2019-05-20T09:14:16.622Z"
            deleted: false
            eventDate: "20.05.19"
            message: "Aufgabe xyz"
            object: "Aufgabe"
    },
{
            attributes: (5) [{…}, {…}, {…}, {…}, {…}]
            creationDate: "2019-05-20T09:14:16.622Z"
            deleted: false
            eventDate: "21.05.19"
            message: "Aufgabe"
            object: "Aufgabe"    }
]
</code>```

And I want to add a new Item:

```<code>[{
        description: "Ereignisgruppe"
        key: "objectGroup"
        value: "Aufgaben"
    },{
        description: "Ereignis"
        key: "object"
        value: "Aufgabe"
   }]
</code>```

To get this:

```<code> [{
                attributes: (5) [{…}, {…}, {…}, {…}, {…}]
                creationDate: "2019-05-20T09:14:16.622Z"
                deleted: false
                eventDate: "20.05.19"
                message: "Aufgabe xyz"
                object: "Aufgabe",
                masterAttributes: (2) [{…}, {…}]        <-------------- new
        },
    {
                attributes: (5) [{…}, {…}, {…}, {…}, {…}]
                creationDate: "2019-05-20T09:14:16.622Z"
                deleted: false
                eventDate: "21.05.19"
                message: "Aufgabe"
                object: "Aufgabe"
   }]
</code>```

Best regards!

答:
Your json is missing the comma behind every attribute.

You can then add the 'masterAttributes' like:

```<code>oModel[0].masterAttributes = masterAttributes;
</code>```

check this fiddle:

     var oModel= [{
                attributes: [],
                creationDate: "2019-05-20T09:14:16.622Z",
                deleted: false,
                eventDate: "20.05.19"  ,
                message: "Aufgabe xyz",
                object: "Aufgabe"
        },
    {
                attributes: [],
                creationDate: "2019-05-20T09:14:16.622Z",
                deleted: false,
                eventDate: "21.05.19",
                message: "Aufgabe",
                object: "Aufgabe"    }
    ];

    var masterAttributes = [{
        description: "Ereignisgruppe",
        key: "objectGroup",
        value: "Aufgaben"
    },{
        description: "Ereignis",
        key: "object",
        value: "Aufgabe",
   }];

   // add the other array
   oModel[0].masterAttributes = masterAttributes;

   console.log("oModel after adding masterAttributes ");
   console.log(oModel);```

Body:
I want to add a array of objects to a specific entry of an odata array.
It is a JSON-Model in sapui5 and I wanted to do oModel.getData()[j].setProperty(""), but this does not. Can anyone help?

I have:

    [{
            attributes: (5) [{…}, {…}, {…}, {…}, {…}]
            creationDate: "2019-05-20T09:14:16.622Z"
            deleted: false
            eventDate: "20.05.19"
            message: "Aufgabe xyz"
            object: "Aufgabe"
    },
{
            attributes: (5) [{…}, {…}, {…}, {…}, {…}]
            creationDate: "2019-05-20T09:14:16.622Z"
            deleted: false
            eventDate: "21.05.19"
            message: "Aufgabe"
            object: "Aufgabe"    }
]

And I want to add a new Item:

[{
        description: "Ereignisgruppe"
        key: "objectGroup"
        value: "Aufgaben"
    },{
        description: "Ereignis"
        key: "object"
        value: "Aufgabe"
   }]

To get this:

 [{
                attributes: (5) [{…}, {…}, {…}, {…}, {…}]
                creationDate: "2019-05-20T09:14:16.622Z"
                deleted: false
                eventDate: "20.05.19"
                message: "Aufgabe xyz"
                object: "Aufgabe",
                masterAttributes: (2) [{…}, {…}]        <-------------- new
        },
    {
                attributes: (5) [{…}, {…}, {…}, {…}, {…}]
                creationDate: "2019-05-20T09:14:16.622Z"
                deleted: false
                eventDate: "21.05.19"
                message: "Aufgabe"
                object: "Aufgabe"
   }]

Best regards!

Body:
Your json is missing the comma behind every attribute.

You can then add the 'masterAttributes' like:

oModel[0].masterAttributes = masterAttributes;

check this fiddle:

     var oModel= [{
                attributes: [],
                creationDate: "2019-05-20T09:14:16.622Z",
                deleted: false,
                eventDate: "20.05.19"  ,
                message: "Aufgabe xyz",
                object: "Aufgabe"
        },
    {
                attributes: [],
                creationDate: "2019-05-20T09:14:16.622Z",
                deleted: false,
                eventDate: "21.05.19",
                message: "Aufgabe",
                object: "Aufgabe"    }
    ];

    var masterAttributes = [{
        description: "Ereignisgruppe",
        key: "objectGroup",
        value: "Aufgaben"
    },{
        description: "Ereignis",
        key: "object",
        value: "Aufgabe",
   }];

   // add the other array
   oModel[0].masterAttributes = masterAttributes;

   console.log("oModel after adding masterAttributes ");
   console.log(oModel);


问:
How change a iframe content?

Possible Duplicate:

  How to change style of iframe content cross-domain?

Hi everybody.

Is it possible to change an iframe content if it comes from another site?
e.g.

```<code><html>
<head></head>
 <body>
  <iframe src="http://www.google.com"></iframe>
 </body>
</html>
</code>```

Thanks.

答: Not what you're going to want to hear but... No...  You can't even use JavaScript to alter the contents of the iFrame if you do not have control over the domain and can access the files in your example Google.com.</p>

Title: How change a iframe content?

Body:
Possible Duplicate:

  How to change style of iframe content cross-domain?

Hi everybody.

Is it possible to change an iframe content if it comes from another site?
e.g.

Thanks.


问:
For loop and if for multiple conditions and change another column in the same row in pandas
I am trying to have a change a column if some strings are in the other column in the same row. I am new to Pandas.

I need to change the price of some oranges to 200 but not the price of 'Red Orange'. I cannot change the name of the "fruits". It is a much longer string and I just made it shorter for convenience here.

```<code>    fruits                         price
    Green apple from us            10
    Orange Apple from US           11
    Mango from Canada              15
    Blue Orange from Mexico        16
    Red Orange from Costa          15
    Pink Orange from Brazil        19
    Yellow Pear from Guatemala     32
    Black Melon from Guatemala     4
    Purple orange from Honduras    5
</code>```

so that the final result would be

```<code>    fruits                         price
    Green apple from us            10
    Orange Apple from US           11
    Mango from Canada              15
    Blue Orange from Mexico        200
    Red Orange from Costa          15
    Pink Orange from Brazil        200
    Yellow Pear from Guatemala     32
    Black Melon from Guatemala     4
    Purple orange from Honduras    5
</code>```

I tried

```<code>    df.loc[df['fruits'].str.lower().str.contains('orange'), 'price'] = 200
</code>```

But this produces total of 4 items to change its price instead of only 2 items.

I have used for loop once and that changed the entire column to change its price.

答:
You can use regex:

```<code>import re

df.loc[df['fruits'].str.lower().str.contains(r'(?<!red) orange', regex = True), 'price'] = 200
</code>```

(?<!red) is a negative look behind. So if behind orange is red it wont match it. It also ensure its the second word with the mandatory space before the word orange, so you wont have to worry about it been the color describing something.

Body:
I am trying to have a change a column if some strings are in the other column in the same row. I am new to Pandas.

I need to change the price of some oranges to 200 but not the price of 'Red Orange'. I cannot change the name of the "fruits". It is a much longer string and I just made it shorter for convenience here.

    fruits                         price
    Green apple from us            10
    Orange Apple from US           11
    Mango from Canada              15
    Blue Orange from Mexico        16
    Red Orange from Costa          15
    Pink Orange from Brazil        19
    Yellow Pear from Guatemala     32
    Black Melon from Guatemala     4
    Purple orange from Honduras    5

so that the final result would be

    fruits                         price
    Green apple from us            10
    Orange Apple from US           11
    Mango from Canada              15
    Blue Orange from Mexico        200
    Red Orange from Costa          15
    Pink Orange from Brazil        200
    Yellow Pear from Guatemala     32
    Black Melon from Guatemala     4
    Purple orange from Honduras    5

I tried

    df.loc[df['fruits'].str.lower().str.contains('orange'), 'price'] = 200

But this produces total of 4 items to change its price instead of only 2 items.

I have used for loop once and that changed the entire column to change its price.

Body:
You can use regex:

import re

df.loc[df['fruits'].str.lower().str.contains(r'(?<!red) orange', regex = True), 'price'] = 200

(?<!red) is a negative look behind. So if behind orange is red it wont match it. It also ensure its the second word with the mandatory space before the word orange, so you wont have to worry about it been the color describing something.


问:
How to Skip 500 Internal Server Error and Continue Webscraping using BeautifulSoup?
I am Doing Webscraping using Python BeautifulSoup.

Getting an Error 'HTTP Error 500: Internal Server Error'.

Below is My Code

```<code>import requests
from bs4 import BeautifulSoup
import pdb
from urllib.request import urlopen
import csv
from urllib.error import HTTPError

for IPRD_ID in range(1,10):
   url = 'https://ipr.etsi.org/IPRDetails.aspx?IPRD_ID={}&IPRD_TYPE_ID=2&MODE=2'.format(IPRD_ID)
   page = urlopen(url)
   soup = BeautifulSoup(page, "lxml")
   table = soup.findAll('table', style="width:100%")
   try:
      for tr in table:
          a = (tr.get_text())
   except:
      print('exe')
</code>```

As we have seen I am doing Using range function which Starts from 1 to 10.I checked code step by step.At IPRD_ID=3 page server error is there no data.So its creating 500 Internal Errorenter image description here

As we have seen no data so its coming error
     enter image description here

HTTP Error 500: Internal Server Error
we have seen one IPRD_ID=3 which is having error,If i give more range 1 to 100 may have more error pages.So,I want help that how to skip like this pages and move forward for webscraping

答:
Try catching the error code and continue if it encounters an error</p>

```<code>for IPRD_ID in range(1,10):
    url = 'https://ipr.etsi.org/IPRDetails.aspx?IPRD_ID={}&IPRD_TYPE_ID=2&MODE=2'.format(IPRD_ID)
    try:
        page = urlopen(url)
        soup = BeautifulSoup(page, "lxml")
        table = soup.findAll('table', style="width:100%")
        for tr in table:
            a = (tr.get_text())

    except  HTTPError, err:
        if err.code == 500:
            print ("Internal server error 500")
        else:
            print ("Some other error. Error code: ", err.code)
</code>```

Body:
I am Doing Webscraping using Python BeautifulSoup.

Getting an Error 'HTTP Error 500: Internal Server Error'.

Below is My Code

import requests
from bs4 import BeautifulSoup
import pdb
from urllib.request import urlopen
import csv
from urllib.error import HTTPError

for IPRD_ID in range(1,10):
   url = 'https://ipr.etsi.org/IPRDetails.aspx?IPRD_ID={}&IPRD_TYPE_ID=2&MODE=2'.format(IPRD_ID)
   page = urlopen(url)
   soup = BeautifulSoup(page, "lxml")
   table = soup.findAll('table', style="width:100%")
   try:
      for tr in table:
          a = (tr.get_text())
   except:
      print('exe')

As we have seen I am doing Using range function which Starts from 1 to 10.I checked code step by step.At IPRD_ID=3 page server error is there no data.So its creating 500 Internal Errorenter image description here

As we have seen no data so its coming error
     enter image description here

HTTP Error 500: Internal Server Error
we have seen one IPRD_ID=3 which is having error,If i give more range 1 to 100 may have more error pages.So,I want help that how to skip like this pages and move forward for webscraping

Body:
Try catching the error code and continue if it encounters an error

for IPRD_ID in range(1,10):
    url = 'https://ipr.etsi.org/IPRDetails.aspx?IPRD_ID={}&IPRD_TYPE_ID=2&MODE=2'.format(IPRD_ID)
    try:
        page = urlopen(url)
        soup = BeautifulSoup(page, "lxml")
        table = soup.findAll('table', style="width:100%")
        for tr in table:
            a = (tr.get_text())

    except  HTTPError, err:
        if err.code == 500:
            print ("Internal server error 500")
        else:
            print ("Some other error. Error code: ", err.code)


问:
Reassign Pandas DataFrame column values
I have a csv that has incorrect datetime formatting. I've worked out how to convert those values into the format I need, but now I need to reassign all the values in a column to the new, converted values.

For example, I'm hoping that there's something I can put into the following FOR loop that will insert the values back into the dataframe at the correct location:

```<code>for i in df[df.columns[1]]:
    t = pd.Timestamp(i)
    short_date = t.date().strftime('%m/%d/%Y').lstrip('0')
    # Insert back into dataframe?
</code>```

As always, your help is very much appreciated!

Part of the column in question:
Part of the dataframe in question:

```<code>Created Date
2019-02-27 22:55:16
2019-01-29 22:57:12
2018-11-29 00:13:31
2019-01-30 21:35:15
2018-12-20 21:14:45
2018-11-01 16:20:15
2019-04-11 16:38:07
2019-01-24 00:23:17
2018-12-21 19:30:10
2018-12-19 22:33:04
2018-11-07 19:54:19
2019-05-10 21:15:00
</code>```

答:
Thank you all for your help. All of the answers were helpful, but the answer I ended up using was as follows:</p>

```<code>import pandas as pd

df[df.columns[0]] = pd.to_datetime(df[df.columns[0]]).dt.strftime('%m/%d/%Y')
</code>```

Title: Reassign Pandas DataFrame column values

Body:
I have a csv that has incorrect datetime formatting. I've worked out how to convert those values into the format I need, but now I need to reassign all the values in a column to the new, converted values.

For example, I'm hoping that there's something I can put into the following FOR loop that will insert the values back into the dataframe at the correct location:

for i in df[df.columns[1]]:
    t = pd.Timestamp(i)
    short_date = t.date().strftime('%m/%d/%Y').lstrip('0')
    # Insert back into dataframe?

As always, your help is very much appreciated!

Part of the column in question:
Part of the dataframe in question:

Created Date
2019-02-27 22:55:16
2019-01-29 22:57:12
2018-11-29 00:13:31
2019-01-30 21:35:15
2018-12-20 21:14:45
2018-11-01 16:20:15
2019-04-11 16:38:07
2019-01-24 00:23:17
2018-12-21 19:30:10
2018-12-19 22:33:04
2018-11-07 19:54:19
2019-05-10 21:15:00

Body:
Thank you all for your help. All of the answers were helpful, but the answer I ended up using was as follows:

import pandas as pd

df[df.columns[0]] = pd.to_datetime(df[df.columns[0]]).dt.strftime('%m/%d/%Y')


问:
why is mySQL missing a column?
This statement is not populating the image_path column. I have copied and pasted column names from phpMyAdmin to ensure accuracy.</p>

```<code>INSERT INTO (theme_name, theme_path, image_path)
VALUES ('',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/themes/Original/',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/thumbnails/original.png')
</code>```

答:
You've forgotten to name a table to INSERT into:</p>

```<code>INSERT INTO my_table (theme_name, theme_path, image_path)
</code>```

Title: why is mySQL missing a column?

Body:
This statement is not populating the image_path column. I have copied and pasted column names from phpMyAdmin to ensure accuracy.

INSERT INTO (theme_name, theme_path, image_path)
VALUES ('',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/themes/Original/',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/thumbnails/original.png')

Body:
You've forgotten to name a table to INSERT into:

INSERT INTO my_table (theme_name, theme_path, image_path)


答:
This is not a formal explanation, but rather a (hopefully) easy to understand rationale.

As C++ is a strongly typed language, the return type of std::get has to be known to compiler at compile time. But different versions of std::get would return different types - because there could be different types in the tuple at different indexes.

Because of that, value to the template argument of std::get needs to come from somewhere which is known to compiler at compile time. constexpr variable is something which has a value known to compiler, as well as, for example, const variables initialized with constant expressions. But simple non-const integral variable, even when initialized at definition, is not.

Title: Why std::get does not work with variables?

Body:
I am running into a trouble of understanding how functions, especially template functions and local variables behave during the compilation time.

So this code works well with std::get:

enum class UserInfoFields{name, email, address};

using UserInfo = std::tuple<std::string, std::string, std::string>;

int main()
{
    UserInfo s{"Edmund", "edmund@page.me", "Denver street 19"};
    std::cout << std::get<static_cast<size_t>(UserInfoFields::name)>(s) << std::endl;
    return 0;
}

This from my understanding is because std::get is a template function and it requires a template argument to be known during the compilation. That makes sense as static_cast<... gives us the value during the compilation time.

What I do not understand, if I change the main() code to this:

 int main()
{
    UserInfo s{"Edmund", "edmund@page.me", "Denver street 19"};
    auto a = static_cast<size_t>(UserInfoFields::name);
    std::cout << std::get(s) << std::endl;
    return 0;
}

This is not allowed. I know that I have to use constexpr but I want to know, why exactly the second code does not work?


问:
How can I get the bytes of a GetObjectResponse from S3?
I'm retrieving a file from Amazon S3. I want to convert the file to bytes so that I can download it as follows:

```<code>var download = new FileContentResult(bytes, "application/pdf");
download.FileDownloadName = filename;
return download;
</code>```

I have the file here:

```<code>var client = Amazon.AWSClientFactory.CreateAmazonS3Client(
        accessKey,
        secretKey,
        config
        );
GetObjectRequest request = new GetObjectRequest();
GetObjectResponse response = client.GetObject(request);
</code>```

I know about  response.WriteResponseStreamToFile() but I want to download the file to the regular downloads folder. If I convert the GetObjectResponse to bytes, I can return the file. How can I do this?

答:
Stream now has asynchronous methods. In C# 8, you can do this:

```<code>public async Task<byte[]> GetAttachmentAsync(string objectPointer)
{
    var objReq = new GetObjectRequest
    {
        BucketName = "bucket-name",
        Key = objectPointer,    // the file name
    };

    using var objResp = await _s3Client.GetObjectAsync(objReq);
    using var ms = new MemoryStream();
    await objResp.ResponseStream.CopyToAsync(ms, _ct);  // _ct is a CancellationToken
    return ms.ToArray();
}
</code>```

This won't block any threads while the IO occurs.

Body:
I'm retrieving a file from Amazon S3. I want to convert the file to bytes so that I can download it as follows:

var download = new FileContentResult(bytes, "application/pdf");
download.FileDownloadName = filename;
return download;

I have the file here:

var client = Amazon.AWSClientFactory.CreateAmazonS3Client(
        accessKey,
        secretKey,
        config
        );
GetObjectRequest request = new GetObjectRequest();
GetObjectResponse response = client.GetObject(request);

I know about  response.WriteResponseStreamToFile() but I want to download the file to the regular downloads folder. If I convert the GetObjectResponse to bytes, I can return the file. How can I do this?

Body:
Stream now has asynchronous methods. In C# 8, you can do this:

public async Task<byte[]> GetAttachmentAsync(string objectPointer)
{
    var objReq = new GetObjectRequest
    {
        BucketName = "bucket-name",
        Key = objectPointer,    // the file name
    };

    using var objResp = await _s3Client.GetObjectAsync(objReq);
    using var ms = new MemoryStream();
    await objResp.ResponseStream.CopyToAsync(ms, _ct);  // _ct is a CancellationToken
    return ms.ToArray();
}

This won't block any threads while the IO occurs.


问:
How to handle error code -43 from NSOSStatusErrorDomain when initializing AVAudioPlayer Object?
I observed strange behavior while working with AVAudioPlayer

Following is the code:

```<code>AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@",fileName]] error: &error];
</code>```

In this, I downloaded the file from server and stored in application's Cache directory.

I am getting following error:

```<code>Error in playing =
Domain = NSOSStatusErrorDomain
Code = -43
Description = Error Domain=NSOSStatusErrorDomain Code=-43 "The operation couldn’t be completed. (OSStatus error -43.)"
</code>```

I also verified that file is present at that location.
Everytime I restart my application, I was getting same error for song play.
After some time, when I tried to run same code, my player just works fine without any error.

Can anyone tell me how to handle this error?

Also, Can anyone explain me what was the problem?

答:
I had the same error and it appeared to be that the URL was  nil.
Try to check if your URL object is != nil.
Maybe your path is wrong.</p>

Body:
I observed strange behavior while working with AVAudioPlayer

Following is the code:

AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@",fileName]] error: &error];

In this, I downloaded the file from server and stored in application's Cache directory.

I am getting following error:

Error in playing =
Domain = NSOSStatusErrorDomain
Code = -43
Description = Error Domain=NSOSStatusErrorDomain Code=-43 "The operation couldn’t be completed. (OSStatus error -43.)"

I also verified that file is present at that location.
Everytime I restart my application, I was getting same error for song play.
After some time, when I tried to run same code, my player just works fine without any error.

Can anyone tell me how to handle this error?

Also, Can anyone explain me what was the problem?


问:
How can I convert this Unity code to MonoGame code?
I don't know how to use PlayFab in a MonoGame project. I have read some PlayFab tutorials, but they are all for Unity and I think that it's not possible to use the Unity code samples with MonoGame, because I always get error messages.

From this line of code.

```<code>PlayFabClientAPI.GetUserInventoryAsync(new GetUserInventoryRequest(), OnGetUserInventoryRequest, OnPlayFabInventoryError);
</code>```

I get the error messages here:

Error CS1503: Argument 2: cannot convert from 'method group' to
  'object'

Error CS1503: Argument 3: cannot convert from 'method group' to
  'Dictionary'

Something is wrong with "OnGetUserInventoryRequest, OnPlayFabInventoryError", but I don't know what I could change.

What can I change so that this code works with MonoGame?

https://api.playfab.com/documentation/client/method/GetUserInventory

Sample Code

```<code>public void GetInventoryList()
{
    PlayFabClientAPI.GetUserInventoryAsync(new GetUserInventoryRequest(), OnGetUserInventoryRequest, OnPlayFabInventoryError);
}
public void OnGetUserInventoryRequest(GetUserInventoryResult result)
{
    Console.WriteLine(result.VirtualCurrency);
}

public void OnPlayFabInventoryError(PlayFabError result)
{
    Console.WriteLine("Error");
}
</code>```

EDIT:

I get a new error message if I want to use the value of VirtualCurrency. I don't know how to get the value of VirtualCurrency, what am I doing wrong?

```<code>private async Task GetInventoryList()
{
    var result = await PlayFabClientAPI.GetUserInventoryAsync(new GetUserInventoryRequest());

    int CurrentAmount = result.Result.VirtualCurrency;
}
</code>```

Error CS0029: Cannot implicitly convert type
  'System.Collections.Generic.Dictionary' to 'int'

答:
it's pretty obvious if you look at the method signature:

```<code>GetUserInventoryAsync(GetUserInventoryRequest request, object customData = null, Dictionary<string,string> extraHeaders = null)
</code>```

the last 2 parameters are optional, and they are not callback methods

Body:
I don't know how to use PlayFab in a MonoGame project. I have read some PlayFab tutorials, but they are all for Unity and I think that it's not possible to use the Unity code samples with MonoGame, because I always get error messages.

From this line of code.

PlayFabClientAPI.GetUserInventoryAsync(new GetUserInventoryRequest(), OnGetUserInventoryRequest, OnPlayFabInventoryError);

I get the error messages here:

Error CS1503: Argument 2: cannot convert from 'method group' to
  'object'

Error CS1503: Argument 3: cannot convert from 'method group' to
  'Dictionary'

Something is wrong with "OnGetUserInventoryRequest, OnPlayFabInventoryError", but I don't know what I could change.

What can I change so that this code works with MonoGame?

https://api.playfab.com/documentation/client/method/GetUserInventory

Sample Code

public void GetInventoryList()
{
    PlayFabClientAPI.GetUserInventoryAsync(new GetUserInventoryRequest(), OnGetUserInventoryRequest, OnPlayFabInventoryError);
}
public void OnGetUserInventoryRequest(GetUserInventoryResult result)
{
    Console.WriteLine(result.VirtualCurrency);
}

public void OnPlayFabInventoryError(PlayFabError result)
{
    Console.WriteLine("Error");
}

EDIT:

I get a new error message if I want to use the value of VirtualCurrency. I don't know how to get the value of VirtualCurrency, what am I doing wrong?

private async Task GetInventoryList()
{
    var result = await PlayFabClientAPI.GetUserInventoryAsync(new GetUserInventoryRequest());

    int CurrentAmount = result.Result.VirtualCurrency;
}

Error CS0029: Cannot implicitly convert type
  'System.Collections.Generic.Dictionary' to 'int'

Body:
it's pretty obvious if you look at the method signature:

GetUserInventoryAsync(GetUserInventoryRequest request, object customData = null, Dictionary<string,string> extraHeaders = null)

the last 2 parameters are optional, and they are not callback methods


问:
How to add types to a curried function in TypeScript?
In the following snippet of code where I have declared a curried add method.

const add = (a: number) => {
  return (b?: number) => {
    return (b === undefined ? a : add(a + b))
  }
}
```

<p>This works fine if I call this with the following arguments:
<code>add(1)()</code></p>

<p>But typescript throws the following error when I call it like this:
<code>add(1)(2)()</code></p>

```Cannot invoke an expression whose type lacks a call signature. Type 'number | ((b?: number) => number | ...)' has no compatible call signatures.
```

What do I need to add to enable typed usage of this method?

答:
I would describe the type of add() as the following Add type:

```<code>type Add = (a: number) => Add2;
type Add2 = ((b: number) => Add2) & (() => number);
</code>```

The Add function type takes a number and returns an Add2.

The Add2 function type is an overloaded function which returns a different type depending on the number and type of arguments that come in.  It's also self-referential: if you call an Add2 with a number parameter, you get an Add2 out.

You more or less need to use assertions to convince the compiler that your add() is a valid Add:

```<code>const add = ((a: number) => (b?: number) =>
  b === undefined ? a : add(a + b)) as Add;
</code>```

And then you should be able to use it as expected:

```<code>const x = add(1)(2)(3)(); // number
console.log(x); // 6
</code>```

Link to code

Okay, hope that helps; good luck!

Body:
In the following snippet of code where I have declared a curried add method.

const add = (a: number) => {
  return (b?: number) => {
    return (b === undefined ? a : add(a + b))
  }
}

This works fine if I call this with the following arguments:
add(1)()

But typescript throws the following error when I call it like this:
add(1)(2)()

Cannot invoke an expression whose type lacks a call signature. Type 'number | ((b?: number) => number | ...)' has no compatible call signatures.

What do I need to add to enable typed usage of this method?

Body:
I would describe the type of add() as the following Add type:

type Add = (a: number) => Add2;
type Add2 = ((b: number) => Add2) & (() => number);

The Add function type takes a number and returns an Add2.

The Add2 function type is an overloaded function which returns a different type depending on the number and type of arguments that come in.  It's also self-referential: if you call an Add2 with a number parameter, you get an Add2 out.

You more or less need to use assertions to convince the compiler that your add() is a valid Add:

const add = ((a: number) => (b?: number) =>
  b === undefined ? a : add(a + b)) as Add;

And then you should be able to use it as expected:

const x = add(1)(2)(3)(); // number
console.log(x); // 6

Link to code

Okay, hope that helps; good luck!


问:
iOS SceneKit application faster in App Switcher Mode
I'm encountering a rather bizarre behavior with a SceneKit application that I am developing. I invoke a method which manipulates the simdWorldPosition property of  various SCNNode objects. The method changes the simdWorldPosition in a loop which can execute around ~40k times.

I define a DispatchQueue:

let updateQueue = DispatchQueue(label: Bundle.main.bundleIdentifier! +
        ".serialSceneKitQueue")
```

<p>A button press calls the following: </p>

<pre class="lang-swift prettyprint-override"><code>@objc func didPressGreedy() {
    updateQueue.async {
        let _ = self.Greedy()
    }
}
</code>```

autoreleasepool {
    for offset in stride(from: 0.0, through: planeWidth, by: increment) {
        var topLeftTransform = arkitAnchor!.simdWorldTransform * HelperMethods.makeTranslationMatrix(tx: -Float(planeWidth / 2), ty: 0.0, tz: -Float(planeHeight/2))
        topLeftTransform = topLeftTransform * HelperMethods.makeTranslationMatrix(tx: Float(offset), ty: 0.0, tz: 0.0)
        let topEdgePosition = simd_float3(x: topLeftTransform.columns.3.x, y: topLeftTransform.columns.3.y, z: topLeftTransform.columns.3.z)
        saLabelComponent.simdWorldPosition = topEdgePosition

        let oldSpriteTransform = sprite.simdWorldTransform

        for xOffset in stride(from:-0.20, through: 0.20, by: increment) {
            for yOffset in stride(from: 0.05, through: 0.20, by: increment) {
                LOOP_1_ITERATIONS += 1
                var newSpriteTransform = anchor.simdWorldTransform * HelperMethods.makeTranslationMatrix(tx: Float(xOffset), ty: Float(yOffset), tz: 0.0)
                sprite.simdWorldTransform = newSpriteTransform
            }
        }
    }
}
```

These iterations are slow - I can sometimes see about a thousand manipulations happen in multiple seconds and then it takes a minute to do 50 simdWorldPosition updates. If I tap on the screen I can see the executions speed up.

When I use the iOS App Switcher (by just swiping up on the application on iPhone XS and letting it sit in the App Switcher) the application significantly speeds up the execution the iterations by a factor of 10x.

Any idea of why this is caused? If I am having conceptual issues please point to relevant topic/articles.

答:
Any idea of why this is caused?

It sounds like your app is simply doing a lot less work when in switcher. That's not surprising... the area that the app draws into is much smaller, there are no touch events to handle, etc. The difference may have less to do with the code in the loop you've shown than in the fact that the rest of the app isn't doing as much.

If you really want to know what's going on (or what isn't going on), the best thing to do is to profile your code with Instruments.

Body:
I'm encountering a rather bizarre behavior with a SceneKit application that I am developing. I invoke a method which manipulates the simdWorldPosition property of  various SCNNode objects. The method changes the simdWorldPosition in a loop which can execute around ~40k times.

I define a DispatchQueue:

let updateQueue = DispatchQueue(label: Bundle.main.bundleIdentifier! +
        ".serialSceneKitQueue")

A button press calls the following:

@objc func didPressGreedy() {
    updateQueue.async {
        let _ = self.Greedy()
    }
}

autoreleasepool {
    for offset in stride(from: 0.0, through: planeWidth, by: increment) {
        var topLeftTransform = arkitAnchor!.simdWorldTransform * HelperMethods.makeTranslationMatrix(tx: -Float(planeWidth / 2), ty: 0.0, tz: -Float(planeHeight/2))
        topLeftTransform = topLeftTransform * HelperMethods.makeTranslationMatrix(tx: Float(offset), ty: 0.0, tz: 0.0)
        let topEdgePosition = simd_float3(x: topLeftTransform.columns.3.x, y: topLeftTransform.columns.3.y, z: topLeftTransform.columns.3.z)
        saLabelComponent.simdWorldPosition = topEdgePosition

        let oldSpriteTransform = sprite.simdWorldTransform

        for xOffset in stride(from:-0.20, through: 0.20, by: increment) {
            for yOffset in stride(from: 0.05, through: 0.20, by: increment) {
                LOOP_1_ITERATIONS += 1
                var newSpriteTransform = anchor.simdWorldTransform * HelperMethods.makeTranslationMatrix(tx: Float(xOffset), ty: Float(yOffset), tz: 0.0)
                sprite.simdWorldTransform = newSpriteTransform
            }
        }
    }
}

These iterations are slow - I can sometimes see about a thousand manipulations happen in multiple seconds and then it takes a minute to do 50 simdWorldPosition updates. If I tap on the screen I can see the executions speed up.

When I use the iOS App Switcher (by just swiping up on the application on iPhone XS and letting it sit in the App Switcher) the application significantly speeds up the execution the iterations by a factor of 10x.

Any idea of why this is caused? If I am having conceptual issues please point to relevant topic/articles.


问:
why django username parameters passed to urls is connecting directly and how prevent it
I'm trying to access to a user profil if urls parameters is profile/username
it work but i have a security problem because user is directly connected.

How i can define in django user profil access depending if user is authenticated or not

profil.html

```<code>{% if  user.is_authenticated %}
            <p>{{ user.username}}</p>
            <a href="">edit your profile</a>

            {% else %}
            <p>{{ user.username}}</p>
            <p>basic profile of user</p>
 {% endif%}
</code>```

views.py

```<code>def profil(request,username):
    user=get_object_or_404(User, username=username)
    context = {
        'user':user
    }
    return render(request, 'service/profil.html',context)
</code>```

答:
I fixed my problem condition was

{% if  request.user == requested_user %}

{{ requested_user.username}}

            edit your profile
            {% else %}

{{ requested_user.username}}

basic profile of user

 {% endif%}

Body:
I'm trying to access to a user profil if urls parameters is profile/username
it work but i have a security problem because user is directly connected.

How i can define in django user profil access depending if user is authenticated or not

profil.html

{% if  user.is_authenticated %}

{{ user.username}}

            edit your profile

            {% else %}

{{ user.username}}

basic profile of user

 {% endif%}

views.py

def profil(request,username):
    user=get_object_or_404(User, username=username)
    context = {
        'user':user
    }
    return render(request, 'service/profil.html',context)

Body:
I fixed my problem condition was

{% if  request.user == requested_user %}
            <p>{{ requested_user.username}}</p>
            <a href="">edit your profile</a>
            {% else %}
            <p>{{ requested_user.username}}</p>
            <p>basic profile of user</p>
 {% endif%}


问:
How can I allow multiple activities to share the same inflated "included" view?
I see this question here, and it makes me wonder if what I'm asking isn't really possible:

How to share a view across various activities

Basically, I have a common footer view that I'm inflating (including) in all of my views. However, it uses the same repetitive code to do that. My thought was to create a parent activity class to do this, but it doesn't seem correct to have one activity render the view of another. So should I just create a utility class of some sort, or is there a better way?

答:
You can include other layout XML files directly in another layout file.  So whenever you set content to a layout file, along comes your footer for the ride.

If your footer needs code to drive it, just create a custom class for it along with the layout file.  Then perhaps during instantiation you can drive the code that needs to execute.

This is a blog of how to do it.


问:
Get the response from the dispatch - React Redux
How can I get a response back from the dispatch action to the component and get the values in the context.

index.jsx :

```<code>    componentWillMount() {
        this.context.store.dispatch(getConfigSettings());
    }
</code>```

Dispatch calls :

```<code>export function getConfigSettings(params) {
    return (dispatch) => {
        dispatch(requestConfig());
        admin.getConfig(params,
            (response) => {
                return dispatch(receivedConfig(response));
            },
            (error) => {
                return dispatch(failedConfig(error));
            }
        );
    };
}

export function getConfig(params, onSuccess, onFailure) {
    const url = `${process.env}/admin/data`;
    return $.get(url,
        (response) => {
            onSuccess(response);
        }).fail((error) => {
        onFailure(error);
    });
}
</code>```

Reducer :

```<code>import {
    request,
    received,
    failed
} from '../actions/actions';

const defaultState = Immutable.fromJS({
    data: Immutable.fromJS([]),
    loading: true,
    error: false
});

const reducer = createReducer({
    [request]: (state, res) => {
        return state.set('loading', true)
            .set('error', false)
    },
    [received]: (state, res) => {
        return state.set('data', Immutable.fromJS(res))
            .set('loading', false)
            .set('error', false);
    },
    [failed]: (state, res) => {
        return state.set('data', Immutable.fromJS({}))
            .set('loading', false)
            .set('error', true)
    }
}, defaultState);

export default reducer;
</code>```

I have checked the response has the correct value. But how to access that value in the index.jsx
I have to display those values in the table.

答:
While you really should just utilize mapStateToProps() to retrieve the data you need from the store, you can return a Promise that resolves the response or rejects the data as follows:

```<code>export function getConfigSettings(params) {
    return (dispatch) => {
        dispatch(requestConfig());

        return new Promise((resolve, reject) => {
          admin.getConfig(params,
              (response) => {
                  dispatch(receivedConfig(response));
                  return resolve(response);
                  // or return resolve(dispatch(receivedConfig(response)));
              },
              (error) => {
                  dispatch(failedConfig(error));
                  return reject(error);
                  // or return reject(dispatch(failedConfig(error)));
              }
          );
        }
    };
}
</code>```

Then in the component you can access the resolved response or rejected error using then() and catch():

```<code>componentWillMount() {
  this.context.store.dispatch(getConfigSettings())
    .then(response => console.log(response))
    .catch(err => console.log(err);
}
</code>```

Here is an example in action.

I'd really recommend looking into something Promise based for making HTTP calls such as fetch to avoid needing callbacks. redux-thunk works really well with promises.

Hopefully that helps!

Body:
How can I get a response back from the dispatch action to the component and get the values in the context.

index.jsx :

    componentWillMount() {
        this.context.store.dispatch(getConfigSettings());
    }

Dispatch calls :

export function getConfigSettings(params) {
    return (dispatch) => {
        dispatch(requestConfig());
        admin.getConfig(params,
            (response) => {
                return dispatch(receivedConfig(response));
            },
            (error) => {
                return dispatch(failedConfig(error));
            }
        );
    };
}

export function getConfig(params, onSuccess, onFailure) {
    const url = `${process.env}/admin/data`;
    return $.get(url,
        (response) => {
            onSuccess(response);
        }).fail((error) => {
        onFailure(error);
    });
}

Reducer :

import {
    request,
    received,
    failed
} from '../actions/actions';

const defaultState = Immutable.fromJS({
    data: Immutable.fromJS([]),
    loading: true,
    error: false
});

const reducer = createReducer({
    [request]: (state, res) => {
        return state.set('loading', true)
            .set('error', false)
    },
    [received]: (state, res) => {
        return state.set('data', Immutable.fromJS(res))
            .set('loading', false)
            .set('error', false);
    },
    [failed]: (state, res) => {
        return state.set('data', Immutable.fromJS({}))
            .set('loading', false)
            .set('error', true)
    }
}, defaultState);

export default reducer;

I have checked the response has the correct value. But how to access that value in the index.jsx
I have to display those values in the table.

Body:
While you really should just utilize mapStateToProps() to retrieve the data you need from the store, you can return a Promise that resolves the response or rejects the data as follows:

export function getConfigSettings(params) {
    return (dispatch) => {
        dispatch(requestConfig());

        return new Promise((resolve, reject) => {
          admin.getConfig(params,
              (response) => {
                  dispatch(receivedConfig(response));
                  return resolve(response);
                  // or return resolve(dispatch(receivedConfig(response)));
              },
              (error) => {
                  dispatch(failedConfig(error));
                  return reject(error);
                  // or return reject(dispatch(failedConfig(error)));
              }
          );
        }
    };
}

Then in the component you can access the resolved response or rejected error using then() and catch():

componentWillMount() {
  this.context.store.dispatch(getConfigSettings())
    .then(response => console.log(response))
    .catch(err => console.log(err);
}

Here is an example in action.

I'd really recommend looking into something Promise based for making HTTP calls such as fetch to avoid needing callbacks. redux-thunk works really well with promises.

Hopefully that helps!


问:
How to prevent cross-domain ajax requests?
How can I detect if my php script is being called from another domain and the other domain is making illegal use of my script? Is there a way to prevent this too?

UPDATE

I found this question on SO, but its still not safe, it can be spoofed.

答:
for user3491125's answer, you could try encrypting the session token. I have one encryption function that can add a unique key based on a users port 80 IP. it's Not foolproof, but it does make it more difficult for hackers.</p>

```<code>function encryptString($string, $action, $baseIP = 'false', $extraKey = ''){
    global $flag;

    $encryptedIP = '';

    if($baseIP){
        $encryptedIP = encryptString(strip_tags(htmlentities($_SERVER['REMOTE_ADDR'])), 'encrypt', false);
    }

    $output = false;

    $encrypt_method = "AES-256-CBC";
    $secret_key = $flag['encrypt-key'].$encryptedIP.'-'.$extraKey;
    $secret_iv = $flag['encrypt-secret'].$encryptedIP.'-'.$extraKey;

    $key = hash('sha256', $secret_key);
    $iv = substr(hash('sha256', $secret_iv), 0, 16);

    $output;

    if($action == 'encrypt'){
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
        $output = str_replace('=', '[equal]', $output);
    }else if($action == 'decrypt'){
        $setString = str_replace('[equal]', '=', $string);
        $output = openssl_decrypt(base64_decode($setString), $encrypt_method, $key, 0, $iv);
    }

    return $output;
}
</code>```

Body:
for user3491125's answer, you could try encrypting the session token. I have one encryption function that can add a unique key based on a users port 80 IP. it's Not foolproof, but it does make it more difficult for hackers.

function encryptString($string, $action, $baseIP = 'false', $extraKey = ''){
    global $flag;

    $encryptedIP = '';

    if($baseIP){
        $encryptedIP = encryptString(strip_tags(htmlentities($_SERVER['REMOTE_ADDR'])), 'encrypt', false);
    }

    $output = false;

    $encrypt_method = "AES-256-CBC";
    $secret_key = $flag['encrypt-key'].$encryptedIP.'-'.$extraKey;
    $secret_iv = $flag['encrypt-secret'].$encryptedIP.'-'.$extraKey;

    $key = hash('sha256', $secret_key);
    $iv = substr(hash('sha256', $secret_iv), 0, 16);

    $output;

    if($action == 'encrypt'){
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
        $output = str_replace('=', '[equal]', $output);
    }else if($action == 'decrypt'){
        $setString = str_replace('[equal]', '=', $string);
        $output = openssl_decrypt(base64_decode($setString), $encrypt_method, $key, 0, $iv);
    }

    return $output;
}


问:
How to loop over query data and insert in structure?
I have query data that should be inserted in the structure. While looping over data each value should be assigned to matching column. Here is example of query data:

```<code>    REC_ID  NAME    STATUS      TYPE    YEAR
1   01      PARIS   Approved    1       2019
2   06      AUSTIN  Inactive    3       2017
3   48      LONDON  Approved    2       2018
4   43      ROME    Inactive    5       2019
5   61      DUBLIN  Inactive    4       2019
</code>```

This data should be organized to look like this:

```<code>1
  REC_ID  01
  NAME    PARIS
  STATUS  Approved
  TYPE    1
  YEAR    2019
2
  REC_ID  06
  NAME    AUSTIN
  STATUS  Inactive
  TYPE    3
  YEAR    2017
3
  REC_ID  48
  NAME    LONDON
  STATUS  Approved
  TYPE    2
  YEAR    2018
4
  REC_ID  43
  NAME    ROME
  STATUS  Inactive
  TYPE    5
  YEAR    2019
5
  REC_ID  61
  NAME    DUBLIN
  STATUS  Inactive
  TYPE    4
  YEAR    2019
</code>```

I tried to get desired data format with this function:

```<code>function formatData(qryData) {
    local.fnResult = structNew();
    local.fnData = structNew();

    if(qryData.recordcount){
        for(row in qryData) {
            for(column in qryData.columnList) {
                local.strRec = structNew();
                structInsert(strRec, column, row[column]);
                local.fnData[qryData.currentrow] = strRec;
            }
        }
    }

    writeDump(fnData);
}
</code>```

Here is how my result looks:

```<code>1
  REC_ID  01
2
  REC_ID  06
3
  REC_ID  48
4
  REC_ID  43
5
  REC_ID  61
</code>```

I use ColdFusion 11 cfscript syntax. If anyone can help me solve this problem please let me know. Thank you.

答:
If I understand this correctly, it looks like you could just

```<code>array function formatData(qryData) {
   return DeserializeJSON(SerializeJSON(arguments.qryData, "struct"));
}
</code>```

Runnable example on trycf.com

Result:

Alternative

```<code>array function formatData(qryData) {
   var result = [];

   for (var row in qryData) {
       result.append(row);
   }

   return result;
}
</code>```

Body:
I have query data that should be inserted in the structure. While looping over data each value should be assigned to matching column. Here is example of query data:

    REC_ID  NAME    STATUS      TYPE    YEAR
1   01      PARIS   Approved    1       2019
2   06      AUSTIN  Inactive    3       2017
3   48      LONDON  Approved    2       2018
4   43      ROME    Inactive    5       2019
5   61      DUBLIN  Inactive    4       2019

This data should be organized to look like this:

1
  REC_ID  01
  NAME    PARIS
  STATUS  Approved
  TYPE    1
  YEAR    2019
2
  REC_ID  06
  NAME    AUSTIN
  STATUS  Inactive
  TYPE    3
  YEAR    2017
3
  REC_ID  48
  NAME    LONDON
  STATUS  Approved
  TYPE    2
  YEAR    2018
4
  REC_ID  43
  NAME    ROME
  STATUS  Inactive
  TYPE    5
  YEAR    2019
5
  REC_ID  61
  NAME    DUBLIN
  STATUS  Inactive
  TYPE    4
  YEAR    2019

I tried to get desired data format with this function:

function formatData(qryData) {
    local.fnResult = structNew();
    local.fnData = structNew();

    if(qryData.recordcount){
        for(row in qryData) {
            for(column in qryData.columnList) {
                local.strRec = structNew();
                structInsert(strRec, column, row[column]);
                local.fnData[qryData.currentrow] = strRec;
            }
        }
    }

    writeDump(fnData);
}

Here is how my result looks:

1
  REC_ID  01
2
  REC_ID  06
3
  REC_ID  48
4
  REC_ID  43
5
  REC_ID  61

I use ColdFusion 11 cfscript syntax. If anyone can help me solve this problem please let me know. Thank you.

Body:
If I understand this correctly, it looks like you could just

array function formatData(qryData) {
   return DeserializeJSON(SerializeJSON(arguments.qryData, "struct"));
}

Runnable example on trycf.com

Result:

Alternative

array function formatData(qryData) {
   var result = [];

   for (var row in qryData) {
       result.append(row);
   }

   return result;
}


问:
How to change the legend of a ggplot
When I use ggplot and try to change the legend name from "value" to "Work schedules" doesn't change. As well the scale 0 - Did not worked; 1-Did worked. Do you know what could be wrong with my code:

```<code>plot <- ggplot(df3, aes(x = time, y = index, fill = value)) +
  geom_raster() +
  facet_grid(~ day) +
  theme(panel.spacing = unit(1, "mm"),
        axis.text.x = element_text(angle = 90, hjust = 1)) +
  labs(x="Hours", y ="Identification Number") +
  scale_x_continuous(breaks =  c(9,17), name= "Time") +
  scale_y_continuous()

plot + annotate("rect", fill = "red", alpha = 0.5, xmin = c(9), xmax = c(17), ymin = -Inf, ymax = Inf) +
  ylab ("Identification number") +
  theme_bw()
</code>```

答:
@Jordo82 has the right answer for naming the legend. As far as changing the scale from continuous to discrete, you should take a look at your variable "value" and see the range of the (for lack of a better word) values. If the variable type is a double, you may need to use dplyr::mutate() to create ranges. If the values are indeed discrete, try dplyr::mutate(value = as.factor(values))</p>

```<code>df3 <- df3 %>% dplyr::mutate(value = ifelse(value < 2, "Not Worked", "Worked"))
</code>```

Title: How to change the legend of a ggplot

Body:
When I use ggplot and try to change the legend name from "value" to "Work schedules" doesn't change. As well the scale 0 - Did not worked; 1-Did worked. Do you know what could be wrong with my code:

plot <- ggplot(df3, aes(x = time, y = index, fill = value)) +
  geom_raster() +
  facet_grid(~ day) +
  theme(panel.spacing = unit(1, "mm"),
        axis.text.x = element_text(angle = 90, hjust = 1)) +
  labs(x="Hours", y ="Identification Number") +
  scale_x_continuous(breaks =  c(9,17), name= "Time") +
  scale_y_continuous()

plot + annotate("rect", fill = "red", alpha = 0.5, xmin = c(9), xmax = c(17), ymin = -Inf, ymax = Inf) +
  ylab ("Identification number") +
  theme_bw()

Body:
@Jordo82 has the right answer for naming the legend. As far as changing the scale from continuous to discrete, you should take a look at your variable "value" and see the range of the (for lack of a better word) values. If the variable type is a double, you may need to use dplyr::mutate() to create ranges. If the values are indeed discrete, try dplyr::mutate(value = as.factor(values))

df3 <- df3 %>% dplyr::mutate(value = ifelse(value < 2, "Not Worked", "Worked"))


问:
Cutting a database down to size
Say you have a database that has served a company for 10 years. It is 500GB in size, it has myriad tables, stored procedures and triggers.

Now say you wish to create a cut down version of the database to use as a test bed for use in integration testing and for individual testers and developers to spin up instances of to play around with.

In broad terms how would you set about this task?

In case it matters, the database I have in mind is SQL Server 2008.

Edit: removed "unit testing" because of course unit tests should not test db integration

答:
If your tables all consisted of unrelated data, you could just pick X random records from each table. I'm guessing that the problem is that the tables are NOT unrelated, so if, say, table A includes a foreign key reference to table B and you just pulled 10% of the records from table A and 10% of the records from table B, you'd have a whole bunch of invalid references from A to B.

I don't know of a general solution to this problem. It depends on the exact structure of your database. I often find that my databases consist of a small number of "central" tables that have lots of references from other tables. That is, I generally find that I have, say, an Order table, and then there's an Order Line table that points to Order, and a Customer table that Order points to, and a Delivery table that points to Order or maybe Order Line, etc, but everything seems to center around "Order". In that case, you could randomly pick some number of Order records, then find all the Customers for those Orders, all the Order Lines for those Orders, etc. I usually also have some number of "code lookup" tables, like a list of all the "order status" codes, another list of all the "customer type" codes, etc. These are usually small, so I just copy them entirely.

If your database is more ... disjointed ... than that, i.e. if it doesn't have any clear centers but is a maze of interrelationships, this could be much more complicated. I think the same principle would apply, though. Pick SOME starting point, select some records from there, then get all the records connected to those records, etc.

Title: Cutting a database down to size


问:
Using Mocha with TypeScript paths
I'm having an issue with running mocha when using the paths + baseUrl configuration in TypeScript

My tsconfig.js is set like so:

```<code>"baseUrl": "./src/", /* Base directory to resolve non-absolute module names. */
"paths": {
  "interfaces/*": [
    "interfaces/*"
  ],
  "models/*": [
    "models/*"
  ],
  "schemas/*": [
    "schemas/*"
  ],
  "classes/*": [
    "classes/*"
  ],
  "libs/*": [
    "libs/*"
  ],
  "config/*": [
    "config/*"
  ]
</code>```

and I'm runnings mocha as "mocha build/test"

The compiled TS code fails to find my references since it compiles to

```<code>var user_1 = require("interfaces/user");
</code>```

and if I add "../" beforehand it will compile without problems

Any ideas what I'm doing wrong here?

答:
You should use a normal testing integration package (most popular one). such as moch-typescript.
With that you only need to setup in test in package.json

```<code>script: 'mocha --ui mocha-typescript test.ts'
</code>```

https://www.npmjs.com/package/mocha-typescript

I will give you a better example - test.ts

```<code>import { suite, test, slow, timeout } from "mocha-typescript";
@suite class Hello {
    @test world() {
        assert.equal(1, 2, "Expected one to equal two.");
    }
}
</code>```

Title: Using Mocha with TypeScript paths

Body:
I'm having an issue with running mocha when using the paths + baseUrl configuration in TypeScript

My tsconfig.js is set like so:

"baseUrl": "./src/", /* Base directory to resolve non-absolute module names. */
"paths": {
  "interfaces/*": [
    "interfaces/*"
  ],
  "models/*": [
    "models/*"
  ],
  "schemas/*": [
    "schemas/*"
  ],
  "classes/*": [
    "classes/*"
  ],
  "libs/*": [
    "libs/*"
  ],
  "config/*": [
    "config/*"
  ]

and I'm runnings mocha as "mocha build/test"

The compiled TS code fails to find my references since it compiles to

var user_1 = require("interfaces/user");

and if I add "../" beforehand it will compile without problems

Any ideas what I'm doing wrong here?

Body:
You should use a normal testing integration package (most popular one). such as moch-typescript.
With that you only need to setup in test in package.json

script: 'mocha --ui mocha-typescript test.ts'

https://www.npmjs.com/package/mocha-typescript

I will give you a better example - test.ts

import { suite, test, slow, timeout } from "mocha-typescript";
@suite class Hello {
    @test world() {
        assert.equal(1, 2, "Expected one to equal two.");
    }
}


问:
TS config target and lib for Angular 8
First of all I kinda know my question will be closed as a duplicate but I cannot find an answer so far.

I am building an angular app based on Angular 8

What target and lib should I use and how are these related? Should lib and target for the tsconfig be at the same version? What are the benefits ?

I don't understand for example what is the difference from a config like this:

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2015",
      "dom"
    ]
  }
}
</code>```

To this:

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  }
}

</code>```

That both work fine.

答:
I might be wrong, but i'll try to answer.

The target specifies what the typescript compiler will output for target ecmascript version.

for angular 8 i think this is set to esnext, because then webpack will compile it once more before you get your bundles.

And then using the new differential loading webpack will spit out two versions one in es5 for older browsers, and one for > es2015 browsers.

The libs are all the features that typescript will enable you to use when writing your code. so dom enables all dom typings, and es2018 would enable all new features that came in that version.

Angular does a good job of polyfilling the language features for you, but sometimes you will need to add polyfill packages to get newer apis working in older browsers.

I hope that clears it up a bit :)

Title: TS config target and lib for Angular 8

Body:
First of all I kinda know my question will be closed as a duplicate but I cannot find an answer so far.

I am building an angular app based on Angular 8

What target and lib should I use and how are these related? Should lib and target for the tsconfig be at the same version? What are the benefits ?

I don't understand for example what is the difference from a config like this:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2015",
      "dom"
    ]
  }
}

To this:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  }
}

That both work fine.


问:
Opening a file with universal newlines in binary mode in python 3
We're (finally) upgrading an application to Python 3.

One thing we have to upgrade is rewriting a CSV file using normal newlines.

The original (python 2) code looks like this:

import csv

IN_PATH = 'in.csv'
OUT_PATH = 'out.csv'

# Opens the original file in 'text mode' (which has no effect on Python 2)
# and with 'universal newlines',
# meaning \r, \n, and \r\n all get treated as line separators.
with open(IN_PATH, 'rU') as in_csv:
    with open(OUT_PATH, 'w') as out_csv:
        csv_reader = csv.reader(in_csv)
        csv_writer = csv.writer(out_csv)

        for tupl in csv_reader:
            csv_writer.writerow(tupl)

```

<p>These CSV files are user-provided. This means:</p>

<ul>
<li>we have no control over what newline characters they use, so we need to handle all of them.</li>
<li>we don't know the encoding of the file at this stage in the process.</li>
</ul>

<p>Because we don't know the encoding, we cannot decode the bytestrings into text. </p>

<p>To make this work on Python 3, first we changed it to use <code>io.open()</code>, which is mostly compatible with py3's <code>open()</code>. Now we can't use 'text mode' any more, because on Python 3 that requires decoding the bytestrings, and we don't know the encoding.</p>

<p>However, using 'binary mode' means we can no longer use universal-newlines, since that's only available in text mode.</p>

<pre class="lang-py prettyprint-override"><code>
# Opens the original file in 'binary mode'
# (because we don't know the encoding, so we can't decode it)
# FIXME: How to get universal newline support?
with io.open(IN_PATH, 'rb') as in_csv:
    with io.open(OUT_PATH, 'wb') as out_csv:
</code>```

Note that, although the U mode character is no longer supported in python 3, it does use universal newlines by default in text mode. It doesn't appear to have any way of using universal newlines in binary mode.

How can we make this code work in Python 3?

答:
I don't think there is a built-in way to do what you want in Python 3.  Without knowing the encoding, you only know for sure that you have a bunch of bytes - you're not sure which ones of them mean the characters \r or \n.

Your Python 2 code was probably using the system default encoding according to sys.getdefaultencoding() to inform the built-in universal newline normalizer (don't quote me, I haven't looked at the implementation), and if your system is like mine, that was probably ascii.

Fortunately I think most encodings (including utf-8) only differ in the mappings of their higher-order characters (above the ascii range).  So, it's not a terrible assumption to make that the byte 10 means \n and 13 means \r for all common encodings - meaning you could just do the replacement yourself by reading the input byte-by-byte (or rather, using a sliding two-byte window).

Warning: I haven't exhaustively tested the following code for behavior around repeated sequences like \r\r\r or weird things like \n\r, so while it may handle those sanely it also may not.  Please do test on your own data.

```<code>from __future__ import print_function

import io
import six  # optional (but hugely helpful for a 2 to 3 port)

def normalize(prev, curr):
    ''' Given current and previous bytes, get tuple of bytes that should be written

    :param prev: The byte just before the read-head
    :type  prev: six.binary_type
    :param curr: The byte at the read-head
    :type  curr: six.binary_type
    :returns   : A tuple containing 0, 1, or 2 bytes that should be written
    :rtype     : Tuple[six.binary_type]
    '''
    R = six.binary_type(b'\r')
    N = six.binary_type(b'\n')
    if   curr == R:         # if we find R, can't dump N yet because it might be start of RN sequence and we must consume N too
        return ()
    elif curr == N:         # if we find N, doesn't matter what previous byte was - dump N
        return (N,)
    elif prev == R:         # we know current not N or R; if previous byte was R - dump N, then the current byte
        return (N, curr)
    else:                   # we know current not N or R and prev not R - dump the current byte
        return (curr,)

if __name__ == '__main__':

    IN_PATH = 'in.csv'
    OUT_PATH = 'out.csv'

    with io.open(IN_PATH, mode='rb') as in_csv:
        with io.open(OUT_PATH, mode='wb') as out_csv:
            prev = None                                 # at start, there is no previous byte
            curr = six.binary_type(in_csv.read(1))      # at start, the current byte is the input file's first byte
            while curr:                                 # loop over all bytes in the input file
                for byte in normalize(prev, curr):      # loop over all bytes returned from the normalizing function
                    print(repr(byte))                   # debugging
                    out_csv.write(byte)                 # write each byte to the output file
                prev = curr                             # update value of previous byte
                curr = six.binary_type(in_csv.read(1))  # update value of current byte
</code>```

This works for me on both Python 2.7.16 and 3.7.3, using an input file I created (using Python 3) like this:

```<code>import io

with io.open('in.csv', mode='wb', encoding='latin-1') as fp:
    fp.write('à,b,c\n')
    fp.write('1,2,3\r')
    fp.write('4,5,6\r\n')
    fp.write('7,8,9\r')
    fp.write('10,11,12\n')
    fp.write('13,14,15')
</code>```

It also works using encoding='UTF-8' (as it should).

It's not necessary to use six.binary_type() like I did, but I find it a helpful reminder of the semantics of the data I'm working with, esp when writing cross-version code.

I spent a while trying to figure out if there was a nicer way to do this than manually examining all the bytes, but was unsuccessful.  If anyone else finds a way, I'm interested in seeing it!

Body:
We're (finally) upgrading an application to Python 3.

One thing we have to upgrade is rewriting a CSV file using normal newlines.

The original (python 2) code looks like this:

import csv

IN_PATH = 'in.csv'
OUT_PATH = 'out.csv'

# Opens the original file in 'text mode' (which has no effect on Python 2)
# and with 'universal newlines',
# meaning \r, \n, and \r\n all get treated as line separators.
with open(IN_PATH, 'rU') as in_csv:
    with open(OUT_PATH, 'w') as out_csv:
        csv_reader = csv.reader(in_csv)
        csv_writer = csv.writer(out_csv)

        for tupl in csv_reader:
            csv_writer.writerow(tupl)

These CSV files are user-provided. This means:

we have no control over what newline characters they use, so we need to handle all of them.

we don't know the encoding of the file at this stage in the process.

Because we don't know the encoding, we cannot decode the bytestrings into text.

To make this work on Python 3, first we changed it to use io.open(), which is mostly compatible with py3's open(). Now we can't use 'text mode' any more, because on Python 3 that requires decoding the bytestrings, and we don't know the encoding.

However, using 'binary mode' means we can no longer use universal-newlines, since that's only available in text mode.

# Opens the original file in 'binary mode'
# (because we don't know the encoding, so we can't decode it)
# FIXME: How to get universal newline support?
with io.open(IN_PATH, 'rb') as in_csv:
    with io.open(OUT_PATH, 'wb') as out_csv:

Note that, although the U mode character is no longer supported in python 3, it does use universal newlines by default in text mode. It doesn't appear to have any way of using universal newlines in binary mode.

How can we make this code work in Python 3?

Body:
I don't think there is a built-in way to do what you want in Python 3.  Without knowing the encoding, you only know for sure that you have a bunch of bytes - you're not sure which ones of them mean the characters \r or \n.

Your Python 2 code was probably using the system default encoding according to sys.getdefaultencoding() to inform the built-in universal newline normalizer (don't quote me, I haven't looked at the implementation), and if your system is like mine, that was probably ascii.

Fortunately I think most encodings (including utf-8) only differ in the mappings of their higher-order characters (above the ascii range).  So, it's not a terrible assumption to make that the byte 10 means \n and 13 means \r for all common encodings - meaning you could just do the replacement yourself by reading the input byte-by-byte (or rather, using a sliding two-byte window).

Warning: I haven't exhaustively tested the following code for behavior around repeated sequences like \r\r\r or weird things like \n\r, so while it may handle those sanely it also may not.  Please do test on your own data.

from __future__ import print_function

import io
import six  # optional (but hugely helpful for a 2 to 3 port)

def normalize(prev, curr):
    ''' Given current and previous bytes, get tuple of bytes that should be written

    :param prev: The byte just before the read-head
    :type  prev: six.binary_type
    :param curr: The byte at the read-head
    :type  curr: six.binary_type
    :returns   : A tuple containing 0, 1, or 2 bytes that should be written
    :rtype     : Tuple[six.binary_type]
    '''
    R = six.binary_type(b'\r')
    N = six.binary_type(b'\n')
    if   curr == R:         # if we find R, can't dump N yet because it might be start of RN sequence and we must consume N too
        return ()
    elif curr == N:         # if we find N, doesn't matter what previous byte was - dump N
        return (N,)
    elif prev == R:         # we know current not N or R; if previous byte was R - dump N, then the current byte
        return (N, curr)
    else:                   # we know current not N or R and prev not R - dump the current byte
        return (curr,)

if __name__ == '__main__':

    IN_PATH = 'in.csv'
    OUT_PATH = 'out.csv'

    with io.open(IN_PATH, mode='rb') as in_csv:
        with io.open(OUT_PATH, mode='wb') as out_csv:
            prev = None                                 # at start, there is no previous byte
            curr = six.binary_type(in_csv.read(1))      # at start, the current byte is the input file's first byte
            while curr:                                 # loop over all bytes in the input file
                for byte in normalize(prev, curr):      # loop over all bytes returned from the normalizing function
                    print(repr(byte))                   # debugging
                    out_csv.write(byte)                 # write each byte to the output file
                prev = curr                             # update value of previous byte
                curr = six.binary_type(in_csv.read(1))  # update value of current byte

This works for me on both Python 2.7.16 and 3.7.3, using an input file I created (using Python 3) like this:

import io

with io.open('in.csv', mode='wb', encoding='latin-1') as fp:
    fp.write('à,b,c\n')
    fp.write('1,2,3\r')
    fp.write('4,5,6\r\n')
    fp.write('7,8,9\r')
    fp.write('10,11,12\n')
    fp.write('13,14,15')

It also works using encoding='UTF-8' (as it should).

It's not necessary to use six.binary_type() like I did, but I find it a helpful reminder of the semantics of the data I'm working with, esp when writing cross-version code.

I spent a while trying to figure out if there was a nicer way to do this than manually examining all the bytes, but was unsuccessful.  If anyone else finds a way, I'm interested in seeing it!