问:
Get Data from API using retrofit
I need to get the details from the API and display them in textviews.

Here's my API in JSON format  : https://imgur.com/a/WI98ymx

I need to get the data like username, user image, user phone number etc in Strings and display them in textviews.
How do i request all the fields and show the list in different textviews?

Here's my Login interface

```<code>package com.example.hb.loginapi;

import java.util.List;

   import retrofit2.Call;
   import retrofit2.http.GET;

  import retrofit2.http.POST;

   import retrofit2.http.Query;

    interface Login {

   @POST("user_login_v1")
   Call<ResObj>  loginInfo(@Query("password") String password,
   @Query("email") String email);

   @GET("user_login_v1")
   Call<List> getUserDetails();

}
</code>```

Here's my ResObj class

```<code>package com.example.hb.loginapi;

import com.google.gson.annotations.SerializedName;
import java.util.List;

 public class ResObj {

@SerializedName("settings")
private Settings settings;

@SerializedName("data")
private List<DataItem> data;

public void setSettings(Settings settings){
    this.settings = settings;
}

public Settings getSettings(){
    return settings;
}

public void setData(List<DataItem> data){
    this.data = data;
}

public List<DataItem> getData(){
    return data;
}

public class Settings {

    @SerializedName("success")
    private String success;

    @SerializedName("message")
    private String message;

    @SerializedName("fields")
    private List<String> fields;

    public void setSuccess(String success) {
        this.success = success;
    }

    public String getSuccess() {
        return success;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setFields(List<String> fields) {
        this.fields = fields;
    }

    public List<String> getFields() {
        return fields;
    }
}

public class DataItem{

    @SerializedName("user_name")
    private String userName;

    @SerializedName("search_report_count")
    private String searchReportCount;

    @SerializedName("access_token")
    private String accessToken;

    @SerializedName("profile_image")
    private String profileImage;

    @SerializedName("is_social")
    private String isSocial;

    @SerializedName("is_notification_enabled")
    private String isNotificationEnabled;

    @SerializedName("user_id")
    private String userId;

    @SerializedName("phone")
    private String phone;

    @SerializedName("plate_number")
    private String plateNumber;

    @SerializedName("state_id")
    private String stateId;

    @SerializedName("state")
    private String state;

    @SerializedName("email")
    private String email;

    @SerializedName("status")
    private String status;

    public void setUserName(String userName){
        this.userName = userName;
    }

    public String getUserName(){
        return userName;
    }

    public void setSearchReportCount(String searchReportCount){
        this.searchReportCount = searchReportCount;
    }

    public String getSearchReportCount(){
        return searchReportCount;
    }

    public void setAccessToken(String accessToken){
        this.accessToken = accessToken;
    }

    public String getAccessToken(){
        return accessToken;
    }

    public void setProfileImage(String profileImage){
        this.profileImage = profileImage;
    }

    public String getProfileImage(){
        return profileImage;
    }

    public void setIsSocial(String isSocial){
        this.isSocial = isSocial;
    }

    public String getIsSocial(){
        return isSocial;
    }

    public void setIsNotificationEnabled(String isNotificationEnabled){
        this.isNotificationEnabled = isNotificationEnabled;
    }

    public String getIsNotificationEnabled(){
        return isNotificationEnabled;
    }

    public void setUserId(String userId){
        this.userId = userId;
    }

    public String getUserId(){
        return userId;
    }

    public void setPhone(String phone){
        this.phone = phone;
    }

    public String getPhone(){
        return phone;
    }

    public void setPlateNumber(String plateNumber){
        this.plateNumber = plateNumber;
    }

    public String getPlateNumber(){
        return plateNumber;
    }

    public void setStateId(String stateId){
        this.stateId = stateId;
    }

    public String getStateId(){
        return stateId;
    }

    public void setState(String state){
        this.state = state;
    }

    public String getState(){
        return state;
    }

    public void setEmail(String email){
        this.email = email;
    }

    public String getEmail(){
        return email;
    }

    public void setStatus(String status){
        this.status = status;
    }

    public String getStatus(){
        return status;
    }
}

}
</code>```

My Layout

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:background="#e9edf6"
    android:scrollbars="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    <com.mikhaellopez.circularimageview.CircularImageView
        android:id="@+id/userProfilePic"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:layout_width="150dp"
        android:layout_height="150dp"
        />

        <TextView
            android:id="@+id/userName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyNameText"
            android:layout_marginTop="50dp"
            />

        <TextView
            android:id="@+id/userID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyUserIDText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/emailID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyEmailText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userStatus"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyStatusText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userPlateNum"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyPlateNumText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userStateName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyStateNameText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userStateID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyStateIDText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userSearchReportCount"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummySearchReportCountText"
            android:layout_marginTop="20dp"
            />

    </LinearLayout>
</ScrollView>
</code>```

My MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

List emList=new ArrayList();

List dataList=new ArrayList();

List userDets=new ArrayList();

ImageView proImg;
TextView userName;
TextView userID;
TextView userEmail;
TextView userStatus;
TextView userPlateNum;
TextView userStateName;
TextView userStateID;
TextView userSearchReportCount;

String img;
String name;
String idUser;
String emailID;
String status;
String plateNum;
String stateName;
String stateID;
String searchReportCount;

String email;

Login login;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    emList.add(email);

    userName=findViewById(R.id.userName);

    email=getIntent().getStringExtra("email");

     login=ApiUtils.getLoginClass();

    getUserData();
}

private void getUserData(){
    Call<List> call=login.getUserDetails();

    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            if(response.isSuccessful()){
                List resObj=(List)response.body();

                for(int i=0;i<resObj.size();i++){
                    Log.e("data",resObj.get(i).toString());
                }
 }
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
        }
    });
}
</code>```

}

I don't know what to write in the onResponse() method.

答:
change the for loop. </p>

```<code>List<DataItem>  items = resObj.getData();
    for(int i=0;i<items.size();i++){
        Log.e("data",items.get(i).getUserName()); // like this you can access other values in the items list
    }
</code>```

Title: Get Data from API using retrofit

Body:
I need to get the details from the API and display them in textviews.

Here's my API in JSON format  : https://imgur.com/a/WI98ymx

I need to get the data like username, user image, user phone number etc in Strings and display them in textviews.
How do i request all the fields and show the list in different textviews?

Here's my Login interface

package com.example.hb.loginapi;

import java.util.List;

   import retrofit2.Call;
   import retrofit2.http.GET;

  import retrofit2.http.POST;

   import retrofit2.http.Query;

    interface Login {

   @POST("user_login_v1")
   Call<ResObj>  loginInfo(@Query("password") String password,
   @Query("email") String email);

   @GET("user_login_v1")
   Call<List> getUserDetails();

}

Here's my ResObj class

package com.example.hb.loginapi;

import com.google.gson.annotations.SerializedName;
import java.util.List;

 public class ResObj {

@SerializedName("settings")
private Settings settings;

@SerializedName("data")
private List<DataItem> data;

public void setSettings(Settings settings){
    this.settings = settings;
}

public Settings getSettings(){
    return settings;
}

public void setData(List<DataItem> data){
    this.data = data;
}

public List<DataItem> getData(){
    return data;
}

public class Settings {

    @SerializedName("success")
    private String success;

    @SerializedName("message")
    private String message;

    @SerializedName("fields")
    private List<String> fields;

    public void setSuccess(String success) {
        this.success = success;
    }

    public String getSuccess() {
        return success;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setFields(List<String> fields) {
        this.fields = fields;
    }

    public List<String> getFields() {
        return fields;
    }
}

public class DataItem{

    @SerializedName("user_name")
    private String userName;

    @SerializedName("search_report_count")
    private String searchReportCount;

    @SerializedName("access_token")
    private String accessToken;

    @SerializedName("profile_image")
    private String profileImage;

    @SerializedName("is_social")
    private String isSocial;

    @SerializedName("is_notification_enabled")
    private String isNotificationEnabled;

    @SerializedName("user_id")
    private String userId;

    @SerializedName("phone")
    private String phone;

    @SerializedName("plate_number")
    private String plateNumber;

    @SerializedName("state_id")
    private String stateId;

    @SerializedName("state")
    private String state;

    @SerializedName("email")
    private String email;

    @SerializedName("status")
    private String status;

    public void setUserName(String userName){
        this.userName = userName;
    }

    public String getUserName(){
        return userName;
    }

    public void setSearchReportCount(String searchReportCount){
        this.searchReportCount = searchReportCount;
    }

    public String getSearchReportCount(){
        return searchReportCount;
    }

    public void setAccessToken(String accessToken){
        this.accessToken = accessToken;
    }

    public String getAccessToken(){
        return accessToken;
    }

    public void setProfileImage(String profileImage){
        this.profileImage = profileImage;
    }

    public String getProfileImage(){
        return profileImage;
    }

    public void setIsSocial(String isSocial){
        this.isSocial = isSocial;
    }

    public String getIsSocial(){
        return isSocial;
    }

    public void setIsNotificationEnabled(String isNotificationEnabled){
        this.isNotificationEnabled = isNotificationEnabled;
    }

    public String getIsNotificationEnabled(){
        return isNotificationEnabled;
    }

    public void setUserId(String userId){
        this.userId = userId;
    }

    public String getUserId(){
        return userId;
    }

    public void setPhone(String phone){
        this.phone = phone;
    }

    public String getPhone(){
        return phone;
    }

    public void setPlateNumber(String plateNumber){
        this.plateNumber = plateNumber;
    }

    public String getPlateNumber(){
        return plateNumber;
    }

    public void setStateId(String stateId){
        this.stateId = stateId;
    }

    public String getStateId(){
        return stateId;
    }

    public void setState(String state){
        this.state = state;
    }

    public String getState(){
        return state;
    }

    public void setEmail(String email){
        this.email = email;
    }

    public String getEmail(){
        return email;
    }

    public void setStatus(String status){
        this.status = status;
    }

    public String getStatus(){
        return status;
    }
}

}

My Layout

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:background="#e9edf6"
    android:scrollbars="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    <com.mikhaellopez.circularimageview.CircularImageView
        android:id="@+id/userProfilePic"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:layout_width="150dp"
        android:layout_height="150dp"
        />

        <TextView
            android:id="@+id/userName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyNameText"
            android:layout_marginTop="50dp"
            />

        <TextView
            android:id="@+id/userID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyUserIDText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/emailID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyEmailText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userStatus"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyStatusText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userPlateNum"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyPlateNumText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userStateName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyStateNameText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userStateID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummyStateIDText"
            android:layout_marginTop="20dp"
            />

        <TextView
            android:id="@+id/userSearchReportCount"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/fnavyblue"
            android:textSize="20sp"
            android:text="DummySearchReportCountText"
            android:layout_marginTop="20dp"
            />

    </LinearLayout>
</ScrollView>

My MainActivity.java

public class MainActivity extends AppCompatActivity {

List emList=new ArrayList();

List dataList=new ArrayList();

List userDets=new ArrayList();

ImageView proImg;
TextView userName;
TextView userID;
TextView userEmail;
TextView userStatus;
TextView userPlateNum;
TextView userStateName;
TextView userStateID;
TextView userSearchReportCount;

String img;
String name;
String idUser;
String emailID;
String status;
String plateNum;
String stateName;
String stateID;
String searchReportCount;

String email;

Login login;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    emList.add(email);

    userName=findViewById(R.id.userName);

    email=getIntent().getStringExtra("email");

     login=ApiUtils.getLoginClass();

    getUserData();
}

private void getUserData(){
    Call<List> call=login.getUserDetails();

    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            if(response.isSuccessful()){
                List resObj=(List)response.body();

                for(int i=0;i<resObj.size();i++){
                    Log.e("data",resObj.get(i).toString());
                }
 }
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();
        }
    });
}

}

I don't know what to write in the onResponse() method.

Body:
change the for loop.

List<DataItem>  items = resObj.getData();
    for(int i=0;i<items.size();i++){
        Log.e("data",items.get(i).getUserName()); // like this you can access other values in the items list
    }


来源: stackexchange

问:
RxSwift table view with multiple custom cell types
I'w wonder is there any code example for RxSwift when I can use multiple custom cells inside one table view. So for example I have two section and first section has 10 cells with type CellWithImage identifier and second section has 10 cells with type CellWithVideo identifier.

All tuts and code examples which I've founded are using only one cell type, for instance RxSwiftTableViewExample

Thanks for any help

答:
You can set multiple custom cell without RxDatasource.</p>

```<code>    //Register Cells as you want
    tableView.register(CustomRxTableViewCell.self, forCellReuseIdentifier: "Cell")
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "BasicCell")

    ViewModel.data.bind(to: tableView.rx.items){(tv, row, item) -> UITableViewCell in

        if row == 0 {
            let cell = tv.dequeueReusableCell(withIdentifier: "BasicCell", for: IndexPath.init(row: row, section: 0))

            cell.textLabel?.text = item.birthday
            return cell
        }else{
            let cell = tv.dequeueReusableCell(withIdentifier: "Cell", for: IndexPath.init(row: row, section: 0)) as! CustomRxTableViewCell
            cell.titleLb.text = item.name
            return cell
        }

    }.disposed(by: disposeBag)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can set multiple custom cell without RxDatasource.

    //Register Cells as you want
    tableView.register(CustomRxTableViewCell.self, forCellReuseIdentifier: "Cell")
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "BasicCell")

    ViewModel.data.bind(to: tableView.rx.items){(tv, row, item) -> UITableViewCell in

        if row == 0 {
            let cell = tv.dequeueReusableCell(withIdentifier: "BasicCell", for: IndexPath.init(row: row, section: 0))

            cell.textLabel?.text = item.birthday
            return cell
        }else{
            let cell = tv.dequeueReusableCell(withIdentifier: "Cell", for: IndexPath.init(row: row, section: 0)) as! CustomRxTableViewCell
            cell.titleLb.text = item.name
            return cell
        }

    }.disposed(by: disposeBag)

ContentLicense: CC BY-SA 4.0


问:
Why WebJars are not extracted into a lib folder
According to the documentation,webjars are automatically extracted by Play into a lib folder relative to the our public assets, but after installing bootstrap from webjars, I still have no lib folder. No lib folder under /public, no lib folder under /target.

I am having this compilation error:

```<code>not found: value lib
<link rel="stylesheet" href="@routes.Assets.at(lib/bootstrap/css/bootstrap.css)">
</code>```

I am certainly doing something wrong.

This is my routes file:

```<code>GET     /                           controllers.HomeController.index

GET     /assets/*file               controllers.Assets.at(path="/public", file)
</code>```

This is my build.sbt file:

```<code>name := "contact-manager"

version := "0.1"

scalaVersion := "2.12.8"

libraryDependencies ++= Seq(
  guice,
  "org.webjars" % "bootstrap" % "3.3.6",
  "org.webjars" % "jquery" % "3.3.1"
)

enablePlugins(PlayScala)
</code>```

Any idea ?

答: You are missing qoutes around lib/bootstrap/..., since Assets.at() takes a string as argument. In your code lib is a variable and thus comes the message not found: value lib.

Body:
According to the documentation,webjars are automatically extracted by Play into a lib folder relative to the our public assets, but after installing bootstrap from webjars, I still have no lib folder. No lib folder under /public, no lib folder under /target.

I am having this compilation error:

not found: value lib
<link rel="stylesheet" href="@routes.Assets.at(lib/bootstrap/css/bootstrap.css)">

I am certainly doing something wrong.

This is my routes file:

GET     /                           controllers.HomeController.index

GET     /assets/*file               controllers.Assets.at(path="/public", file)

This is my build.sbt file:

name := "contact-manager"

version := "0.1"

scalaVersion := "2.12.8"

libraryDependencies ++= Seq(
  guice,
  "org.webjars" % "bootstrap" % "3.3.6",
  "org.webjars" % "jquery" % "3.3.1"
)

enablePlugins(PlayScala)

Any idea ?


问:
Inserting only unique values in objectbox entity
Is there something similar to this: @Insert(onConflict = OnConflictStrategy.REPLACE) as found in Room database that you can do in Objectbox.  If not, how can you avoid saving duplicate entries in an objectbox entity?  Thanks.</p>

答:
in object box DataModel class, make the item anotation

@unique
  Public String userID;

```<code>private Box<User> userBox;
userBox = ObjectBox.get().boxFor(User.class);

//your inserted object

if (!userBox.getAll().contains(insertedObject)){
                        leadBoxForLeadOpions.put(l);
                    }
</code>```

Body:
in object box DataModel class, make the item anotation

@unique
  Public String userID;

private Box<User> userBox;
userBox = ObjectBox.get().boxFor(User.class);

//your inserted object

if (!userBox.getAll().contains(insertedObject)){
                        leadBoxForLeadOpions.put(l);
                    }


问:
Grid lines in secondary y axis in Power Bi
I am using a line and clustered column chart in Power Bi in which I have a dual y-axis. I need grid lines for the secondary y-axis, i.e. the y-axis with the line value. </p>

<p>In Power Bi, for the primary y-axis we can just turn on the grid lines option to get the grid lines, but there's no option for the secondary y-axis. Is there any R script or any internal Power Bi option to enable this? </p>

答:
I don't really get the question.

PowerBI creates gridlines automatically and they are a different thing than the Y axis labels.

So I think you most likely want, is to turn off primary Y axis labels and keep secondary Y-axis labels on? First, why would you do that? It' going to be confusing for the end users.

Secondly, PowerBI does not support it natively (more specifically, I am not aware of that functionality), but there might be a workaround using different colors:

Set primary Y axis label to white (or same as your background) and secondary Y-axis label to black.
The output might look like this:

There are custom R visuals available, so I suppose you could write some code, but is it really worth it?

Body:
I am using a line and clustered column chart in Power Bi in which I have a dual y-axis. I need grid lines for the secondary y-axis, i.e. the y-axis with the line value.

In Power Bi, for the primary y-axis we can just turn on the grid lines option to get the grid lines, but there's no option for the secondary y-axis. Is there any R script or any internal Power Bi option to enable this?


问:
Finding the true anomaly from state vectors
I'm attempting to convert from state vectors (position and speed) into Kepler elements, however I'm running into problems where a negative velocity or position will give me wrong results when trying to calculate true anomaly.

Here are the different ways I'm trying to calculate the True Anomaly:

```<code>/// <summary>
/// https://en.wikipedia.org/wiki/True_anomaly#From_state_vectors
/// </summary>
public static double TrueAnomaly(Vector4 eccentVector, Vector4 position, Vector4 velocity)
{
    var dotEccPos = Vector4.Dot(eccentVector, position);
    var talen = eccentVector.Length() * position.Length();
    talen = dotEccPos / talen;
    talen = GMath.Clamp(talen, -1, 1);
    var trueAnomoly = Math.Acos(talen);

    if (Vector4.Dot(position, velocity) < 0)
        trueAnomoly = Math.PI * 2 - trueAnomoly;

    return trueAnomoly;
}
</code>```

```<code>//sgp = standard gravitational parameter
public static double TrueAnomaly(double sgp, Vector4 position, Vector4 velocity)
{
    var H = Vector4.Cross(position, velocity).Length();
    var R = position.Length();
    var q = Vector4.Dot(position, velocity);  // dot product of r*v
    var TAx = H * H / (R * sgp) - 1;
    var TAy = H * q / (R * sgp);
    var TA = Math.Atan2(TAy, TAx);
    return TA;
}
</code>```

```<code>public static double TrueAnomalyFromEccentricAnomaly(double eccentricity, double eccentricAnomaly)
{
    var x = Math.Sqrt(1 - Math.Pow(eccentricity, 2)) * Math.Sin(eccentricAnomaly);
    var y = Math.Cos(eccentricAnomaly) - eccentricity;
    return Math.Atan2(x, y);
}
</code>```

```<code>public static double TrueAnomalyFromEccentricAnomaly2(double eccentricity, double eccentricAnomaly)
{
    var x = Math.Cos(eccentricAnomaly) - eccentricity;
    var y = 1 - eccentricity * Math.Cos(eccentricAnomaly);
    return Math.Acos(x / y);
}
</code>```

Edit: another way of doing it which Spectre pointed out:

```<code>public static double TrueAnomaly(Vector4 position, double loP)
{
    return Math.Atan2(position.Y, position.X) - loP;
}
</code>```

Positions are all relative to the parent body.

These functions all agree if position.x, position.y and velocity.y are all positive.
How do I fix these so that I get a consistent results when position and velocity are negitive?

Just to clarify: My angles appear to be sort of correct, just pointing in the wrong quadrant depending on the position and or velocity vectors.

Yeah so I was wrong, the above all do return the correct values after all.

So I found an edge case where most of the above calculations fail.
Given position and velocity:

```<code>pos = new Vector4() { X = -0.208994076275941, Y = 0.955838328099748 };
vel = new Vector4() { X = -2.1678187689294E-07, Y = -7.93096769486992E-08 };
</code>```

I get some odd results, ie ~ -31.1 degrees, when I think it should return ` 31.1 (non negative). one of them returns ~ 328.8.

However testing with this position and velocity the results apear to be ok:

```<code>pos = new Vector4() { X = -0.25, Y = 0.25 };
vel = new Vector4() { X = Distance.KmToAU(-25), Y = Distance.KmToAU(-25) };
</code>```

See my answer for extra code on how I'm testing and the math I'm using for some of the other variables.

I'm going around in circles on this one. this is a result of a bug in my existing code that shows up under some conditions but not others.
I guess the real question now is WHY am I getting different results with position/velocity above that don't match to my expectations or each other?

答:
Assuming 2D case... I am doing this differently:

compute radius of semi axises and rotation

so you need to remember whole orbit and find 2 most distant points on it that is major axis a. The minor axis b usually is 90 deg from major axis but to be sure just fins 2 perpendicularly most distant points on your orbit to major axis. So now you got both semi axises. The initial rotation is computed from the major axis by atan2.

compute true anomaly E

so if center is x0,y0 (intersection of a,b or center point of both) initial rotation is ang0 (angle of a) and your point on orbit is x,y then:

```<code>E = atan2(y-y0,x-x0) - ang0
</code>```

However in order to match Newton/D'Alembert physics to Kepler orbital parameters you need to boost the integration precision like I did here:

Is it possible to make realistic n-body solar system simulation in matter of size and mass?

see the [Edit3] Improving Newton D'ALembert integration precision even more in there.

For more info and equations see:

Solving Kepler's equation

[Edit1] so you want to compute V I see it like this:

As you got your coordinates relative to parent you can assume they are already in focal point centered so no need for x0,y0 anymore. Of coarse if you want high precision and have more than 2 bodies (focal mass + object + proximity object(s) like moons) then the parent mass will no longer be in focal point of orbit but close to it ... and to remedy you need to use real focal point position so x0,y0 again... So how to do it:

compute center point (cx,cy) and a,b semi axises

so its the same as in previous text.

compute focal point (x0,y0) in orbit axis aligned coordinates

simple:

```<code>x0 = cx + sqrt( a^2 + b^2 );
y0 = cy;
</code>```

initial angle ang0 of a

let xa,ya be the intersection of orbit and major axis a on the side with bigger speeds (near parent object focus). Then:

```<code>ang0 = atan2( ya-cy , xa-cx );
</code>```

and finally the V fore any of yours x,y

```<code>V = atan2( y-y0 , x-x0 ) - ang0;
</code>```

Body:
I'm attempting to convert from state vectors (position and speed) into Kepler elements, however I'm running into problems where a negative velocity or position will give me wrong results when trying to calculate true anomaly.

Here are the different ways I'm trying to calculate the True Anomaly:

///
/// https://en.wikipedia.org/wiki/True_anomaly#From_state_vectors
///
public static double TrueAnomaly(Vector4 eccentVector, Vector4 position, Vector4 velocity)
{
    var dotEccPos = Vector4.Dot(eccentVector, position);
    var talen = eccentVector.Length() * position.Length();
    talen = dotEccPos / talen;
    talen = GMath.Clamp(talen, -1, 1);
    var trueAnomoly = Math.Acos(talen);

    if (Vector4.Dot(position, velocity) < 0)
        trueAnomoly = Math.PI * 2 - trueAnomoly;

    return trueAnomoly;
}

//sgp = standard gravitational parameter
public static double TrueAnomaly(double sgp, Vector4 position, Vector4 velocity)
{
    var H = Vector4.Cross(position, velocity).Length();
    var R = position.Length();
    var q = Vector4.Dot(position, velocity);  // dot product of r*v
    var TAx = H * H / (R * sgp) - 1;
    var TAy = H * q / (R * sgp);
    var TA = Math.Atan2(TAy, TAx);
    return TA;
}

public static double TrueAnomalyFromEccentricAnomaly(double eccentricity, double eccentricAnomaly)
{
    var x = Math.Sqrt(1 - Math.Pow(eccentricity, 2)) * Math.Sin(eccentricAnomaly);
    var y = Math.Cos(eccentricAnomaly) - eccentricity;
    return Math.Atan2(x, y);
}

public static double TrueAnomalyFromEccentricAnomaly2(double eccentricity, double eccentricAnomaly)
{
    var x = Math.Cos(eccentricAnomaly) - eccentricity;
    var y = 1 - eccentricity * Math.Cos(eccentricAnomaly);
    return Math.Acos(x / y);
}

Edit: another way of doing it which Spectre pointed out:

public static double TrueAnomaly(Vector4 position, double loP)
{
    return Math.Atan2(position.Y, position.X) - loP;
}

Positions are all relative to the parent body.

These functions all agree if position.x, position.y and velocity.y are all positive.
How do I fix these so that I get a consistent results when position and velocity are negitive?

Just to clarify: My angles appear to be sort of correct, just pointing in the wrong quadrant depending on the position and or velocity vectors.

Yeah so I was wrong, the above all do return the correct values after all.

So I found an edge case where most of the above calculations fail.
Given position and velocity:

pos = new Vector4() { X = -0.208994076275941, Y = 0.955838328099748 };
vel = new Vector4() { X = -2.1678187689294E-07, Y = -7.93096769486992E-08 };

I get some odd results, ie ~ -31.1 degrees, when I think it should return ` 31.1 (non negative). one of them returns ~ 328.8.

However testing with this position and velocity the results apear to be ok:

pos = new Vector4() { X = -0.25, Y = 0.25 };
vel = new Vector4() { X = Distance.KmToAU(-25), Y = Distance.KmToAU(-25) };

See my answer for extra code on how I'm testing and the math I'm using for some of the other variables.

I'm going around in circles on this one. this is a result of a bug in my existing code that shows up under some conditions but not others.
I guess the real question now is WHY am I getting different results with position/velocity above that don't match to my expectations or each other?

Body:
Assuming 2D case... I am doing this differently:

compute radius of semi axises and rotation

so you need to remember whole orbit and find 2 most distant points on it that is major axis a. The minor axis b usually is 90 deg from major axis but to be sure just fins 2 perpendicularly most distant points on your orbit to major axis. So now you got both semi axises. The initial rotation is computed from the major axis by atan2.

compute true anomaly E

so if center is x0,y0 (intersection of a,b or center point of both) initial rotation is ang0 (angle of a) and your point on orbit is x,y then:

E = atan2(y-y0,x-x0) - ang0

However in order to match Newton/D'Alembert physics to Kepler orbital parameters you need to boost the integration precision like I did here:

Is it possible to make realistic n-body solar system simulation in matter of size and mass?

see the [Edit3] Improving Newton D'ALembert integration precision even more in there.

For more info and equations see:

Solving Kepler's equation

[Edit1] so you want to compute V I see it like this:

As you got your coordinates relative to parent you can assume they are already in focal point centered so no need for x0,y0 anymore. Of coarse if you want high precision and have more than 2 bodies (focal mass + object + proximity object(s) like moons) then the parent mass will no longer be in focal point of orbit but close to it ... and to remedy you need to use real focal point position so x0,y0 again... So how to do it:

compute center point (cx,cy) and a,b semi axises

so its the same as in previous text.

compute focal point (x0,y0) in orbit axis aligned coordinates

simple:

x0 = cx + sqrt( a^2 + b^2 );
y0 = cy;

initial angle ang0 of a

let xa,ya be the intersection of orbit and major axis a on the side with bigger speeds (near parent object focus). Then:

ang0 = atan2( ya-cy , xa-cx );

and finally the V fore any of yours x,y

V = atan2( y-y0 , x-x0 ) - ang0;


问:
How to update user data in MongoDB using node.js
I have a simple express app with MongoDB connection where I can register a user. Registering and logging in and out works fine but now I'm trying to add possibility to edit user data. My code doesn't throw any errors but it doesn't update the data in database neither.

I've tried to read the MongoDB documentation and similar problems from stackoverflow. But I just can't seem to get it work.

This is my route for update:

```<code>    User.updateOne({ id: req.session.passport.user}, {
        name: req.body.name,
        email: req.body.email,
        password: req.body.password
    }, function (err, user){
        if (err) return next(err);
        User.findById(req.user._id, function(err, user) {
            if (err) return next(err);
            return res.render('user', {
            name: user.name,
            email: user.email
        });
    });
});
});
</code>```

I expect it to update my database data but it just renders the user -page and nothing else happens.

EDIT.
Thank you for your answers, I tried those but it still just goes through but nothing happens in database.
I've also tried to make the edit work based on how I handle the registration and I actually got it to save the data but my problem with this solution is that it doesn't hash the password, it is saved as a string in my db. With registration hashing works fine. I also need to do the email validation somehow else because now it requires it to be changed every time I edit my data. Here's the code:

```<code>router.post('/update/:name', ensureAuthenticated, function(req, res, next){
  const { name, email, password, password2 } = req.body;
  let errors = [];

  //check required fields
  if (!name || !email || !password || !password2) {
    errors.push({ msg: 'Please fill in all fields' });
  }

  //check passwords match
  if (password !== password2) {
    errors.push({ msg: 'Passwords do not match' });
  }

  //check pass length
  if (password.length < 6) {
    errors.push({ msg: 'Password should be at least 6 characters' });
  }

  if (errors.length > 0) {
    res.render('update', {
      errors,
      name,
      email,
      password,
      password2
    });
  } else {
    //validation passed
    User.updateOne({ name: name, email: email, password: password })
      .then(user => {
        if (user) {
          //user exists
          errors.push({ msg: 'Email is already registered'});
          res.render('update', {
            errors,
            name,
            email,
            password,
            password2
          });
        } else {
          const updateUser = new User({
            name,
            email,
            password
          });

          //Hash password
          bcrypt.genSalt(10, (err, salt) =>
            bcrypt.hash(updateUser.password, salt, (err, hash) => {
              if (err) throw err;
              //set password to hashed
              updateUser.password = hash;
              //save user
              updateUser
                .save()
                .then(user => {
                  req.flash('success_msg', 'Info updatet, log in');
                  res.redirect('/users/login');
                })
                .catch(err => console.log(err));
          }));
        }
      });
  }
});
</code>```

答:
Use findByIdAndUpdate in this case is better

```<code>User.findByIdAndUpdate(req.session.passport.user,
{
   $set : {
        name: req.body.name,
        email: req.body.email,
        password: req.body.password
    }
},
(err, user) => {
     // Some handle
   }
);
</code>```

Body:
I have a simple express app with MongoDB connection where I can register a user. Registering and logging in and out works fine but now I'm trying to add possibility to edit user data. My code doesn't throw any errors but it doesn't update the data in database neither.

I've tried to read the MongoDB documentation and similar problems from stackoverflow. But I just can't seem to get it work.

This is my route for update:

    User.updateOne({ id: req.session.passport.user}, {
        name: req.body.name,
        email: req.body.email,
        password: req.body.password
    }, function (err, user){
        if (err) return next(err);
        User.findById(req.user._id, function(err, user) {
            if (err) return next(err);
            return res.render('user', {
            name: user.name,
            email: user.email
        });
    });
});
});

I expect it to update my database data but it just renders the user -page and nothing else happens.

EDIT.
Thank you for your answers, I tried those but it still just goes through but nothing happens in database.
I've also tried to make the edit work based on how I handle the registration and I actually got it to save the data but my problem with this solution is that it doesn't hash the password, it is saved as a string in my db. With registration hashing works fine. I also need to do the email validation somehow else because now it requires it to be changed every time I edit my data. Here's the code:

router.post('/update/:name', ensureAuthenticated, function(req, res, next){
  const { name, email, password, password2 } = req.body;
  let errors = [];

  //check required fields
  if (!name || !email || !password || !password2) {
    errors.push({ msg: 'Please fill in all fields' });
  }

  //check passwords match
  if (password !== password2) {
    errors.push({ msg: 'Passwords do not match' });
  }

  //check pass length
  if (password.length < 6) {
    errors.push({ msg: 'Password should be at least 6 characters' });
  }

  if (errors.length > 0) {
    res.render('update', {
      errors,
      name,
      email,
      password,
      password2
    });
  } else {
    //validation passed
    User.updateOne({ name: name, email: email, password: password })
      .then(user => {
        if (user) {
          //user exists
          errors.push({ msg: 'Email is already registered'});
          res.render('update', {
            errors,
            name,
            email,
            password,
            password2
          });
        } else {
          const updateUser = new User({
            name,
            email,
            password
          });

          //Hash password
          bcrypt.genSalt(10, (err, salt) =>
            bcrypt.hash(updateUser.password, salt, (err, hash) => {
              if (err) throw err;
              //set password to hashed
              updateUser.password = hash;
              //save user
              updateUser
                .save()
                .then(user => {
                  req.flash('success_msg', 'Info updatet, log in');
                  res.redirect('/users/login');
                })
                .catch(err => console.log(err));
          }));
        }
      });
  }
});

Body:
Use findByIdAndUpdate in this case is better

User.findByIdAndUpdate(req.session.passport.user,
{
   $set : {
        name: req.body.name,
        email: req.body.email,
        password: req.body.password
    }
},
(err, user) => {
     // Some handle
   }
);


问:
Why does my custom checkbox not correctly propagate change value if I set the type after view init?
I am writing some wrappers for normal form controls in my angular app by writing components / directives that have selectors like 'input[custom-input]'. By doing that I am able to setup public methods that can later be used when doing content projection.

My Html then looks like

```<code><a-component-that-handles-animating-placeholder-etc>
    <input custom-checkbox formControlName="field"/>
</<a-component-that-handles-animating-placeholder-etc>
</code>```

The advantage here is that the input is available directly to any component that might want to use it, whereas if I wrote a wrapper I would have to implement a pipeline for every functionality such as disabled e.g

```<code><custom-input [disabled]="isDisabled"]></custom-input>
</code>```

Another advantage is that I do not have to implement new custom control value accessors to bind formcontrolName on and make the framework happy, when in reality the implementation of custom-input would be to just internally use input, which for every control adds a lot of complexity to the project.

The problem is that the reactive form control is not being updated with the correct value when the checkbox is checked and unchecked. In my custom component with this selector input[custom-checkbox] I am doing this logic:

```<code>  ngAfterViewInit(): void {
    this.renderer.setAttribute(this.el.nativeElement, 'type', 'checkbox');
  }
</code>```

Thats because I dont want consumers to have to specify that this element is a checkbox twice like so:

```<code><input type="checkbox" custom-checkbox/>
</code>```

But for some reason setting the type after the render is breaking the event that updated the form control. I have no idea why.

EDIT: I forked one of the stackblitz and replicated my problem.
https://stackblitz.com/edit/angular-dzqp4k

答:
You don't even to go though that pain.

Simply use HostBinding to bind on attr.type, and on init, set it to checkbox.

Stackblitz Demo

```<code>export class InputSelectorDirective {

  @HostBinding('attr.type') inputType: string;

  constructor(
    private R: Renderer2,
    private elRef: ElementRef<HTMLInputElement>
  ) { }

  ngOnInit() {
    this.inputType = "checkbox";
  }
}
</code>```

Body:
I am writing some wrappers for normal form controls in my angular app by writing components / directives that have selectors like 'input[custom-input]'. By doing that I am able to setup public methods that can later be used when doing content projection.

My Html then looks like

    <input custom-checkbox formControlName="field"/>
</

The advantage here is that the input is available directly to any component that might want to use it, whereas if I wrote a wrapper I would have to implement a pipeline for every functionality such as disabled e.g

<custom-input [disabled]="isDisabled"]></custom-input>

Another advantage is that I do not have to implement new custom control value accessors to bind formcontrolName on and make the framework happy, when in reality the implementation of custom-input would be to just internally use input, which for every control adds a lot of complexity to the project.

The problem is that the reactive form control is not being updated with the correct value when the checkbox is checked and unchecked. In my custom component with this selector input[custom-checkbox] I am doing this logic:

  ngAfterViewInit(): void {
    this.renderer.setAttribute(this.el.nativeElement, 'type', 'checkbox');
  }

Thats because I dont want consumers to have to specify that this element is a checkbox twice like so:

<input type="checkbox" custom-checkbox/>

But for some reason setting the type after the render is breaking the event that updated the form control. I have no idea why.

EDIT: I forked one of the stackblitz and replicated my problem.
https://stackblitz.com/edit/angular-dzqp4k

Body:
You don't even to go though that pain.

Simply use HostBinding to bind on attr.type, and on init, set it to checkbox.

Stackblitz Demo

export class InputSelectorDirective {

  @HostBinding('attr.type') inputType: string;

  constructor(
    private R: Renderer2,
    private elRef: ElementRef<HTMLInputElement>
  ) { }

  ngOnInit() {
    this.inputType = "checkbox";
  }
}


问:
Docker compose, running containers in net:host
I want to spawn 3 services in the "host" net using docker-compose. Here is my docker-compose.yml file:

```<code>version: '2'
services:
  mysql:
    image: mysql
    net: "host"
  nginx:
    image: nginx
    net: "host"
  app:
    image: tomcat
    net: "host"
</code>```

I got the following error:

```<code>$ docker-compose up
[31mERROR[0m: Validation failed in file '.\docker-compose.yml', reason(s):
Unsupported config option for services.app: 'net'
Unsupported config option for services.mysql: 'net'
Unsupported config option for services.nginx: 'net'
</code>```

I'm using boot2docker on windows.

Docker, and Docker-compose version:

```<code>$ docker -v
Docker version 1.10.2, build c3959b1
$ docker-compose -version
docker-compose version 1.6.0, build cdb920a
</code>```

If I run all services manually by using docker run --net = "host" everything is working fine.

In the documentation I read that net command is supported in docker-compose:

net

Networking mode. Use the same values as the docker client --net parameter.

net: "bridge"

net: "none"

net: "container:[name or id]"

net: "host"

https://docs.docker.com/v1.6/compose/yml/#net

What am I doing wrong?

答:
you can try just add

```<code>network_mode: "host"
</code>```

example :

```<code>version: '2'
services:
  feedx:
    build: web
    ports:
    - "127.0.0.1:8000:8000"
    network_mode: "host"
</code>```

list option available

```<code>network_mode: "bridge"
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
network_mode: "container:[container name/id]"
</code>```

https://docs.docker.com/compose/compose-file/#network_mode

Body:
I want to spawn 3 services in the "host" net using docker-compose. Here is my docker-compose.yml file:

version: '2'
services:
  mysql:
    image: mysql
    net: "host"
  nginx:
    image: nginx
    net: "host"
  app:
    image: tomcat
    net: "host"

I got the following error:

$ docker-compose up
[31mERROR[0m: Validation failed in file '.\docker-compose.yml', reason(s):
Unsupported config option for services.app: 'net'
Unsupported config option for services.mysql: 'net'
Unsupported config option for services.nginx: 'net'

I'm using boot2docker on windows.

Docker, and Docker-compose version:

$ docker -v
Docker version 1.10.2, build c3959b1
$ docker-compose -version
docker-compose version 1.6.0, build cdb920a

If I run all services manually by using docker run --net = "host" everything is working fine.

In the documentation I read that net command is supported in docker-compose:

net

Networking mode. Use the same values as the docker client --net parameter.

net: "bridge"

net: "none"

net: "container:[name or id]"

net: "host"

https://docs.docker.com/v1.6/compose/yml/#net

What am I doing wrong?

Body:
you can try just add

network_mode: "host"

example :

version: '2'
services:
  feedx:
    build: web
    ports:
    - "127.0.0.1:8000:8000"
    network_mode: "host"

list option available

network_mode: "bridge"
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
network_mode: "container:[container name/id]"

https://docs.docker.com/compose/compose-file/#network_mode


问:
I'm using python to webscrape all the "a" tags on a website. And in the "a" tag I want to pick some words and store them
The link tag "a" has following text : "Mino Games (YC W11) Is Hiring Senior Engineers in Montreal, QC (workable.com)"

I want to store the "Mino Games" , "Senior Engineer"  , "Montreal" and "workable.com" in sqlite3.

Please suggest, how can I do it.

答:
Assuming you're scraping https://news.ycombinator.com/jobs, this this should work:

```<code>import re, sqlite3

conn = sqlite3.connect('jobs.db')
c = conn.cursor()
c.execute('''CREATE TABLE jobs
         (company text, position text, location text, source real)''')

company_pattern = re.compile(r'(.+)(hiring|looking|wants|is )', re.IGNORECASE)
source_pattern = re.compile(r'\(([^)]+)\)$')
location_pattern = re.compile(r'in (.*)|(remote)', re.IGNORECASE)
position_pattern = re.compile(r'(?:hiring|looking|wants) (.*)', re.IGNORECASE)
clean_up_pattern = re.compile(r'\(([^)]+)\)| is | for | in |a ', re.IGNORECASE)

# Load up <a> nodes into elements here

for element in elements:
    element = element.text
    source = source_pattern.findall(element)[0].strip()
    element = element.replace('(' + source + ')', '')
    company = clean_up_pattern.sub('', company_pattern.findall(element)[0][0])
    try:
        location = location_pattern.findall(element)[0][0].strip()
    except IndexError:
        location = 'Not stated'
    element = element.replace(location, '')
    position = clean_up_pattern.sub('', position_pattern.findall(element)[0])

    c.execute("INSERT INTO jobs VALUES (company, position, location, source)")

conn.commit()
conn.close()
</code>```

This will parse around 80% of the job offerings there. Tweak the regular expressions if you need to capture more.

Body:
Assuming you're scraping https://news.ycombinator.com/jobs, this this should work:

import re, sqlite3

conn = sqlite3.connect('jobs.db')
c = conn.cursor()
c.execute('''CREATE TABLE jobs
         (company text, position text, location text, source real)''')

company_pattern = re.compile(r'(.+)(hiring|looking|wants|is )', re.IGNORECASE)
source_pattern = re.compile(r'\(([^)]+)\)$')
location_pattern = re.compile(r'in (.*)|(remote)', re.IGNORECASE)
position_pattern = re.compile(r'(?:hiring|looking|wants) (.*)', re.IGNORECASE)
clean_up_pattern = re.compile(r'\(([^)]+)\)| is | for | in |a ', re.IGNORECASE)

# Load up <a> nodes into elements here

for element in elements:
    element = element.text
    source = source_pattern.findall(element)[0].strip()
    element = element.replace('(' + source + ')', '')
    company = clean_up_pattern.sub('', company_pattern.findall(element)[0][0])
    try:
        location = location_pattern.findall(element)[0][0].strip()
    except IndexError:
        location = 'Not stated'
    element = element.replace(location, '')
    position = clean_up_pattern.sub('', position_pattern.findall(element)[0])

    c.execute("INSERT INTO jobs VALUES (company, position, location, source)")

conn.commit()
conn.close()

This will parse around 80% of the job offerings there. Tweak the regular expressions if you need to capture more.


问:
Ansible Tower: Send e-mail if the project failed
I would like to get a e-mail when the project failed. So I've created a task at the end of the file wich sends me an e-mail. The problem is now that when a task failed also the hole project failed and the e-mail task wouldn't triggered.

Can somebody help me?

(I'm using Ansible Tower)

答:
ansible tower itself provide this feature
you can create a notification template as described in
 https://docs.ansible.com/ansible-tower/3.0/html/userguide/notifications.html#id1

than from notification option of workflow template, you can select this template on failure or success


问:
How do I get an OAuth 2.0 authentication token in C#
I have these settings:

Auth URL (which happens to be a
"https://login.microsoftonline.com/...") if that helps.

Access Token URL "https://service.endpoint.com/api/oauth2/token"

ClientId "abc"

Clientsecret "123"

I then need to make a get call using a bearer token in the header.

I can get this to work in Postman, but have hit a wall trying to work out how to implement it in C#. I've been using RestSharp (but open to others). It all seems so opaque, when I thought it'd be pretty straight forward: it's a console app, so I don't need bells and whistles.

Ultimately, I want my app to (programatically) get a token, then use that for my subsequent calls. I'd appreciate anyone pointing me to documentation or examples, that explains what I'm after clearly. Everything I've come across is partial or for services operating on a different flow.

Thanks.

答:
Clearly:

Server side generating a token example

```<code>private string GenerateToken(string userName)
{
    var someClaims = new Claim[]{
        new Claim(JwtRegisteredClaimNames.UniqueName, userName),
        new Claim(JwtRegisteredClaimNames.Email, GetEmail(userName)),
        new Claim(JwtRegisteredClaimNames.NameId,Guid.NewGuid().ToString())
    };

    SecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Tokenizer.Key));
    var token = new JwtSecurityToken(
        issuer: _settings.Tokenizer.Issuer,
        audience: _settings.Tokenizer.Audience,
        claims: someClaims,
        expires: DateTime.Now.AddHours(_settings.Tokenizer.ExpiryHours),
        signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
    );

    return new JwtSecurityTokenHandler().WriteToken(token);
}
</code>```

(note: Tokenizer is my helper class that contains Issuer Audience etc..)

Definitely:

Client side getting a token for authentication

```<code>    public async Task<string> GetToken()
    {
        string token = "";
        var siteSettings = DependencyResolver.Current.GetService<SiteSettings>();

        var client = new HttpClient();
        client.BaseAddress = new Uri(siteSettings.PopularSearchRequest.StaticApiUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        StatisticUserModel user = new StatisticUserModel()
        {
            Password = siteSettings.PopularSearchRequest.Password,
            Username = siteSettings.PopularSearchRequest.Username
        };

        string jsonUser = JsonConvert.SerializeObject(user, Formatting.Indented);
        var stringContent = new StringContent(jsonUser, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(siteSettings.PopularSearchRequest.StaticApiUrl + "/api/token/new", stringContent);
        token = await response.Content.ReadAsStringAsync();

        return token;
    }
</code>```

You can use this token for the authorization (that is in the subsequent requests)

Body:
Clearly:

Server side generating a token example

private string GenerateToken(string userName)
{
    var someClaims = new Claim[]{
        new Claim(JwtRegisteredClaimNames.UniqueName, userName),
        new Claim(JwtRegisteredClaimNames.Email, GetEmail(userName)),
        new Claim(JwtRegisteredClaimNames.NameId,Guid.NewGuid().ToString())
    };

    SecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_settings.Tokenizer.Key));
    var token = new JwtSecurityToken(
        issuer: _settings.Tokenizer.Issuer,
        audience: _settings.Tokenizer.Audience,
        claims: someClaims,
        expires: DateTime.Now.AddHours(_settings.Tokenizer.ExpiryHours),
        signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
    );

    return new JwtSecurityTokenHandler().WriteToken(token);
}

(note: Tokenizer is my helper class that contains Issuer Audience etc..)

Definitely:

Client side getting a token for authentication

    public async Task<string> GetToken()
    {
        string token = "";
        var siteSettings = DependencyResolver.Current.GetService<SiteSettings>();

        var client = new HttpClient();
        client.BaseAddress = new Uri(siteSettings.PopularSearchRequest.StaticApiUrl);
        client.DefaultRequestHeaders.Accept.Clear();
        //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        StatisticUserModel user = new StatisticUserModel()
        {
            Password = siteSettings.PopularSearchRequest.Password,
            Username = siteSettings.PopularSearchRequest.Username
        };

        string jsonUser = JsonConvert.SerializeObject(user, Formatting.Indented);
        var stringContent = new StringContent(jsonUser, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(siteSettings.PopularSearchRequest.StaticApiUrl + "/api/token/new", stringContent);
        token = await response.Content.ReadAsStringAsync();

        return token;
    }

You can use this token for the authorization (that is in the subsequent requests)


问:
My code suddenly stops writing at beyond 15500 iterations
I'm studying how to code in Python and I'm trying to recreate a code I did in college.

The code is based on a 2D Ising model applied to epidemiology. What it does is:

it constructs a 2D 100x100 array using numpy, and assigns a value of -1 to each element.

The energy is calculated based on the function calc_h in the script below.

Then, the code randomly selects a cell from the lattice, changes the value to 1, then calculates the energy of the system again.

Then, the code compares if the energy of the system is less than or equal to the previous configuration. If it does, it "accepts" the change. If it isn't, a probability is compared to a random number to determine if the change is "accepted". This part is done in the metropolis function.

The code repeats the process using a while loop until the maximum specified iteration, max_iterations.
-The code tallies the number of elements with a -1 value (which is the s variable) and the number of elements with a 1 value (which is the i variable) in the countSI function. The script appends to a text file every 500 iteratons.

THE PROBLEM

I ran the script and besides taking too long to execute, the tallying stops at 15500. The code doesn't throw any error, but it just keeps going. I waited for around 3 hours for it to finish but it still goes only up to 15500 iterations.

I've tried commenting out the writing to csv block and instead printing the values first to observe it as it happens, and there I see, it stops at 15500 again.

I have no idea what's wrong as it doesn't throw in any error, and the code doesn't stop.

Here's the whole script. I put a description of what the part does below each block:

```<code>import numpy as np
import random as r
import math as m
import csv

init_size = input("Input array size: ")
size = int(init_size)

</code>```

this part initializes the size of the 2D array. For observation purposes, I selected a 100 by 100 latice.

```<code>def check_overflow(indx, size):
    if indx == size - 1:
        return -indx
    else:
        return 1
</code>```

I use this function for the calc_h function, to initialize a circular boundary condition. Simply put, the edges of the lattice are connected to one another.

```<code>def calc_h(pop, J1, size):
    h_sum = 0
    r = 0
    c = 0

    while r < size:
        buffr = check_overflow(r, size)
        while c < size:
            buffc = check_overflow(c, size)
            h_sum = h_sum + J1*pop[r,c] * pop[r,c-1] * pop[r-1,c] * pop[r+buffr,c] * pop[r,c+buffc]
            c = c + 1
        c = 0
        r = r + 1

    return h_sum
</code>```

this function calculates the energy of the system by taking the sum of the product of the value of a cell, its top, bottom, left and right neighbors, multiplied to a constant J.

```<code>def metropolis(h, h0, T_):
    if h <= h0:
        return 1
    else:
        rand_h = r.random()
        p = m.exp(-(h - h0)/T_)
        if rand_h <= p:
            return 1
        else:
            return 0
</code>```

This determines whether the change from -1 to 1 is accepted depending on what calc_h gets.

```<code>def countSI(pop, sz, iter):
    s = np.count_nonzero(pop == -1)
    i = np.count_nonzero(pop == 1)
    row = [iter, s, i]
    with open('data.txt', 'a') as si_csv:
        tally_data = csv.writer(si_csv)
        tally_data.writerow(row)
        si_csv.seek(0)
</code>```

This part tallies the number of -1's and 1's in the lattice.

```<code>def main():
    J = 1
    T = 4.0
    max_iterations = 150000

    population = np.full((size, size), -1, np.int8) #initialize population array
</code>```

The 2D array is initialized in population.

```<code>    h_0 = calc_h(population, J, size)

    turn = 1
    while turn <= max_iterations:
        inf_x = r.randint(1,size) - 1
        inf_y = r.randint(1,size) - 1

        while population[inf_x,inf_y] == 1:
            inf_x = r.randint(1,size) - 1
            inf_y = r.randint(1,size) - 1

        population[inf_x, inf_y] = 1
        h = calc_h(population, J, size)

        accept_i = metropolis(h,h_0,T)
</code>```

This is the main loop, where a random cell is selected, and whether the change is accepted or not is determined by the function metropolis.

```<code>        if (accept_i == 0):
            population[inf_x, inf_y] = -1

        if turn%500 == 0 :
            countSI(population, size, turn)
</code>```

The script tallies every 500th iteration.

```<code>        turn = turn + 1
        h_0 = h

main()

</code>```

The expected output is a text file with the tallies of the number of the s and i every 500th iteration. something that looks like this:

```<code>500,9736,264
1000,9472,528
1500,9197,803
2000,8913,1087
2500,8611,1389
3000,8292,1708
3500,7968,2032
4000,7643,2357
4500,7312,2688
5000,6960,3040
5500,6613,3387
6000,6257,3743
6500,5913,4087
7000,5570,4430
7500,5212,4788
</code>```

I have no idea where to start at a solution. At first, I thought it was the writing to csv that's causing the problem, but probing through the print function proves otherwise. I tried to make it as concise as I can.

I hope you guys can help! I really wanna learn this language and start simulating a lot of stuff, and I think this mini project is a great starting step for me.

Thanks a lot!

答:
Answer provided by @randomir in the comments:

Your code is probably wrong. It will block in that nested while loop whenever the number of spins to flip is smaller than the number of iterations. In your example from the previous comment, the size of the population is 10000 and you want to flip 15500 spins. Note that once spin is flipped up (with 100% prob), it will be flipped down with smaller prob, due to metropolis sampling.

works.

Body:
I'm studying how to code in Python and I'm trying to recreate a code I did in college.

The code is based on a 2D Ising model applied to epidemiology. What it does is:

it constructs a 2D 100x100 array using numpy, and assigns a value of -1 to each element.

The energy is calculated based on the function calc_h in the script below.

Then, the code randomly selects a cell from the lattice, changes the value to 1, then calculates the energy of the system again.

Then, the code compares if the energy of the system is less than or equal to the previous configuration. If it does, it "accepts" the change. If it isn't, a probability is compared to a random number to determine if the change is "accepted". This part is done in the metropolis function.

The code repeats the process using a while loop until the maximum specified iteration, max_iterations.
-The code tallies the number of elements with a -1 value (which is the s variable) and the number of elements with a 1 value (which is the i variable) in the countSI function. The script appends to a text file every 500 iteratons.

THE PROBLEM

I ran the script and besides taking too long to execute, the tallying stops at 15500. The code doesn't throw any error, but it just keeps going. I waited for around 3 hours for it to finish but it still goes only up to 15500 iterations.

I've tried commenting out the writing to csv block and instead printing the values first to observe it as it happens, and there I see, it stops at 15500 again.

I have no idea what's wrong as it doesn't throw in any error, and the code doesn't stop.

Here's the whole script. I put a description of what the part does below each block:

import numpy as np
import random as r
import math as m
import csv

init_size = input("Input array size: ")
size = int(init_size)

this part initializes the size of the 2D array. For observation purposes, I selected a 100 by 100 latice.

def check_overflow(indx, size):
    if indx == size - 1:
        return -indx
    else:
        return 1

I use this function for the calc_h function, to initialize a circular boundary condition. Simply put, the edges of the lattice are connected to one another.

def calc_h(pop, J1, size):
    h_sum = 0
    r = 0
    c = 0

    while r < size:
        buffr = check_overflow(r, size)
        while c < size:
            buffc = check_overflow(c, size)
            h_sum = h_sum + J1*pop[r,c] * pop[r,c-1] * pop[r-1,c] * pop[r+buffr,c] * pop[r,c+buffc]
            c = c + 1
        c = 0
        r = r + 1

    return h_sum

this function calculates the energy of the system by taking the sum of the product of the value of a cell, its top, bottom, left and right neighbors, multiplied to a constant J.

def metropolis(h, h0, T_):
    if h <= h0:
        return 1
    else:
        rand_h = r.random()
        p = m.exp(-(h - h0)/T_)
        if rand_h <= p:
            return 1
        else:
            return 0

This determines whether the change from -1 to 1 is accepted depending on what calc_h gets.

def countSI(pop, sz, iter):
    s = np.count_nonzero(pop == -1)
    i = np.count_nonzero(pop == 1)
    row = [iter, s, i]
    with open('data.txt', 'a') as si_csv:
        tally_data = csv.writer(si_csv)
        tally_data.writerow(row)
        si_csv.seek(0)

This part tallies the number of -1's and 1's in the lattice.

def main():
    J = 1
    T = 4.0
    max_iterations = 150000

    population = np.full((size, size), -1, np.int8) #initialize population array

The 2D array is initialized in population.

    h_0 = calc_h(population, J, size)

    turn = 1
    while turn <= max_iterations:
        inf_x = r.randint(1,size) - 1
        inf_y = r.randint(1,size) - 1

        while population[inf_x,inf_y] == 1:
            inf_x = r.randint(1,size) - 1
            inf_y = r.randint(1,size) - 1

        population[inf_x, inf_y] = 1
        h = calc_h(population, J, size)

        accept_i = metropolis(h,h_0,T)

This is the main loop, where a random cell is selected, and whether the change is accepted or not is determined by the function metropolis.

        if (accept_i == 0):
            population[inf_x, inf_y] = -1

        if turn%500 == 0 :
            countSI(population, size, turn)

The script tallies every 500th iteration.

        turn = turn + 1
        h_0 = h

main()

The expected output is a text file with the tallies of the number of the s and i every 500th iteration. something that looks like this:

500,9736,264
1000,9472,528
1500,9197,803
2000,8913,1087
2500,8611,1389
3000,8292,1708
3500,7968,2032
4000,7643,2357
4500,7312,2688
5000,6960,3040
5500,6613,3387
6000,6257,3743
6500,5913,4087
7000,5570,4430
7500,5212,4788

I have no idea where to start at a solution. At first, I thought it was the writing to csv that's causing the problem, but probing through the print function proves otherwise. I tried to make it as concise as I can.

I hope you guys can help! I really wanna learn this language and start simulating a lot of stuff, and I think this mini project is a great starting step for me.

Thanks a lot!


问:
UITabBar Border and Shadow issue
I need to put shadow effect in UITabBar, which I'm getting by following code:

```<code>tabBar.layer.shadowOffset = CGSize(width: 0, height: 0)
tabBar.layer.shadowRadius = 4.0
tabBar.layer.shadowColor = UIColor.gray.cgColor
tabBar.layer.shadowOpacity = 0.6
</code>```

And it is working perfectly.

But, I need to remove the border on top of the UITabBar, And by searching I got self.tabBar.clipsToBounds = true, by putting that code, It removes the Border but it also remove the shadow effect.

I need like following image:

No Border but shadow effect.

Any Help will be appreciated.

答:
Tested on iOS 12.1, Swift 4.2

The UITabBar view added in your .storyboard/.xib file need to be lower (position in the Document Outline) than the content that will be scrolling, in my case the Web Report Container is the scrolling part and the Tab Bar is the UITabBar in the bottom. I put it as well lower in the Document Outline as you can see here to give it a lower z-index:

Then in your ViewController.swift file you could have a setup like this in your viewDidLoad for example:

```<code>// Remove default line
tabBar.shadowImage = UIImage()
tabBar.backgroundImage = UIImage()
tabBar.backgroundColor = UIColor.white

// Add only shadow
tabBar.layer.shadowOffset = CGSize(width: 0, height: 0)
tabBar.layer.shadowRadius = 8
tabBar.layer.shadowColor = UIColor.black.cgColor
tabBar.layer.shadowOpacity = 0.2
</code>```

You can play with shadowOpacity and shadowRadius to adjust the shadowing visual to the desired effect.

Title: UITabBar Border and Shadow issue

Body:
I need to put shadow effect in UITabBar, which I'm getting by following code:

tabBar.layer.shadowOffset = CGSize(width: 0, height: 0)
tabBar.layer.shadowRadius = 4.0
tabBar.layer.shadowColor = UIColor.gray.cgColor
tabBar.layer.shadowOpacity = 0.6

And it is working perfectly.

But, I need to remove the border on top of the UITabBar, And by searching I got self.tabBar.clipsToBounds = true, by putting that code, It removes the Border but it also remove the shadow effect.

I need like following image:

No Border but shadow effect.

Any Help will be appreciated.

Body:
Tested on iOS 12.1, Swift 4.2

The UITabBar view added in your .storyboard/.xib file need to be lower (position in the Document Outline) than the content that will be scrolling, in my case the Web Report Container is the scrolling part and the Tab Bar is the UITabBar in the bottom. I put it as well lower in the Document Outline as you can see here to give it a lower z-index:

Then in your ViewController.swift file you could have a setup like this in your viewDidLoad for example:

// Remove default line
tabBar.shadowImage = UIImage()
tabBar.backgroundImage = UIImage()
tabBar.backgroundColor = UIColor.white

// Add only shadow
tabBar.layer.shadowOffset = CGSize(width: 0, height: 0)
tabBar.layer.shadowRadius = 8
tabBar.layer.shadowColor = UIColor.black.cgColor
tabBar.layer.shadowOpacity = 0.2

You can play with shadowOpacity and shadowRadius to adjust the shadowing visual to the desired effect.


问:
(Angular 7) Cannot assign to read only property 'isActive' on ng-block-ui
I'm trying to use the ng-block-ui dependency for my project. The problem is that it doesn't work properly on Angular 7. I have used this on an Angular 6 project and works fine

app.module.ts

```<code>import { BlockUIModule } from 'ng-block-ui';

@NgModule({
     BlockUIModule.forRoot()
})
</code>```

component.ts

```<code>import { BlockUI, NgBlockUI } from 'ng-block-ui';

export class *classname* implements OnInit {
     @BlockUI('departure') blockUIList: NgBlockUI;

     constructor() { this.blockUIList.start('Loading Page...'); }
}
</code>```

component.html

```<code><div class="kt-portlet kt-portlet--mobile" *blockUI="'departure'">
</code>```

Error Message

```<code>ERROR TypeError: Cannot assign to read only property 'isActive' of object '[object Object]'
    at BlockUIInstanceService.push../node_modules/ng-block-ui/fesm5/ng-block-ui.js.BlockUIInstanceService.blockUIMiddleware (ng-block-ui.js:113)
    at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:192)
    at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:130)
    at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:76)
    at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:53)
    at ReplaySubject.push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next (Subject.js:47)
    at ReplaySubject.push../node_modules/rxjs/_esm5/internal/ReplaySubject.js.ReplaySubject.nextInfiniteTimeWindow (ReplaySubject.js:39)
    at Object.stop (ng-block-ui.js:131)
    at SafeSubscriber._complete (booking-reservation.component.ts:125)
    at SafeSubscriber.wrappedComplete (Subscriber.js:175)
</code>```

答:
I had a problem with it.

I am in error when changing isActive = true from fesm5 / ng-block-ui.js in ng-block-ui.

It's not a perfect solution, ng-block-ui.js -> Line: 114 [this.blockUIInstances[name].isActive = isActive] ==> this.blockUIInstances[name] = Object.assign({}, this.blockUIInstances[name], {isActive: isActive}) you can fix it without errors.

Body:
I'm trying to use the ng-block-ui dependency for my project. The problem is that it doesn't work properly on Angular 7. I have used this on an Angular 6 project and works fine

app.module.ts

import { BlockUIModule } from 'ng-block-ui';

@NgModule({
     BlockUIModule.forRoot()
})

component.ts

import { BlockUI, NgBlockUI } from 'ng-block-ui';

export class *classname* implements OnInit {
     @BlockUI('departure') blockUIList: NgBlockUI;

     constructor() { this.blockUIList.start('Loading Page...'); }
}

component.html

Error Message

ERROR TypeError: Cannot assign to read only property 'isActive' of object '[object Object]'
    at BlockUIInstanceService.push../node_modules/ng-block-ui/fesm5/ng-block-ui.js.BlockUIInstanceService.blockUIMiddleware (ng-block-ui.js:113)
    at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:192)
    at SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next (Subscriber.js:130)
    at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next (Subscriber.js:76)
    at Subscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:53)
    at ReplaySubject.push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next (Subject.js:47)
    at ReplaySubject.push../node_modules/rxjs/_esm5/internal/ReplaySubject.js.ReplaySubject.nextInfiniteTimeWindow (ReplaySubject.js:39)
    at Object.stop (ng-block-ui.js:131)
    at SafeSubscriber._complete (booking-reservation.component.ts:125)
    at SafeSubscriber.wrappedComplete (Subscriber.js:175)


问:
Making a folder directory from a text file using a python script
I have a text file with hundreds of lines, each line contains a number to represent the level the folder/file should be on and a folder/file name. Because the  hierarchy is too large I want to make a script to automate making this directory/sub directory.

Example text file

```<code> .0.  Folder Name a
  .1. Folder Name b
   .2. Folder Name c
   .2. Folder Name c2
  .1. Folder Name d
   .2. Folder Name e
   .2. Folder Name e2
    .3. Folder Name f
</code>```

I assume I need to read line by line and use os.mkdir, but I don't know how to step down a directory level.

```<code>#path of file
import os

with open('Tree.txt', 'r') as t:
 for line in t:
  readline(.{Level}. {FolderName})
    if Level == '0'
     os.mkdir(FolderName)
    else if Level == '1'
     # go down and os.mkdir(FolderName)
</code>```

答:
For clarity I do not show reading of file, but hard-code it, so say you use variable content to store what was read from file:

```<code>content = ''' .0.  Folder Name a
  .1. Folder Name b
   .2. Folder Name c
   .2. Folder Name c2
  .1. Folder Name d
   .2. Folder Name e
   .2. Folder Name e2
    .3. Folder Name f  '''
</code>```

You could break it into lines:

```<code>content = content.split('\n')
</code>```

Now it is list of lines, but these lines have spaces in front and end, which we need to remove:

```<code>content = [i.strip(' ') for i in content]
</code>```

Now is time to tokenize it

```<code>def tokenize(x):
    n,name = x.split(' Folder Name ',1)
    return (int(n.replace('.','')),name)
content = [tokenize(i) for i in content]
</code>```

Now print(content) gives [(0, 'a'), (1, 'b'), (2, 'c'), (2, 'c2'), (1, 'd'), (2, 'e'), (2, 'e2'), (3, 'f')] that is list of tuples (int,str).

Finally we could do traversal of tree:

```<code>import os
paths = []
while(content):
    path = [content[0]]
    for i in content[1:]:
        if(i[0]<=path[-1][0]):
            break
        path.append(i)
    paths.append(os.path.join(*[i[1] for i in path]))
    content.remove(path[-1])
</code>```

Now my paths is ['a/b/c', 'a/b/c2', 'a/b', 'a/d/e', 'a/d/e2/f', 'a/d/e2', 'a/d', 'a'] as I use Linux OS and os.path.join will use proper slashes for your system.
Explanation of above code: I traverse this tree and when I go into deadend I add path which lead to it to my list paths and remove that leaf (list remove always removes only 1 element so no need to worry about deleting same named folder being another leaf). I end when all leafs are deleted (hope that you could understand, sadly I am unable to explain it in more clear way)

As paths is now list of paths I could simply use os.makedirs() function. Note that if you would try to make dir which already exist it would result in error, so we need to check firstly if it does not exist:

```<code>for i in paths:
    if not os.path.exists(i):
        os.makedirs(i)
</code>```

Body:
I have a text file with hundreds of lines, each line contains a number to represent the level the folder/file should be on and a folder/file name. Because the  hierarchy is too large I want to make a script to automate making this directory/sub directory.

Example text file

 .0.  Folder Name a
  .1. Folder Name b
   .2. Folder Name c
   .2. Folder Name c2
  .1. Folder Name d
   .2. Folder Name e
   .2. Folder Name e2
    .3. Folder Name f

I assume I need to read line by line and use os.mkdir, but I don't know how to step down a directory level.

#path of file
import os

with open('Tree.txt', 'r') as t:
 for line in t:
  readline(.{Level}. {FolderName})
    if Level == '0'
     os.mkdir(FolderName)
    else if Level == '1'
     # go down and os.mkdir(FolderName)

Body:
For clarity I do not show reading of file, but hard-code it, so say you use variable content to store what was read from file:

content = ''' .0.  Folder Name a
  .1. Folder Name b
   .2. Folder Name c
   .2. Folder Name c2
  .1. Folder Name d
   .2. Folder Name e
   .2. Folder Name e2
    .3. Folder Name f  '''

You could break it into lines:

content = content.split('\n')

Now it is list of lines, but these lines have spaces in front and end, which we need to remove:

content = [i.strip(' ') for i in content]

Now is time to tokenize it

def tokenize(x):
    n,name = x.split(' Folder Name ',1)
    return (int(n.replace('.','')),name)
content = [tokenize(i) for i in content]

Now print(content) gives [(0, 'a'), (1, 'b'), (2, 'c'), (2, 'c2'), (1, 'd'), (2, 'e'), (2, 'e2'), (3, 'f')] that is list of tuples (int,str).

Finally we could do traversal of tree:

import os
paths = []
while(content):
    path = [content[0]]
    for i in content[1:]:
        if(i[0]<=path[-1][0]):
            break
        path.append(i)
    paths.append(os.path.join(*[i[1] for i in path]))
    content.remove(path[-1])

Now my paths is ['a/b/c', 'a/b/c2', 'a/b', 'a/d/e', 'a/d/e2/f', 'a/d/e2', 'a/d', 'a'] as I use Linux OS and os.path.join will use proper slashes for your system.
Explanation of above code: I traverse this tree and when I go into deadend I add path which lead to it to my list paths and remove that leaf (list remove always removes only 1 element so no need to worry about deleting same named folder being another leaf). I end when all leafs are deleted (hope that you could understand, sadly I am unable to explain it in more clear way)

As paths is now list of paths I could simply use os.makedirs() function. Note that if you would try to make dir which already exist it would result in error, so we need to check firstly if it does not exist:

for i in paths:
    if not os.path.exists(i):
        os.makedirs(i)


问:
How to make two independent changes through api
I have a situation in which I have to update video details on facebook, that update needs two different calls, now my problem is

If any of the call fails, then what should I do?

I dont want to show user partially updated data, neither I want to retry as that might fail again if it failed already.

Only solution I think is to make a new call that will revert that previous call change, but that doesnt seems to be a nice solution.

Can someone suggest a better approach?

答:
It's a difficult situration.

Prior to making any API calls you should do anything you can to check for possible reasons why the calls may fail ahead of time - like missing authentication or authorization.

I agree that it is best practice not to show the user partially updated data, so you have a few options depending on what kind of failure you are up against.

If it fails with a network-like error you could just attempt a single retry to the 2nd endpoint.

Otherwise I'd recommend rolling back. If your rollback call fails, you should inform your user that some data has changed and could not be rolled back. If the error is a network error again you could create a queuejob to run later for rolling back the changes.

In any event, you should inform your user.


问:
How to sum columns without using Loop in VBA
I am trying to reformat a report so it can feed into my system like below:

```<code>wbOutput.Sheets(1).Range("B" & O_lrow + 1 & ":B" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("F1:F" & lRow).Value
</code>```

One issue I encounter is column F needs to be the sum of two source column and below doesn't work:

```<code>wbOutput.Sheets(1).Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("N1:N" & lRow).Value + wbSource.Sheets(1).Range("O1:O" & lRow).Value
</code>```

I am trying to avoid using loop as there are many rows and I don't want the marco slow down too much.

Is there any simple way to achieve this without using a loop?

答:
You can try this:</p>

```<code> wbOutput.Sheets(1).Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow).Value = _
             wbSource.Sheets(1).Evaluate("N1:N" & lRow & " + O1:O" & lRow)
</code>```

Body:
I am trying to reformat a report so it can feed into my system like below:

wbOutput.Sheets(1).Range("B" & O_lrow + 1 & ":B" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("F1:F" & lRow).Value

One issue I encounter is column F needs to be the sum of two source column and below doesn't work:

wbOutput.Sheets(1).Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow).Value = wbSource.Sheets(1).Range("N1:N" & lRow).Value + wbSource.Sheets(1).Range("O1:O" & lRow).Value

I am trying to avoid using loop as there are many rows and I don't want the marco slow down too much.

Is there any simple way to achieve this without using a loop?

Body:
You can try this:

 wbOutput.Sheets(1).Range("F" & O_lrow + 1 & ":F" & O_lrow + lRow).Value = _
             wbSource.Sheets(1).Evaluate("N1:N" & lRow & " + O1:O" & lRow)


问:
How can I change a static method behavior in C++?
Is there a way to modify the behavior of a static method to return different parameters?

I am using Gmock for mocking but in this case I am not able to change my code and the methods must stay static

for example

```<code>class MyClass
{
public:
    static int GetSomething()
    {
        return -1;
    }
};
</code>```

I need the method to return positive number

答:
In that case your options are limited, but if it's just for a mock, then just make the method return a static variable instead of a hard coded value. </p>

```<code>class MyClass
{
  static int somethingValue;
public:
  static int GetSomething()
  {
    return somethingValue;
  }
  static void SetSomething(int value)
  {
    somethingValue = value;
  }
};
int MyClass::somethingValue = -1;
</code>```

Body:
Is there a way to modify the behavior of a static method to return different parameters?

I am using Gmock for mocking but in this case I am not able to change my code and the methods must stay static

for example

class MyClass
{
public:
    static int GetSomething()
    {
        return -1;
    }
};

I need the method to return positive number

Body:
In that case your options are limited, but if it's just for a mock, then just make the method return a static variable instead of a hard coded value.

class MyClass
{
  static int somethingValue;
public:
  static int GetSomething()
  {
    return somethingValue;
  }
  static void SetSomething(int value)
  {
    somethingValue = value;
  }
};
int MyClass::somethingValue = -1;


问:
How to chunk shell script input by time, not by size?
In a bash script I am using a many-producer single-consumer pattern. Producers are background processes writing lines into a fifo (via GNU Parallel). The consumer reads all lines from the fifo, then sorts, filters, and prints the formatted result to stdout.

However, it could take a long time until the full result is available. Producers are usually fast on the first few results but then would slow down. Here I am more interested to see chunks of data every few seconds, each sorted and filtered individually.

mkfifo fifo
parallel ... >"$fifo" &
while chunk=$(read with timeout 5s and at most 10s <"$fifo"); do
  process "$chunk"
done
```

<p>The loop would run until all producers are done and all input is read. Each chunk is read until there has been no new data for 5s, or until 10s have passed since the chunk was started. A chunk may also be empty if there was no new data for 10s.</p>

<p>I tried to make it work like this:</p>

<pre class="lang-sh prettyprint-override"><code>output=$(mktemp)
while true; do
  wasTimeout=0 interruptAt=$(( $(date '+%s') + 10 ))
  while true; do
    IFS= read -r -t5 <>"${fifo}"
    rc="$?"
    if [[ "${rc}" -gt 0 ]]; then
      [[ "${rc}" -gt 128 ]] && wasTimeout=1
      break
    fi
    echo "$REPLY" >>"${output}"
    if [[ $(date '+%s') -ge "${interruptAt}" ]]; then
      wasTimeout=1
      break
    fi
  done
  echo '---' >>"${output}"
  [[ "${wasTimeout}" -eq 0 ]] && break
done
</code>```

Tried some variations of this. In the form above it reads the first chunk but then loops forever. If I use <"${fifo}" (no read/write as above) it blocks after the first chunk. Maybe all of this could be simplified with buffer and/or stdbuf? But both of them define blocks by size, not by time.

答:
Something like this:</p>

```<code>#!/usr/bin/perl

$timeout = 3;
while(<STDIN>) {
    # Make sure there is some input
    push @out,$_;
    eval {
        local $SIG{ALRM} = sub { die };
        alarm $timeout;
        while(<STDIN>) {
            alarm $timeout;
            push @out,$_;
        }
        alarm 0;
    };
    system "echo","process",@out;
}
</code>```

Body:
In a bash script I am using a many-producer single-consumer pattern. Producers are background processes writing lines into a fifo (via GNU Parallel). The consumer reads all lines from the fifo, then sorts, filters, and prints the formatted result to stdout.

However, it could take a long time until the full result is available. Producers are usually fast on the first few results but then would slow down. Here I am more interested to see chunks of data every few seconds, each sorted and filtered individually.

mkfifo fifo
parallel ... >"$fifo" &
while chunk=$(read with timeout 5s and at most 10s <"$fifo"); do
  process "$chunk"
done

The loop would run until all producers are done and all input is read. Each chunk is read until there has been no new data for 5s, or until 10s have passed since the chunk was started. A chunk may also be empty if there was no new data for 10s.

I tried to make it work like this:

output=$(mktemp)
while true; do
  wasTimeout=0 interruptAt=$(( $(date '+%s') + 10 ))
  while true; do
    IFS= read -r -t5 <>"${fifo}"
    rc="$?"
    if [[ "${rc}" -gt 0 ]]; then
      [[ "${rc}" -gt 128 ]] && wasTimeout=1
      break
    fi
    echo "$REPLY" >>"${output}"
    if [[ $(date '+%s') -ge "${interruptAt}" ]]; then
      wasTimeout=1
      break
    fi
  done
  echo '---' >>"${output}"
  [[ "${wasTimeout}" -eq 0 ]] && break
done

Tried some variations of this. In the form above it reads the first chunk but then loops forever. If I use <"${fifo}" (no read/write as above) it blocks after the first chunk. Maybe all of this could be simplified with buffer and/or stdbuf? But both of them define blocks by size, not by time.

Body:
Something like this:

#!/usr/bin/perl

$timeout = 3;
while(<STDIN>) {
    # Make sure there is some input
    push @out,$_;
    eval {
        local $SIG{ALRM} = sub { die };
        alarm $timeout;
        while(<STDIN>) {
            alarm $timeout;
            push @out,$_;
        }
        alarm 0;
    };
    system "echo","process",@out;
}


问:
HTTP Error 502.5 - Process Failure when trying to run my project
I am trying to follow this tutorial, my program has the API template

https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio

but when I run the program it gives me this error HTTP Error 502.5 - Process Failure

it also says
The application to execute does not exist: 'C:\Users\Cristina\Desktop\roweb proj\TodoApi\TodoApi\bin\Debug\netcoreapp2.2\TodoApi.dll'
even though it did not create those files when I created the folder.

答:
There are multiple reasons as to why this error may arise.

Call your .dll file of your project in the cmd using the dotnet command will help you understand exactly what the issue is. In my case there was a version error for ASP.NET core. Make sure all your project dependencies in the .csproj file of your project use the same version of ASP.NET core SDK and runtime bundle. You can check the versions present on your system through the dotnet command on cmd:

```<code>dotnet --info
</code>```

Take a moment to read this link, there may be a solution for your problem .

Body:
There are multiple reasons as to why this error may arise.

Call your .dll file of your project in the cmd using the dotnet command will help you understand exactly what the issue is. In my case there was a version error for ASP.NET core. Make sure all your project dependencies in the .csproj file of your project use the same version of ASP.NET core SDK and runtime bundle. You can check the versions present on your system through the dotnet command on cmd:

dotnet --info

Take a moment to read this link, there may be a solution for your problem .


问:
Allow docker container to connect to a local/host postgres database
I've recently been playing around with Docker and QGIS and have installed a container following the instructions in this tutorial.

Everything works great, although I am unable to connect to a localhost postgres database that contains all my GIS data. I figure this is because my postgres database is not configured to accept remote connections and have been editing the postgres conf files to allow remote connections using the  instructions in this article.

I'm still getting an error message when I try and connect to my database running QGIS in Docker: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections to port 5433?
The postgres server is running, and I've edited my pg_hba.conf file to allow connections from a range of IP addresses (172.17.0.0/32). I had previously queried the IP address of the docker container using docker ps and although the IP address changes, it has so far always been in the range 172.17.0.x

Any ideas why I can't connect to this database? Probably something very simple I imagine!

I'm running Ubuntu 14.04; Postgres 9.3

答:
for docker-compose you can try just add

```<code>network_mode: "host"
</code>```

example :

```<code>version: '2'
services:
  feedx:
    build: web
    ports:
    - "127.0.0.1:8000:8000"
    network_mode: "host"
</code>```

https://docs.docker.com/compose/compose-file/#network_mode

Body:
for docker-compose you can try just add

network_mode: "host"

example :

version: '2'
services:
  feedx:
    build: web
    ports:
    - "127.0.0.1:8000:8000"
    network_mode: "host"

https://docs.docker.com/compose/compose-file/#network_mode


问:
Return a new string where everth xth character (starting at 0) is now followed by *?
I wanna write a function that takes a string, s, and an int, x. It should return a new string where every xth character (starting from zero) is now followed by an '*'.

So far I've tried this code:

```<code>def string_chunks(string, x):
    """
    >>> string_chunks("Once upon a time, in a land far, far away", 5)
    'O*nce u*pon a* time*, in *a lan*d far*, far* away*'
    """
    for ch in string:
        return ch + "*"
</code>```

but I am very stuck and am unable to make it work.
I would appreciate any help. If you provide an answer, it would be nice if you could comment the code also.

答:
Turn it into a list and every nth index append a '*', then join it back to a string.

```<code>def string_chunks(string, x):
    string = list(string)
    for i in range(0, len(string)-1, 5):
        string[i] += '*'
    return ''.join(string)
</code>```

Body:
I wanna write a function that takes a string, s, and an int, x. It should return a new string where every xth character (starting from zero) is now followed by an '*'.

So far I've tried this code:

def string_chunks(string, x):
    """
    >>> string_chunks("Once upon a time, in a land far, far away", 5)
    'O*nce u*pon a* time*, in *a lan*d far*, far* away*'
    """
    for ch in string:
        return ch + "*"

but I am very stuck and am unable to make it work.
I would appreciate any help. If you provide an answer, it would be nice if you could comment the code also.

Body:
Turn it into a list and every nth index append a '*', then join it back to a string.

def string_chunks(string, x):
    string = list(string)
    for i in range(0, len(string)-1, 5):
        string[i] += '*'
    return ''.join(string)