问:
Accessing a temporary table multiple times in MySql
I have tried to use a temporary table as an intermediate result holder for a SELECT statement. The problem is though that I can't access the temp table multiple times in other queries statement which I hoped would be possible i.e. makes the temp table useless.

Is there an alternative to temporary tables in MySql that allows me to extract my SQL statement.

I can't use store procedures (can't access them from the web-framework version used in the company) and I don't want to use a cursor.

Edit:

Well my code looks somewhat like this:

Temp table creation:

```<code>CREATE TEMPORARY TABLE dates_with_entries (
  seq  INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  datum VARCHAR(32)
);

INSERT INTO dates_with_entries (datum) SELECT datum AS Datum from project_times
    WHERE user_id = 20 GROUP BY datum ORDER BY datum desc LIMIT 13;
</code>```

Then the code where I use my temp table looks somewhat like this (I simpled it down to the problem I have..)

```<code>SELECT
...
FROM (SELECT entrie_date AS datum FROM dates_with_entries ) AS sub_result
INNER JOIN project_times
    ON sub_result.datum = project_times.datum AND project_times.user_id = 20
LEFT JOIN works AS w ON project_times.work_id = w.id
LEFT JOIN sub_projects AS sp ON sp.id = w.sub_project_id
LEFT JOIN projects AS p ON p.id = sp.project_id
GROUP BY datum
UNION(
    SELECT
      ..
  FROM (SELECT entrie_date AS datum FROM dates_with_entries ) AS sub_result
  INNER JOIN project_times AS pt ON pt.datum = sub_result.datum
  INNER JOIN works AS w on w.id = pt.work_id
  INNER JOIN sub_projects AS sp on w.sub_project_id = sp.id
  INNER JOIN projects AS p ON sp.project_id = p.id
  WHERE pt.user_id = 20
);
</code>```

The numbers will be later on replaced by ruby, this is only for testing the SQL statement.

答:
For this problem, where the temporary table is only to be read, I create a second temporary table as a copy of the first then use this in the query:

```<code>CREATE TEMPORARY TABLE t2 as (SELECT * FROM dates_with_entries);
</code>```

Then

```<code>SELECT
...
FROM (SELECT entrie_date AS datum FROM dates_with_entries ) AS sub_result
INNER JOIN project_times
    ON sub_result.datum = project_times.datum AND project_times.user_id = 20
LEFT JOIN works AS w ON project_times.work_id = w.id
LEFT JOIN sub_projects AS sp ON sp.id = w.sub_project_id
LEFT JOIN projects AS p ON p.id = sp.project_id
GROUP BY datum
UNION(
    SELECT
      ..
  FROM (SELECT entrie_date AS datum FROM t2) AS sub_result
  INNER JOIN project_times AS pt ON pt.datum = sub_result.datum
  INNER JOIN works AS w on w.id = pt.work_id
  INNER JOIN sub_projects AS sp on w.sub_project_id = sp.id
  INNER JOIN projects AS p ON sp.project_id = p.id
  WHERE pt.user_id = 20
);
</code>```

Body:
I have tried to use a temporary table as an intermediate result holder for a SELECT statement. The problem is though that I can't access the temp table multiple times in other queries statement which I hoped would be possible i.e. makes the temp table useless.

Is there an alternative to temporary tables in MySql that allows me to extract my SQL statement.

I can't use store procedures (can't access them from the web-framework version used in the company) and I don't want to use a cursor.

Edit:

Well my code looks somewhat like this:

Temp table creation:

CREATE TEMPORARY TABLE dates_with_entries (
  seq  INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  datum VARCHAR(32)
);

INSERT INTO dates_with_entries (datum) SELECT datum AS Datum from project_times
    WHERE user_id = 20 GROUP BY datum ORDER BY datum desc LIMIT 13;

Then the code where I use my temp table looks somewhat like this (I simpled it down to the problem I have..)

SELECT
...
FROM (SELECT entrie_date AS datum FROM dates_with_entries ) AS sub_result
INNER JOIN project_times
    ON sub_result.datum = project_times.datum AND project_times.user_id = 20
LEFT JOIN works AS w ON project_times.work_id = w.id
LEFT JOIN sub_projects AS sp ON sp.id = w.sub_project_id
LEFT JOIN projects AS p ON p.id = sp.project_id
GROUP BY datum
UNION(
    SELECT
      ..
  FROM (SELECT entrie_date AS datum FROM dates_with_entries ) AS sub_result
  INNER JOIN project_times AS pt ON pt.datum = sub_result.datum
  INNER JOIN works AS w on w.id = pt.work_id
  INNER JOIN sub_projects AS sp on w.sub_project_id = sp.id
  INNER JOIN projects AS p ON sp.project_id = p.id
  WHERE pt.user_id = 20
);

The numbers will be later on replaced by ruby, this is only for testing the SQL statement.

Body:
For this problem, where the temporary table is only to be read, I create a second temporary table as a copy of the first then use this in the query:

CREATE TEMPORARY TABLE t2 as (SELECT * FROM dates_with_entries);

Then

SELECT
...
FROM (SELECT entrie_date AS datum FROM dates_with_entries ) AS sub_result
INNER JOIN project_times
    ON sub_result.datum = project_times.datum AND project_times.user_id = 20
LEFT JOIN works AS w ON project_times.work_id = w.id
LEFT JOIN sub_projects AS sp ON sp.id = w.sub_project_id
LEFT JOIN projects AS p ON p.id = sp.project_id
GROUP BY datum
UNION(
    SELECT
      ..
  FROM (SELECT entrie_date AS datum FROM t2) AS sub_result
  INNER JOIN project_times AS pt ON pt.datum = sub_result.datum
  INNER JOIN works AS w on w.id = pt.work_id
  INNER JOIN sub_projects AS sp on w.sub_project_id = sp.id
  INNER JOIN projects AS p ON sp.project_id = p.id
  WHERE pt.user_id = 20
);


来源: stackexchange

问:
GSON & Volley => Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
This error drove me crazy I tried using different kind of Volley requests such as JsonArrayRequest and JsonObjectRequest but no luck !!

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Here's the JSON response link => http://www.mocky.io/v2/58df83a80f00005922eaf4e1

Here's my model class

```<code> public class Order {

@SerializedName("status")
@Expose
private String status; //status

@SerializedName("total")
@Expose
private float price; //total

@SerializedName("created_at")
@Expose
private Date time;

@SerializedName("line_items")
@Expose
public List<ItemsNum> lineItems = new ArrayList<ItemsNum>();

@SerializedName("sub_orders")
@Expose
public List<OrdersNum> subOrders = new ArrayList<OrdersNum>();

@SerializedName("shipping_address")
@Expose
public CusAddress cusAdress;

@SerializedName("customer")
@Expose
public Customer customer;

public Order(Customer customer, String status, float price, String cusPicURL, String firstName, String lastName, Date time, List<ItemsNum> lineItems, List<OrdersNum> subOrders, CusAddress cusAdress) {
    this.status = status;
    this.price = price;
    this.customer = customer;
    this.time = time;
    this.lineItems = lineItems;
    this.subOrders = subOrders;
    this.cusAdress = cusAdress;
}

public Date getTime() {
    return time;
}

public void setTime(Date time) {
    this.time = time;
}

public List<ItemsNum> getLineItems() {
    return lineItems;
}

public void setLineItems(List<ItemsNum> lineItems) {
    this.lineItems = lineItems;
}

public List<OrdersNum> getSubOrders() {
    return subOrders;
}

public void setSubOrders(List<OrdersNum> subOrders) {
    this.subOrders = subOrders;
}

public String getStatus() {
    return status;
}

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

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public CusAddress getCusAdress() {
    return cusAdress;
}

public void setCusAdress(CusAddress cusAdress) {
    this.cusAdress = cusAdress;
}

// //////////// Inner-Classes

public class Customer {

    @SerializedName("avatar_url")
    @Expose
    private String cusPicURL; //avatar_url

    @SerializedName("first_name")
    @Expose
    private String firstName; //first_name

    @SerializedName("last_name")
    @Expose
    private String lastName; //last_name

    public String getCusPicURL() {
        return cusPicURL;
    }

    public void setCusPicURL(String cusPicURL) {
        this.cusPicURL = cusPicURL;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

public class CusAddress {

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

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

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @SerializedName("address_1")
    @Expose
    public String address;

    @SerializedName("city")
    @Expose
    public String city;

    @SerializedName("state")
    @Expose
    public String state;

    @SerializedName("country")
    @Expose
    public String country;
}

public class ItemsNum {

    @SerializedName("id")
    @Expose
    public Integer id;
}

public class OrdersNum {

    @SerializedName("id")
    @Expose
    public Integer id;
 }
}
</code>```

My Adapter

```<code>  public class OrdersDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

public Context context;
private int num;
ArrayList<Order> orders;

public OrdersDataAdapter(ArrayList<Order> orders, Context context) {
    this.orders = orders;

    this.context = context;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_card, parent, false);

    return new NewOrderVH(v);

}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
    final Order order = this.orders.get(position);
    final NewOrderVH vh1 = (NewOrderVH) holder;
    vh1.setData(orders.get(position));

}

@Override
public int getItemCount() {
    return orders.size();
}

public class NewOrderVH extends RecyclerView.ViewHolder {

    private ImageView cusPic;
    private TextView cusName;
    private TextView CusAdress;
    private TextView vendorsNum;
    private TextView itemsNum;
    private TextView time;

    public NewOrderVH(View itemView) {
        super(itemView);

        orderCard = (CardView) itemView.findViewById(R.id.OrderCard);
        cusPic = (ImageView) itemView.findViewById(R.id.cusPic);
        cusName = (TextView) itemView.findViewById(R.id.cusName);
        CusAdress = (TextView) itemView.findViewById(R.id.CusAdress);
        vendorsNum = (TextView) itemView.findViewById(R.id.vendorsNum);
        itemsNum = (TextView) itemView.findViewById(R.id.itemsNum);
        time = (TextView) itemView.findViewById(R.id.time);

    }

    public void setData(final Order data) {

        cusName.setText(data.customer.getFirstName() + "" + data.customer.getLastName());
        Picasso.with(context).load(data.customer.getCusPicURL()).into(cusPic);
        time.setText(data.getTime().getMinutes());
        vendorsNum.setText(data.getSubOrders().size());
        itemsNum.setText(data.getLineItems().size());
        CusAdress.setText(data.cusAdress.getAddress() + "" + data.cusAdress.getCity() + "" + data.cusAdress.getCountry() + "" + data.cusAdress.getState());

    }

}
</code>```

}

Request Method inside a Fragment

```<code>private void fetchPosts() {

    requestQueue = Volley.newRequestQueue(getActivity());

    StringRequest jRequest = new StringRequest(Request.Method.GET, ENDPOINT, onPostsLoaded, onPostsError);

    requestQueue.add(jRequest);

}

private final Response.Listener<String> onPostsLoaded = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {

        Gson gson = new Gson();
        Type listType = new TypeToken<List<Order>>() {}.getType();
        modelData = gson.fromJson(response, listType);

        adapter = new OrdersDataAdapter((ArrayList<Order>) modelData, getActivity());
        recyclerView.setAdapter(adapter);
        adapter.setMode(Attributes.Mode.Single);

    }
};

private final Response.ErrorListener onPostsError = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("PostActivity", error.toString());
    }
};
</code>```

答:
Here your problem is the orders object. You don't deserialize orders. You can solve this issue

```<code>public class OrderHolder{
    private List<Order> orders;

    public List<Order> getOrders(){ return orders; }

}

OrderHolder holder = new Gson().fromJson(response, OrderHolder.class);
modelData = holder.getOrders();
</code>```

or

```<code>JsonElement jelement = new JsonParser().parse(response);
JsonObject  jobject = jelement.getAsJsonObject();
String ordersString = jobject.get("orders").getAsString();

Gson gson = new Gson();
Type listType = new TypeToken<List<Order>>() {}.getType();
modelData = gson.fromJson(ordersString, listType);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This error drove me crazy I tried using different kind of Volley requests such as JsonArrayRequest and JsonObjectRequest but no luck !!

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Here's the JSON response link => http://www.mocky.io/v2/58df83a80f00005922eaf4e1

Here's my model class

 public class Order {

@SerializedName("status")
@Expose
private String status; //status

@SerializedName("total")
@Expose
private float price; //total

@SerializedName("created_at")
@Expose
private Date time;

@SerializedName("line_items")
@Expose
public List<ItemsNum> lineItems = new ArrayList<ItemsNum>();

@SerializedName("sub_orders")
@Expose
public List<OrdersNum> subOrders = new ArrayList<OrdersNum>();

@SerializedName("shipping_address")
@Expose
public CusAddress cusAdress;

@SerializedName("customer")
@Expose
public Customer customer;

public Order(Customer customer, String status, float price, String cusPicURL, String firstName, String lastName, Date time, List<ItemsNum> lineItems, List<OrdersNum> subOrders, CusAddress cusAdress) {
    this.status = status;
    this.price = price;
    this.customer = customer;
    this.time = time;
    this.lineItems = lineItems;
    this.subOrders = subOrders;
    this.cusAdress = cusAdress;
}

public Date getTime() {
    return time;
}

public void setTime(Date time) {
    this.time = time;
}

public List<ItemsNum> getLineItems() {
    return lineItems;
}

public void setLineItems(List<ItemsNum> lineItems) {
    this.lineItems = lineItems;
}

public List<OrdersNum> getSubOrders() {
    return subOrders;
}

public void setSubOrders(List<OrdersNum> subOrders) {
    this.subOrders = subOrders;
}

public String getStatus() {
    return status;
}

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

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public CusAddress getCusAdress() {
    return cusAdress;
}

public void setCusAdress(CusAddress cusAdress) {
    this.cusAdress = cusAdress;
}

// //////////// Inner-Classes

public class Customer {

    @SerializedName("avatar_url")
    @Expose
    private String cusPicURL; //avatar_url

    @SerializedName("first_name")
    @Expose
    private String firstName; //first_name

    @SerializedName("last_name")
    @Expose
    private String lastName; //last_name

    public String getCusPicURL() {
        return cusPicURL;
    }

    public void setCusPicURL(String cusPicURL) {
        this.cusPicURL = cusPicURL;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

public class CusAddress {

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

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

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @SerializedName("address_1")
    @Expose
    public String address;

    @SerializedName("city")
    @Expose
    public String city;

    @SerializedName("state")
    @Expose
    public String state;

    @SerializedName("country")
    @Expose
    public String country;
}

public class ItemsNum {

    @SerializedName("id")
    @Expose
    public Integer id;
}

public class OrdersNum {

    @SerializedName("id")
    @Expose
    public Integer id;
 }
}

My Adapter

  public class OrdersDataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

public Context context;
private int num;
ArrayList<Order> orders;

public OrdersDataAdapter(ArrayList<Order> orders, Context context) {
    this.orders = orders;

    this.context = context;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.order_card, parent, false);

    return new NewOrderVH(v);

}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
    final Order order = this.orders.get(position);
    final NewOrderVH vh1 = (NewOrderVH) holder;
    vh1.setData(orders.get(position));

}

@Override
public int getItemCount() {
    return orders.size();
}

public class NewOrderVH extends RecyclerView.ViewHolder {

    private ImageView cusPic;
    private TextView cusName;
    private TextView CusAdress;
    private TextView vendorsNum;
    private TextView itemsNum;
    private TextView time;

    public NewOrderVH(View itemView) {
        super(itemView);

        orderCard = (CardView) itemView.findViewById(R.id.OrderCard);
        cusPic = (ImageView) itemView.findViewById(R.id.cusPic);
        cusName = (TextView) itemView.findViewById(R.id.cusName);
        CusAdress = (TextView) itemView.findViewById(R.id.CusAdress);
        vendorsNum = (TextView) itemView.findViewById(R.id.vendorsNum);
        itemsNum = (TextView) itemView.findViewById(R.id.itemsNum);
        time = (TextView) itemView.findViewById(R.id.time);

    }

    public void setData(final Order data) {

        cusName.setText(data.customer.getFirstName() + "" + data.customer.getLastName());
        Picasso.with(context).load(data.customer.getCusPicURL()).into(cusPic);
        time.setText(data.getTime().getMinutes());
        vendorsNum.setText(data.getSubOrders().size());
        itemsNum.setText(data.getLineItems().size());
        CusAdress.setText(data.cusAdress.getAddress() + "" + data.cusAdress.getCity() + "" + data.cusAdress.getCountry() + "" + data.cusAdress.getState());

    }

}

}

Request Method inside a Fragment

private void fetchPosts() {

    requestQueue = Volley.newRequestQueue(getActivity());

    StringRequest jRequest = new StringRequest(Request.Method.GET, ENDPOINT, onPostsLoaded, onPostsError);

    requestQueue.add(jRequest);

}

private final Response.Listener<String> onPostsLoaded = new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {

        Gson gson = new Gson();
        Type listType = new TypeToken<List<Order>>() {}.getType();
        modelData = gson.fromJson(response, listType);

        adapter = new OrdersDataAdapter((ArrayList<Order>) modelData, getActivity());
        recyclerView.setAdapter(adapter);
        adapter.setMode(Attributes.Mode.Single);

    }
};

private final Response.ErrorListener onPostsError = new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("PostActivity", error.toString());
    }
};

Body:
Here your problem is the orders object. You don't deserialize orders. You can solve this issue

public class OrderHolder{
    private List<Order> orders;

    public List<Order> getOrders(){ return orders; }

}

OrderHolder holder = new Gson().fromJson(response, OrderHolder.class);
modelData = holder.getOrders();

or

JsonElement jelement = new JsonParser().parse(response);
JsonObject  jobject = jelement.getAsJsonObject();
String ordersString = jobject.get("orders").getAsString();

Gson gson = new Gson();
Type listType = new TypeToken<List<Order>>() {}.getType();
modelData = gson.fromJson(ordersString, listType);


问:
Firebase WEB - Email Verification not being sent. What's wrong with the code
Well, I've tried using many ways to trigger the function sendEmailVerification(). But none have worked successfully. The docs aren't helping either.

Below is part of the source code that I will be using. Please let me know of how I can correct this.

On my console I get the the following error:

TypeError: Cannot read property 'emailVerified' of null
           at Object.firebase.auth.onAuthStateChanged.firebaseUser [as next]

```

        btnSignUpWithGoogle.addEventListener('click', e => {
            var provider = new firebase.auth.GoogleAuthProvider();

            firebase.auth().signInWithPopup(provider).then(function(result) {
            var token = result.credential.accessToken;
            var user = result.user;
          }).catch(function(error) {
            var errorCode = error.code;
            var errorMessage = error.message;
            var email = error.email;
            var credential = error.credential;
            console.log(errorCode);
          });
    });

    btnLogin.addEventListener('click', e => {
      const email = txtEmail.value;
      const pass = txtPassword.value;
      const auth = firebase.auth();

      const promise = auth.signInWithEmailAndPassword(email, pass);
      promise.catch(e => console.log(e.message));

      txtEmail.value = "";
      txtPassword.value = "";
    });

    btnSignUp.addEventListener('click', e => {
      const email = txtEmail.value;
      const pass = txtPassword.value;
      const auth = firebase.auth();

      const promise = auth.createUserWithEmailAndPassword(email, pass);
      promise.catch(e => console.log(e.message));

      txtEmail.value = "";
      txtPassword.value = "";

      const emailVerified = firebaseUser.emailVerified;

      if (!emailVerified){
        firebase.auth().firebaseUser.sendEmailVerification().then(function(){
          alert('Please check your email to verify your Account.');
        });
      } else {
        alert('Your Email has been verified!');
      }

    });

    firebase.auth().onAuthStateChanged(firebaseUser => {
      if (firebaseUser) {
        console.log(firebaseUser);
        console.log('Logged IN!');
        btnLogout.style.visibility = 'visible';
    }
      if (firebaseUser.emailVerified) {
        console.log('Email is verified');
      }
      else {
        console.log('Email is not verified');
        firebaseUser.sendEmailVerification();
      }

    });

```

答:
sendEmailVerification() only works once you have the email address already loaded into firebase.

Check the below code :
https://github.com/aqeelsmith/AngularJsData/blob/master/builds/angulardata/js/services/authentication.js - Line 82

Body:
Well, I've tried using many ways to trigger the function sendEmailVerification(). But none have worked successfully. The docs aren't helping either.

Below is part of the source code that I will be using. Please let me know of how I can correct this.

On my console I get the the following error:

TypeError: Cannot read property 'emailVerified' of null
           at Object.firebase.auth.onAuthStateChanged.firebaseUser [as next]

        btnSignUpWithGoogle.addEventListener('click', e => {
            var provider = new firebase.auth.GoogleAuthProvider();

            firebase.auth().signInWithPopup(provider).then(function(result) {
            var token = result.credential.accessToken;
            var user = result.user;
          }).catch(function(error) {
            var errorCode = error.code;
            var errorMessage = error.message;
            var email = error.email;
            var credential = error.credential;
            console.log(errorCode);
          });
    });

    btnLogin.addEventListener('click', e => {
      const email = txtEmail.value;
      const pass = txtPassword.value;
      const auth = firebase.auth();

      const promise = auth.signInWithEmailAndPassword(email, pass);
      promise.catch(e => console.log(e.message));

      txtEmail.value = "";
      txtPassword.value = "";
    });

    btnSignUp.addEventListener('click', e => {
      const email = txtEmail.value;
      const pass = txtPassword.value;
      const auth = firebase.auth();

      const promise = auth.createUserWithEmailAndPassword(email, pass);
      promise.catch(e => console.log(e.message));

      txtEmail.value = "";
      txtPassword.value = "";

      const emailVerified = firebaseUser.emailVerified;

      if (!emailVerified){
        firebase.auth().firebaseUser.sendEmailVerification().then(function(){
          alert('Please check your email to verify your Account.');
        });
      } else {
        alert('Your Email has been verified!');
      }

    });

    firebase.auth().onAuthStateChanged(firebaseUser => {
      if (firebaseUser) {
        console.log(firebaseUser);
        console.log('Logged IN!');
        btnLogout.style.visibility = 'visible';
    }
      if (firebaseUser.emailVerified) {
        console.log('Email is verified');
      }
      else {
        console.log('Email is not verified');
        firebaseUser.sendEmailVerification();
      }

    });


问:
ReactJS - Change Component in parent depending on nested route
I have my App wrapped in a component which renders a Header, Footer and any routed child components.

I am trying to replace the  component with </HeaderAdmin/> when at /admin.

Routes

```<code><Route path='/' component={SiteWrapper} >
  <IndexRoute component={Home} />
  <Route path="admin" component={Admin}>
    <Route path="dashboard" component={Dashboard}/>
  </Route>
</Route>
</code>```

SiteWrapper Comp

```<code>export default class SiteWrapper extends React.Component {
    render() {
        return (
            <div>
                <Header/> // Want to replace with <AdminHeader /> if on /admin
                <div className="container">
                    {this.props.children.props.route.header ? <PageHeader header={this.props.children.props.route.header} /> : null}
                    {this.props.children}
                </div>
                <Footer/>
            </div>
        )
    }
}
</code>```

答:
You can use this.props.location.pathname to find the route name

```<code>export default class SiteWrapper extends React.Component {
    render() {
        return (
            <div>
                {(this.prop.location.pathname === 'admin')? <AdminHeader/>: <Header/>}
                <div className="container">
                    {this.props.children.props.route.header ? <PageHeader header={this.props.children.props.route.header} /> : null}
                    {this.props.children}
                </div>
                <Footer/>
            </div>
        )
    }
}
</code>```

Body:
I have my App wrapped in a component which renders a Header, Footer and any routed child components.

I am trying to replace the  component with </HeaderAdmin/> when at /admin.

Routes

<Route path='/' component={SiteWrapper} >
  <IndexRoute component={Home} />
  <Route path="admin" component={Admin}>
    <Route path="dashboard" component={Dashboard}/>
  </Route>
</Route>

SiteWrapper Comp

export default class SiteWrapper extends React.Component {
    render() {
        return (

                 // Want to replace with <AdminHeader /> if on /admin

                    {this.props.children.props.route.header ? <PageHeader header={this.props.children.props.route.header} /> : null}
                    {this.props.children}

        )
    }
}

Body:
You can use this.props.location.pathname to find the route name

export default class SiteWrapper extends React.Component {
    render() {
        return (
            <div>
                {(this.prop.location.pathname === 'admin')? <AdminHeader/>: <Header/>}
                <div className="container">
                    {this.props.children.props.route.header ? <PageHeader header={this.props.children.props.route.header} /> : null}
                    {this.props.children}
                </div>
                <Footer/>
            </div>
        )
    }
}


问:
Can we add version control for individual objects in Bucket
I know we can add Version control for the whole bucket but can we add the version control separately for individual objects in a bucket.</p>

答:
It is not possible to selectively apply versioning to specific objects in Amazon S3.

However, you could suspend versioning when you do not require it, then resume versioning when you wish to keep new versions of objets.


问:
mysql stored procedure: using declared vars in a limit statement returns an error
I have the following code:

```<code>delimiter ;

DROP PROCEDURE IF EXISTS ufk_test;
delimiter //
CREATE PROCEDURE ufk_test(IN highscoreChallengeId INT UNSIGNED)
BEGIN
DECLARE vLoopOrder INT UNSIGNED DEFAULT 5;
DECLARE vLoopLimit INT UNSIGNED DEFAULT 10;
select * from fb_user LIMIT vLoopOrder,vLoopLimit;
END//

delimiter ;
</code>```

Mysql returns the following error:

```<code>ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'vLoopOrder,vLoopLimit;
END' at line 11
</code>```

it seems that I cannot use declared variables in a LIMIT statement. is there any other way to overcome this ?

of course this is a simple example, here i could just put static numbers but I need to know if it's possible in any way to use any kind of variables with LIMIT.

Thanks

答:
i use something like:</p>

```<code>SET @s = CONCAT('SELECT * FROM table limit  ', vLoopOrder ', ', vLoopLimit);
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
</code>```

Body:
I have the following code:

delimiter ;

DROP PROCEDURE IF EXISTS ufk_test;
delimiter //
CREATE PROCEDURE ufk_test(IN highscoreChallengeId INT UNSIGNED)
BEGIN
DECLARE vLoopOrder INT UNSIGNED DEFAULT 5;
DECLARE vLoopLimit INT UNSIGNED DEFAULT 10;
select * from fb_user LIMIT vLoopOrder,vLoopLimit;
END//

delimiter ;

Mysql returns the following error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'vLoopOrder,vLoopLimit;
END' at line 11

it seems that I cannot use declared variables in a LIMIT statement. is there any other way to overcome this ?

of course this is a simple example, here i could just put static numbers but I need to know if it's possible in any way to use any kind of variables with LIMIT.

Thanks

Body:
i use something like:

SET @s = CONCAT('SELECT * FROM table limit  ', vLoopOrder ', ', vLoopLimit);
PREPARE stmt1 FROM @s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

ContentLicense: CC BY-SA 2.5


问:
If an R package's licence X is, do all the content in that package have to be licenced under X?
Hope the question above is clear.

Now my case: For my package, i'm using several libraries (jars). Each library has been licenced under one of these:  Apache v2, BSD or LPGL.

Edit [some clarification] I have my own java classes packed in a jar. These import classes (dynamic linking) from the libraries mentioned here [End Edit]

Question 1: Can i pack all these libraries in a single package?

Question 1a: If yes, under what licence Apache, BSD, LGPL or any other?

Question 1b: If yes, would it be enough to put all the library names in a NOTICE and to write under what licence is a library licenced together?

Question 2: Or do i have to create for each type of licence a separate package and put libraries in it according to their licence type?

答:
R itself is licensed under the GPL. It contains other functionality released under different licences, such a PCRE which is licensed under BSD. The R sources contain separate licence files for the different components as well as copyright statements/acknowledgements.

Edit [some clarification] So in and of itself, if you are redistributing libraries as part of your package you need to preserve their licence details and respect the licence under which they were distributed. Your package can have whatever licence you want as long as it is not in conflict with the licences of the libraries you are redistributing (unlikely given the ones you cite). You make clear what licence your package is under in the DESCRIPTION file (as Hadley mentions in his answer), but you should make sure a LICENCE, or COPYING file is included in the top level of the package source so it is clear what code is under what licence etc.
[End edit]

The problem you are going to have is that unless we have some lawyers hereabouts who are coders, any advice given should be taken with a big pinch of salt. If you are worried about this, you should seek expert advice.


问:
Instantiate Facebook adaccount object with post data
I am trying to create a new obect of adaccount with the Facebook marketing API with post data. When I hard code the act_{number} it works fine but when I try to insert the post data variable it fails. Here is my code. Thanks for any insight!</p>

```<code><?php
 date_default_timezone_set('America/Los_Angeles');
 if (!session_id()) {
    session_start();
 }

$id = $_POST['actid'];

define('VENDOR_DIR', '/'); // Path to the Vendor directory
$loader = include 'vendor/autoload.php';

use FacebookAds\Api;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\Fields\UserFields;

if(isset($_SESSION['fb_access_token'])) {

// Initialize a new Session and instanciate an Api object
Api::init('{appinfo}', '{appinfo}', $_SESSION['fb_access_token']);

// The Api object is now available trough singleton
$api = Api::instance();

$account = new AdAccount($id);

$adsets = $account->getAdSets(array(
  AdSetFields::NAME,
));

header('Content-Type: application/json');
echo json_encode(array('id'=>$id));
}
?>
</code>```

答: The post data had weird whitespace added. All I needed to do was trim the variable. </p>

Body:
I am trying to create a new obect of adaccount with the Facebook marketing API with post data. When I hard code the act_{number} it works fine but when I try to insert the post data variable it fails. Here is my code. Thanks for any insight!

<?php
 date_default_timezone_set('America/Los_Angeles');
 if (!session_id()) {
    session_start();
 }

$id = $_POST['actid'];

define('VENDOR_DIR', '/'); // Path to the Vendor directory
$loader = include 'vendor/autoload.php';

use FacebookAds\Api;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\Fields\UserFields;

if(isset($_SESSION['fb_access_token'])) {

// Initialize a new Session and instanciate an Api object
Api::init('{appinfo}', '{appinfo}', $_SESSION['fb_access_token']);

// The Api object is now available trough singleton
$api = Api::instance();

$account = new AdAccount($id);

$adsets = $account->getAdSets(array(
  AdSetFields::NAME,
));

header('Content-Type: application/json');
echo json_encode(array('id'=>$id));
}
?>


问:
Display Image from Media Library in Umbraco 7
This should be something embarrassingly simple, but I can't get it to work: I'd simply like to display an image that was uploaded to the Umbraco Media Library (Umbraco 7.1.1) within a Partial View template. The code is

```<code>@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    var imgNode = CurrentPage.BannerBackgroundImage;
    var imgUrl = umbraco.library.NiceUrl(imgNode);
    <div id="banner-wrapper" style="background: url('@imgUrl') center center no-repeat;">
        <!-- some irrelevant content -->
    </div>
}
</code>```

where BannerBackgroundImage is a custom property of the page. When this is displayed, however, the @imgUrl gets replaced with #.

Other alternatives that I've tried are multiple Media Picker images, how to display a Media Picker image, get image from media with Razor, and display image from Media Picker, to name but a few.

I'd really appreciate if somebody could help me with what I believe is a rookie question!

答:
```<code> <img src="@Umbraco.Media(Convert.ToString(@Umbraco.Field("image"))).umbracoFile" alt="" />
</code>```

Body:
This should be something embarrassingly simple, but I can't get it to work: I'd simply like to display an image that was uploaded to the Umbraco Media Library (Umbraco 7.1.1) within a Partial View template. The code is

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    var imgNode = CurrentPage.BannerBackgroundImage;
    var imgUrl = umbraco.library.NiceUrl(imgNode);

}

where BannerBackgroundImage is a custom property of the page. When this is displayed, however, the @imgUrl gets replaced with #.

Other alternatives that I've tried are multiple Media Picker images, how to display a Media Picker image, get image from media with Razor, and display image from Media Picker, to name but a few.

I'd really appreciate if somebody could help me with what I believe is a rookie question!


问:
Errors like "Conflicting types for 'move'" when using Xcode
I got a problem with Xcode, that only appears on Xcode. It does not appear in VisualStudio and not even when compiling over the console (on OS X).

Following errors occur:

Conflicting types for 'move' (Line 4)

Implicit declaration of function 'move' is invalid in C99 (Line 20)

Too many arguments to function call, expected 2, have 4 (Line 20)

Conflicting types for 'move' (Line 42)

Here is the code:

```<code>#include<stdio.h>

void printField(int *field);
void move(int *field, int *posX, int *posY, char zug); //line 4

int main() {

    int field[8][8] = { 0 }, posX=0, posY=0;
    char zug;

    // setzen der Spielfigur
    field[posY][posX] = 1;

    printf("\nBeenden mit x\n");

    do {
        printField(&field[0][0]);
        printf("\nZug [w hoch, a links, s runter, d rechts]: ");
        scanf("%c", &zug);
        move(&field[0][0], &posX, &posY, zug); //line 20
    }while(zug != 'x');

    return 0;
}

// Ausgabe Spielfeld
void printField(int *field) {
    printf("\n");
    int i, j;
    // Schleife fuer Zeilen, Y-Achse
    for(i=0; i<8; i++) {
        // Schleife fuer Spalten, X-Achse
        for(j=0; j<8; j++) {
            printf("%d ", *(field+i*8+j));
        }
        printf("\n");
    }
}

// Spielfigur bewegen
void move(int *field, int *posX, int *posY, char zug) { //line 42
    // alte Position loeschen
    *(field + *posY * 8 + *posX) = 0;

    // neue Position bestimmen
    switch(zug) {
        case 'w': (*posY)--; break;
        case 'a': (*posX)--; break;
        case 's': (*posY)++; break;
        case 'd': (*posX)++; break;
    }

    // Grenzueberschreitung pruefen
    if(*posX < 0) *posX = 7;
    if(*posX > 7) *posX = 0;
    if(*posY < 0) *posY = 7;
    if(*posY > 7) *posY = 0;

    // neue Position setzen
    *(field + *posY * 8 + *posX) = 1;
}
</code>```

答:
```<code>Conflicting types for 'move' (Line 4)
...
Too many arguments to function call, expected 2, have 4 (Line 20)
</code>```

To me this looks as if the <stdio.h> in use pulls in an existing declaration of a function called move() (specifying 2 but 4 parameters).

Try renaming your function move() to something like my_move().

Body:
I got a problem with Xcode, that only appears on Xcode. It does not appear in VisualStudio and not even when compiling over the console (on OS X).

Following errors occur:

Conflicting types for 'move' (Line 4)

Implicit declaration of function 'move' is invalid in C99 (Line 20)

Too many arguments to function call, expected 2, have 4 (Line 20)

Conflicting types for 'move' (Line 42)

Here is the code:

#include<stdio.h>

void printField(int *field);
void move(int *field, int *posX, int *posY, char zug); //line 4

int main() {

    int field[8][8] = { 0 }, posX=0, posY=0;
    char zug;

    // setzen der Spielfigur
    field[posY][posX] = 1;

    printf("\nBeenden mit x\n");

    do {
        printField(&field[0][0]);
        printf("\nZug [w hoch, a links, s runter, d rechts]: ");
        scanf("%c", &zug);
        move(&field[0][0], &posX, &posY, zug); //line 20
    }while(zug != 'x');

    return 0;
}

// Ausgabe Spielfeld
void printField(int *field) {
    printf("\n");
    int i, j;
    // Schleife fuer Zeilen, Y-Achse
    for(i=0; i<8; i++) {
        // Schleife fuer Spalten, X-Achse
        for(j=0; j<8; j++) {
            printf("%d ", *(field+i*8+j));
        }
        printf("\n");
    }
}

// Spielfigur bewegen
void move(int *field, int *posX, int *posY, char zug) { //line 42
    // alte Position loeschen
    *(field + *posY * 8 + *posX) = 0;

    // neue Position bestimmen
    switch(zug) {
        case 'w': (*posY)--; break;
        case 'a': (*posX)--; break;
        case 's': (*posY)++; break;
        case 'd': (*posX)++; break;
    }

    // Grenzueberschreitung pruefen
    if(*posX < 0) *posX = 7;
    if(*posX > 7) *posX = 0;
    if(*posY < 0) *posY = 7;
    if(*posY > 7) *posY = 0;

    // neue Position setzen
    *(field + *posY * 8 + *posX) = 1;
}

Body:
Conflicting types for 'move' (Line 4)
...
Too many arguments to function call, expected 2, have 4 (Line 20)

To me this looks as if the <stdio.h> in use pulls in an existing declaration of a function called move() (specifying 2 but 4 parameters).

Try renaming your function move() to something like my_move().


问:
How to resolve “Validation (): Element ‘x’ is not supported” warning in Visual Studio 2010
I have been getting all of these "Validation (): Element 'x' is not supported" warnings and I can't seem to find a way to get rid of them. Here are two examples:

Validation (XHTML 1.0 Transitional): Attribute 'name' is not a valid attribute of element 'ul'.

Validation (CSS 2.1): 'border-radius' is not a known CSS property name.

I have searched on the web and all solutions point to removing the following folder:

```<code>C:\Users\{username}\AppData\Roaming \Microsoft\VisualStudio\10.0\ReflectedSchemas
</code>```

Which seems to fix 90% of people's issues, however I don't have that folder anywhere on my computer!

I am using Visual Studio 10 SP1 and this project is an MVC 3 project using Razor and HTML5.

So can anyone else suggest what else might be causing the issue?

Thanks very much.

答:
You have to remove

```<code>xmlns="https://www.w3.org/1999/xhtml"
</code>```

let it remain

```<code><!DocType Html>
</code>```

only above

Body:
I have been getting all of these "Validation (): Element 'x' is not supported" warnings and I can't seem to find a way to get rid of them. Here are two examples:

Validation (XHTML 1.0 Transitional): Attribute 'name' is not a valid attribute of element 'ul'.

Validation (CSS 2.1): 'border-radius' is not a known CSS property name.

I have searched on the web and all solutions point to removing the following folder:

C:\Users\{username}\AppData\Roaming \Microsoft\VisualStudio\10.0\ReflectedSchemas

Which seems to fix 90% of people's issues, however I don't have that folder anywhere on my computer!

I am using Visual Studio 10 SP1 and this project is an MVC 3 project using Razor and HTML5.

So can anyone else suggest what else might be causing the issue?

Thanks very much.

Body:
You have to remove

xmlns="https://www.w3.org/1999/xhtml"

let it remain

<!DocType Html>

only above


问:
Ec2 instance getting terminated instantly in cloud formation
I have created a simple JSON template for launching an EC2 instance using CloudFormation. The JSON code works for RedHat ami-2051294a (in us-east-1 region) but does not work for Amazon Linux ami-0b33d91d.

What could be the issue?

```<code>  "Resources": {
    "Ec2Instance" :{
      "Type" : "AWS::EC2::Instance",
      "Properties" : {
        "Tags": [
          { "Key" : "Name" , "Value" : "BIP-Spark" }
           ],
        "KeyName": { "Ref" : "KeyName" },
        "InstanceType" : { "Ref" : "BipDevInstanceType" },
        "ImageId" : { "Ref" : "NATAMI" },
        "IamInstanceProfile" : { "Ref": "RoleName" },
        "BlockDeviceMappings" : [ {
           "DeviceName" : "/dev/sda1",
           "Ebs" : { "VolumeSize" : "30", "VolumeType": "gp2" }
            },
           {
           "DeviceName" : "/dev/sdb",
           "Ebs" : { "VolumeSize" : "30", "VolumeType": "gp2" }
           }
        ],
        "NetworkInterfaces" : [ {
           "GroupSet": [ "sg-***" ],
           "SubnetId": { "Ref" : "SubnetID" },
           "AssociatePublicIpAddress": "true",
           "DeleteOnTermination": "true",
           "DeviceIndex":"0" }
         ]
        }
      }
    }
}
</code>```

答:
Both AMIs launched perfectly well for me.

Here is the minimal version of the template that I used to successfully launch an Amazon EC2 instance with Amazon Linux AMI ami-0b33d91d:

```<code>{
   "AWSTemplateFormatVersion":"2010-09-09",

  "Resources": {
    "Ec2Instance" :{
      "Type" : "AWS::EC2::Instance",
      "Properties" : {
        "InstanceType" : "t2.micro",
        "ImageId" : "ami-0b33d91d",
        "NetworkInterfaces" : [ {
           "GroupSet": [ "sg-xxxxxxxx" ],
           "SubnetId": "subnet-xxxxxxxx",
           "AssociatePublicIpAddress": "true",
           "DeleteOnTermination": "true",
           "DeviceIndex":"0" }
         ]
        }
      }
    }
}
</code>```

The instance successfully entered the Running state and kept running correctly.

It is likely that one of your manually-entered parameters was incorrect.

Body:
I have created a simple JSON template for launching an EC2 instance using CloudFormation. The JSON code works for RedHat ami-2051294a (in us-east-1 region) but does not work for Amazon Linux ami-0b33d91d.

What could be the issue?

  "Resources": {
    "Ec2Instance" :{
      "Type" : "AWS::EC2::Instance",
      "Properties" : {
        "Tags": [
          { "Key" : "Name" , "Value" : "BIP-Spark" }
           ],
        "KeyName": { "Ref" : "KeyName" },
        "InstanceType" : { "Ref" : "BipDevInstanceType" },
        "ImageId" : { "Ref" : "NATAMI" },
        "IamInstanceProfile" : { "Ref": "RoleName" },
        "BlockDeviceMappings" : [ {
           "DeviceName" : "/dev/sda1",
           "Ebs" : { "VolumeSize" : "30", "VolumeType": "gp2" }
            },
           {
           "DeviceName" : "/dev/sdb",
           "Ebs" : { "VolumeSize" : "30", "VolumeType": "gp2" }
           }
        ],
        "NetworkInterfaces" : [ {
           "GroupSet": [ "sg-***" ],
           "SubnetId": { "Ref" : "SubnetID" },
           "AssociatePublicIpAddress": "true",
           "DeleteOnTermination": "true",
           "DeviceIndex":"0" }
         ]
        }
      }
    }
}

Body:
Both AMIs launched perfectly well for me.

Here is the minimal version of the template that I used to successfully launch an Amazon EC2 instance with Amazon Linux AMI ami-0b33d91d:

{
   "AWSTemplateFormatVersion":"2010-09-09",

  "Resources": {
    "Ec2Instance" :{
      "Type" : "AWS::EC2::Instance",
      "Properties" : {
        "InstanceType" : "t2.micro",
        "ImageId" : "ami-0b33d91d",
        "NetworkInterfaces" : [ {
           "GroupSet": [ "sg-xxxxxxxx" ],
           "SubnetId": "subnet-xxxxxxxx",
           "AssociatePublicIpAddress": "true",
           "DeleteOnTermination": "true",
           "DeviceIndex":"0" }
         ]
        }
      }
    }
}

The instance successfully entered the Running state and kept running correctly.

It is likely that one of your manually-entered parameters was incorrect.


问:
Retrieve Mac address in powershell and convert it to decimal format
I can easily get Mac address in powershell by:

```<code>$localMac=Get-WmiObject win32_networkadapterconfiguration | select macaddress
echo $localMac[0]
</code>```

The result is:

```<code>macaddress
----------
E8:21:32:E5:F4:6A
</code>```

How can I change result to decimal format in powershell? Just for example 7436378647

I tried

```<code>$MacAddressConverted = $localMac[0] -replace '(:|-|\.)'
echo $MacAddressConverted
</code>```

It returns

```<code>@{macaddress=E82132E5F46A}
</code>```

It's close what I would like to achive but it still has @{macadress= and it's not converted to decimal

答:
```<code>$MAC = ((Get-WmiObject Win32_NetworkAdapterConfiguration |
        Where-Object MACAddress |
        Select-Object -ExpandProperty MACAddress -First 1
    ) -replace ':'
)
[int64]$('0x' + $MAC)
</code>```

EDIT: to get a more verbose version with a [PSCustomObject]

```<code>Get-WmiObject win32_networkadapterconfiguration |
    Where-Object MacAddress | ForEach {
        [PSCustomObject]@{
        'MAC_hex' = $_.MacAddress
        'MAC_dec' = [int64]("0x$($_.MacAddress.Replace(':',''))")
        'ServiceName' = $_.ServiceName
        'Description'=$_.Description}
}
</code>```

Sample output:

```<code>MAC_hex                  MAC_dec ServiceName Description
-------                  ------- ----------- -----------
0A:00:27:xx:xx:xx 10995770599999 VBoxNetAdp  VirtualBox Host-Only Ethernet Adapter #3
00:23:54:xx:xx:xx   151749299999 rt640x64    Realtek PCIe GBE Family Controller
</code>```

Body:
I can easily get Mac address in powershell by:

$localMac=Get-WmiObject win32_networkadapterconfiguration | select macaddress
echo $localMac[0]

The result is:

macaddress
----------
E8:21:32:E5:F4:6A

How can I change result to decimal format in powershell? Just for example 7436378647

I tried

$MacAddressConverted = $localMac[0] -replace '(:|-|\.)'
echo $MacAddressConverted

It returns

@{macaddress=E82132E5F46A}

It's close what I would like to achive but it still has @{macadress= and it's not converted to decimal

Body:
$MAC = ((Get-WmiObject Win32_NetworkAdapterConfiguration |
        Where-Object MACAddress |
        Select-Object -ExpandProperty MACAddress -First 1
    ) -replace ':'
)
[int64]$('0x' + $MAC)

EDIT: to get a more verbose version with a [PSCustomObject]

Get-WmiObject win32_networkadapterconfiguration |
    Where-Object MacAddress | ForEach {
        [PSCustomObject]@{
        'MAC_hex' = $_.MacAddress
        'MAC_dec' = [int64]("0x$($_.MacAddress.Replace(':',''))")
        'ServiceName' = $_.ServiceName
        'Description'=$_.Description}
}

Sample output:

MAC_hex                  MAC_dec ServiceName Description
-------                  ------- ----------- -----------
0A:00:27:xx:xx:xx 10995770599999 VBoxNetAdp  VirtualBox Host-Only Ethernet Adapter #3
00:23:54:xx:xx:xx   151749299999 rt640x64    Realtek PCIe GBE Family Controller


问:
Configuring snake_case query parameter using Gson in Spring Boot
I try to configure Gson as my JSON mapper to accept "snake_case" query parameter, and translate them into standard Java "camelCase" parameters.

First of all, I know I could use the @SerializedName annotation to customise the serialized name of each field, but this will involve some manual work.

After doing some search, I believe the following approach should work (please correct me if I am wrong).

Use Gson as the default JSON mapper of Spring Boot

spring.http.converters.preferred-json-mapper=gson

Configuring Gson before GsonHttpMessageConverter is created as described here

Customising the Gson naming policy in step 2 according to GSON Field Naming Policy

private GsonHttpMessageConverter createGsonHttpMessageConverter() {
    Gson gson = new GsonBuilder()
                   .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                   .create();

    GsonHttpMessageConverter gsonConverter = new GsonHttpMessageConverter();
    gsonConverter.setGson(gson);

    return gsonConverter;
}
```

<p>Then I create a simple controller like this:</p>

<pre class="lang-java prettyprint-override"><code>@RequestMapping(value = "/example/gson-naming-policy")
public Object testNamingPolicy(ExampleParam data) {
    return data.getCamelCase();
}
</code>```

With the following Param class:

import lombok.Data;

@Data
public class ExampleParam {

    private String camelCase;

}
```

But when I call the controller with query parameter ?camel_case=hello, the data.camelCase could not been populated (and it's null). When I change the query parameters to ?camelCase=hello then it could be set, which mean my setting is not working as expected.

Any hint would be highly appreciated. Thanks in advance!

答:
It's a nice question. If I understand how Spring MVC works behind the scenes, no HTTP converters are used for @ModelAttribute-driven. It can be inspected easily when throwing an exception from your ExampleParam constructor or the ExampleParam.setCamelCase method (de-Lombok first) -- Spring uses its bean utilities that use public (!) ExampleParam.setCamelCase to set the DTO value. Another proof is that no Gson.fromJson is never invoked regardless how your Gson converter is configured. So, your camelCase confuses you because the default Gson instance uses this strategy as well as Spring does -- so this is just a matter of confusion.

In order to make it work, you have to create a custom Gson-aware HandlerMethodArgumentResolver implementation. Let's assume we support POJO only (not lists, maps or primitives).

@Configuration
@EnableWebMvc
class WebMvcConfiguration
        extends WebMvcConfigurerAdapter {

    private static final Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES)
            .create();

    @Override
    public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new HandlerMethodArgumentResolver() {
            @Override
            public boolean supportsParameter(final MethodParameter parameter) {
                // It must be never a primitive, array, string, boxed number, map or list -- and whatever you configure ;)
                final Class<?> parameterType = parameter.getParameterType();
                return !parameterType.isPrimitive()
                        && !parameterType.isArray()
                        && parameterType != String.class
                        && !Number.class.isAssignableFrom(parameterType)
                        && !Map.class.isAssignableFrom(parameterType)
                        && !List.class.isAssignableFrom(parameterType);
            }

            @Override
            public Object resolveArgument(final MethodParameter parameter, final ModelAndViewContainer mavContainer, final NativeWebRequest webRequest,
                    final WebDataBinderFactory binderFactory) {
                // Now we're deconstructing the request parameters creating a JSON tree, because Gson can convert from JSON trees to POJOs transparently
                // Also note parameter.getGenericParameterType() -- it's better that Class<?> that cannot hold generic types parameterization
                return gson.fromJson(
                        parameterMapToJsonElement(webRequest.getParameterMap()),
                        parameter.getGenericParameterType()
                );
            }
        });
    }

    ...

    private static JsonElement parameterMapToJsonElement(final Map<String, String[]> parameters) {
        final JsonObject jsonObject = new JsonObject();
        for ( final Entry<String, String[]> e : parameters.entrySet() ) {
            final String key = e.getKey();
            final String[] value = e.getValue();
            final JsonElement jsonValue;
            switch ( value.length ) {
            case 0:
                // As far as I understand, this must never happen, but I'm not sure
                jsonValue = JsonNull.INSTANCE;
                break;
            case 1:
                // If there's a single value only, let's convert it to a string literal
                // Gson is good at "weak typing": strings can be parsed automatically to numbers and booleans
                jsonValue = new JsonPrimitive(value[0]);
                break;
            default:
                // If there are more than 1 element -- make it an array
                final JsonArray jsonArray = new JsonArray();
                for ( int i = 0; i < value.length; i++ ) {
                    jsonArray.add(value[i]);
                }
                jsonValue = jsonArray;
                break;
            }
            jsonObject.add(key, jsonValue);
        }
        return jsonObject;
    }

}
```

So, here are the results:

http://localhost:8080/?camelCase=hello => (empty)

http://localhost:8080/?camel_case=hello => "hello"

Body:
I try to configure Gson as my JSON mapper to accept "snake_case" query parameter, and translate them into standard Java "camelCase" parameters.

First of all, I know I could use the @SerializedName annotation to customise the serialized name of each field, but this will involve some manual work.

After doing some search, I believe the following approach should work (please correct me if I am wrong).

Use Gson as the default JSON mapper of Spring Boot

spring.http.converters.preferred-json-mapper=gson

Configuring Gson before GsonHttpMessageConverter is created as described here

Customising the Gson naming policy in step 2 according to GSON Field Naming Policy

private GsonHttpMessageConverter createGsonHttpMessageConverter() {
    Gson gson = new GsonBuilder()
                   .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                   .create();

    GsonHttpMessageConverter gsonConverter = new GsonHttpMessageConverter();
    gsonConverter.setGson(gson);

    return gsonConverter;
}

Then I create a simple controller like this:

@RequestMapping(value = "/example/gson-naming-policy")
public Object testNamingPolicy(ExampleParam data) {
    return data.getCamelCase();
}

With the following Param class:

import lombok.Data;

@Data
public class ExampleParam {

    private String camelCase;

}

But when I call the controller with query parameter ?camel_case=hello, the data.camelCase could not been populated (and it's null). When I change the query parameters to ?camelCase=hello then it could be set, which mean my setting is not working as expected.

Any hint would be highly appreciated. Thanks in advance!

Body:
It's a nice question. If I understand how Spring MVC works behind the scenes, no HTTP converters are used for @ModelAttribute-driven. It can be inspected easily when throwing an exception from your ExampleParam constructor or the ExampleParam.setCamelCase method (de-Lombok first) -- Spring uses its bean utilities that use public (!) ExampleParam.setCamelCase to set the DTO value. Another proof is that no Gson.fromJson is never invoked regardless how your Gson converter is configured. So, your camelCase confuses you because the default Gson instance uses this strategy as well as Spring does -- so this is just a matter of confusion.

In order to make it work, you have to create a custom Gson-aware HandlerMethodArgumentResolver implementation. Let's assume we support POJO only (not lists, maps or primitives).

@Configuration
@EnableWebMvc
class WebMvcConfiguration
        extends WebMvcConfigurerAdapter {

    private static final Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES)
            .create();

    @Override
    public void addArgumentResolvers(final List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new HandlerMethodArgumentResolver() {
            @Override
            public boolean supportsParameter(final MethodParameter parameter) {
                // It must be never a primitive, array, string, boxed number, map or list -- and whatever you configure ;)
                final Class<?> parameterType = parameter.getParameterType();
                return !parameterType.isPrimitive()
                        && !parameterType.isArray()
                        && parameterType != String.class
                        && !Number.class.isAssignableFrom(parameterType)
                        && !Map.class.isAssignableFrom(parameterType)
                        && !List.class.isAssignableFrom(parameterType);
            }

            @Override
            public Object resolveArgument(final MethodParameter parameter, final ModelAndViewContainer mavContainer, final NativeWebRequest webRequest,
                    final WebDataBinderFactory binderFactory) {
                // Now we're deconstructing the request parameters creating a JSON tree, because Gson can convert from JSON trees to POJOs transparently
                // Also note parameter.getGenericParameterType() -- it's better that Class<?> that cannot hold generic types parameterization
                return gson.fromJson(
                        parameterMapToJsonElement(webRequest.getParameterMap()),
                        parameter.getGenericParameterType()
                );
            }
        });
    }

    ...

    private static JsonElement parameterMapToJsonElement(final Map<String, String[]> parameters) {
        final JsonObject jsonObject = new JsonObject();
        for ( final Entry<String, String[]> e : parameters.entrySet() ) {
            final String key = e.getKey();
            final String[] value = e.getValue();
            final JsonElement jsonValue;
            switch ( value.length ) {
            case 0:
                // As far as I understand, this must never happen, but I'm not sure
                jsonValue = JsonNull.INSTANCE;
                break;
            case 1:
                // If there's a single value only, let's convert it to a string literal
                // Gson is good at "weak typing": strings can be parsed automatically to numbers and booleans
                jsonValue = new JsonPrimitive(value[0]);
                break;
            default:
                // If there are more than 1 element -- make it an array
                final JsonArray jsonArray = new JsonArray();
                for ( int i = 0; i < value.length; i++ ) {
                    jsonArray.add(value[i]);
                }
                jsonValue = jsonArray;
                break;
            }
            jsonObject.add(key, jsonValue);
        }
        return jsonObject;
    }

}

So, here are the results:

http://localhost:8080/?camelCase=hello => (empty)

http://localhost:8080/?camel_case=hello => "hello"


问:
Exception building gradle task launchIosDevice
After I updated Ios at new version (I think before this thing it was ok), I have this exception when I try to launch Gradle task "launchIosDevice":

```<code>java.lang.NullPointerException
        at org.robovm.libimobiledevice.Callbacks.callInstproxyCallback(Callbacks.java:66)
</code>```

Can anyone help me to understand the problem?
Thank you in advance.

```<code>buildscript {

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'org.javafxports:jfxmobile-plugin:1.3.2'

    }
}

apply plugin: 'org.javafxports.jfxmobile'
repositories {
    jcenter()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases/'
    }
    maven {
       url('https://oss.sonatype.org/content/repositories/snapshots/')
    }
}

mainClassName = 'it.wstech.lex.LXMainApplication'

dependencies {
    compile 'com.airhacks:afterburner.mfx:1.6.2'
    compile fileTree(dir: '***', include: ['*.jar'])
    compile fileTree(dir: '***', include: ['*.jar'])
    compile fileTree(dir: '***', include: ['*.jar'])
    compile fileTree(dir: 'lib', include: ['*.jar'])

    androidCompile 'org.glassfish:javax.json:1.0.4'
    compile "com.gluonhq:charm:4.3.0"

}

jfxmobile {

    javafxportsVersion = '8.60.8'

    downConfig {
        version "3.3.0-SNAPSHOT"
        plugins 'display','browser','cache', 'lifecycle', 'statusbar', 'storage', 'local-notifications', 'device','connectivity','dialer','orientation','runtime-args', 'push-notifications'
    }
    android {
      manifest = 'src/android/AndroidManifest.xml'
      compileSdkVersion = 21
         signingConfig {
            storeFile file('***')
            storePassword 'wstechsrl'
            keyAlias '***'
            keyPassword '***'
        }

         dexOptions {
        javaMaxHeapSize "4g"
    }
    }

    ios {

    iosSignIdentity = '****'
    iosProvisioningProfile = '****'
        infoPList = file('src/ios/Default-Info.plist')
                       arch = 'arm64'
                        ipaArchs=['arm64']

        forceLinkClasses = [
                'com.gluonhq.**.*',
                'it.wstech.**.*',
                'javax.annotations.**.*',
                'javax.inject.**.*',
                'javax.json.**.*',
                'org.glassfish.json.**.*'
        ]

    }
}

[ 96%] Uploading /Volumes/RoboVM RAM Disk/tmp/Users/wstechsrl/Desktop/workspace_fx/strikenball/build/javafxports/tmp/ios/strikenball.app/lib/robovm-cocoatouch-2.3.0.jar...
[ 97%] Uploading /Volumes/RoboVM RAM Disk/tmp/Users/wstechsrl/Desktop/workspace_fx/strikenball/build/javafxports/tmp/ios/strikenball.app/lib/robovm-objc-2.3.0.jar...
[ 98%] Uploading /Volumes/RoboVM RAM Disk/tmp/Users/wstechsrl/Desktop/workspace_fx/strikenball/build/javafxports/tmp/ios/strikenball.app/strikenball...
[100%] Upload complete
[  0%] Beginning installation...
[  5%] CreatingStagingDirectory
[ 15%] ExtractingPackage
[ 20%] InspectingPackage
[ 20%] TakingInstallLock
[ 30%] PreflightingApplication
[ 30%] InstallingEmbeddedProfile
[ 40%] VerifyingApplication
[ 50%] CreatingContainer
[ 60%] InstallingApplication
[ 70%] PostflightingApplication
[ 80%] SandboxingApplication
[ 90%] GeneratingApplicationMap
java.lang.NullPointerException
        at org.robovm.libimobiledevice.Callbacks.callInstproxyCallback(Callbacks.java:66)
</code>```

答:
After updating my iPad to iOS 10.3 I can reproduce the error running ./gradlew --info launchIOSDevice:

```<code>[100%] Upload complete
[  0%] Beginning installation...
[  5%] CreatingStagingDirectory
[ 15%] ExtractingPackage
[ 20%] InspectingPackage
[ 20%] TakingInstallLock
[ 30%] PreflightingApplication
[ 30%] InstallingEmbeddedProfile
[ 40%] VerifyingApplication
[ 50%] CreatingContainer
[ 60%] InstallingApplication
[ 70%] PostflightingApplication
[ 80%] SandboxingApplication
[ 90%] GeneratingApplicationMap
java.lang.NullPointerException
        at org.robovm.libimobiledevice.Callbacks.callInstproxyCallback(Callbacks.java:66)
</code>```

There is something broken with the new iOS version, and this is something that needs to be fixed by Mobidevelop, the Robovm fork. Once they've solved it, it will require a new version of the jfxmobile plugin.

There is already an issue created, but maybe you can also post yours.

In the meantime, the workaround is installing the app manually once you have built the ipa:

Run ./gradlew createIpa, locate the ipa under /build/javafxports/ios, double click on it and it will opened with iTunes. Then it will be downloaded and installed on your iOS device.

Body:
After I updated Ios at new version (I think before this thing it was ok), I have this exception when I try to launch Gradle task "launchIosDevice":

java.lang.NullPointerException
        at org.robovm.libimobiledevice.Callbacks.callInstproxyCallback(Callbacks.java:66)

Can anyone help me to understand the problem?
Thank you in advance.

buildscript {

    repositories {
        jcenter()
    }
    dependencies {
        classpath 'org.javafxports:jfxmobile-plugin:1.3.2'

    }
}

apply plugin: 'org.javafxports.jfxmobile'
repositories {
    jcenter()
    maven {
        url 'http://nexus.gluonhq.com/nexus/content/repositories/releases/'
    }
    maven {
       url('https://oss.sonatype.org/content/repositories/snapshots/')
    }
}

mainClassName = 'it.wstech.lex.LXMainApplication'

dependencies {
    compile 'com.airhacks:afterburner.mfx:1.6.2'
    compile fileTree(dir: '***', include: ['*.jar'])
    compile fileTree(dir: '***', include: ['*.jar'])
    compile fileTree(dir: '***', include: ['*.jar'])
    compile fileTree(dir: 'lib', include: ['*.jar'])

    androidCompile 'org.glassfish:javax.json:1.0.4'
    compile "com.gluonhq:charm:4.3.0"

}

jfxmobile {

    javafxportsVersion = '8.60.8'

    downConfig {
        version "3.3.0-SNAPSHOT"
        plugins 'display','browser','cache', 'lifecycle', 'statusbar', 'storage', 'local-notifications', 'device','connectivity','dialer','orientation','runtime-args', 'push-notifications'
    }
    android {
      manifest = 'src/android/AndroidManifest.xml'
      compileSdkVersion = 21
         signingConfig {
            storeFile file('***')
            storePassword 'wstechsrl'
            keyAlias '***'
            keyPassword '***'
        }

         dexOptions {
        javaMaxHeapSize "4g"
    }
    }

    ios {

    iosSignIdentity = '****'
    iosProvisioningProfile = '****'
        infoPList = file('src/ios/Default-Info.plist')
                       arch = 'arm64'
                        ipaArchs=['arm64']

        forceLinkClasses = [
                'com.gluonhq.**.*',
                'it.wstech.**.*',
                'javax.annotations.**.*',
                'javax.inject.**.*',
                'javax.json.**.*',
                'org.glassfish.json.**.*'
        ]

    }
}

[ 96%] Uploading /Volumes/RoboVM RAM Disk/tmp/Users/wstechsrl/Desktop/workspace_fx/strikenball/build/javafxports/tmp/ios/strikenball.app/lib/robovm-cocoatouch-2.3.0.jar...
[ 97%] Uploading /Volumes/RoboVM RAM Disk/tmp/Users/wstechsrl/Desktop/workspace_fx/strikenball/build/javafxports/tmp/ios/strikenball.app/lib/robovm-objc-2.3.0.jar...
[ 98%] Uploading /Volumes/RoboVM RAM Disk/tmp/Users/wstechsrl/Desktop/workspace_fx/strikenball/build/javafxports/tmp/ios/strikenball.app/strikenball...
[100%] Upload complete
[  0%] Beginning installation...
[  5%] CreatingStagingDirectory
[ 15%] ExtractingPackage
[ 20%] InspectingPackage
[ 20%] TakingInstallLock
[ 30%] PreflightingApplication
[ 30%] InstallingEmbeddedProfile
[ 40%] VerifyingApplication
[ 50%] CreatingContainer
[ 60%] InstallingApplication
[ 70%] PostflightingApplication
[ 80%] SandboxingApplication
[ 90%] GeneratingApplicationMap
java.lang.NullPointerException
        at org.robovm.libimobiledevice.Callbacks.callInstproxyCallback(Callbacks.java:66)

Body:
After updating my iPad to iOS 10.3 I can reproduce the error running ./gradlew --info launchIOSDevice:

[100%] Upload complete
[  0%] Beginning installation...
[  5%] CreatingStagingDirectory
[ 15%] ExtractingPackage
[ 20%] InspectingPackage
[ 20%] TakingInstallLock
[ 30%] PreflightingApplication
[ 30%] InstallingEmbeddedProfile
[ 40%] VerifyingApplication
[ 50%] CreatingContainer
[ 60%] InstallingApplication
[ 70%] PostflightingApplication
[ 80%] SandboxingApplication
[ 90%] GeneratingApplicationMap
java.lang.NullPointerException
        at org.robovm.libimobiledevice.Callbacks.callInstproxyCallback(Callbacks.java:66)

There is something broken with the new iOS version, and this is something that needs to be fixed by Mobidevelop, the Robovm fork. Once they've solved it, it will require a new version of the jfxmobile plugin.

There is already an issue created, but maybe you can also post yours.

In the meantime, the workaround is installing the app manually once you have built the ipa:

Run ./gradlew createIpa, locate the ipa under /build/javafxports/ios, double click on it and it will opened with iTunes. Then it will be downloaded and installed on your iOS device.


问:
String trouble in Rave Reports 8
We are currently working with Delphi 2006, but we are now very ready to move on to Delphi 2010.

The problem lies in our Rave reports, though...

We just get to many string errors when running our reports with Rave 8.  And they just don't make any sense.  (The reports compile with no error, and we can even run them without any error in Rave 6.)

Update:
The errors occurs inside the event scripts in the reports itself.  The errors are related to strings and string concatenation.

For instance:

```<code>//This event causes access violation (in rtl140.bpl) at run time
{ Event for Page1.OnBeforeReport }
function Page1_OnBeforeReport(Self: TRavePage);
var
  s: String;
begin
  s := 'My text in param';
  s := s + ' and som more text';
  s := copy(s,1,length(s)) + ' and then some more';           //<-- This line causes AV
  RaveProject.SetParam('MyTestParam', s);
end OnBeforeReport;

//This event works OK
{ Event for Page1.OnBeforeReport }
function Page1_OnBeforeReport(Self: TRavePage);
var
  s: String;
begin
  s := 'My text in param';
  s := s + ' and som more text';
  s := copy(s,1,length(s));                                   //<-- This line is OK
  RaveProject.SetParam('MyTestParam', s);
end OnBeforeReport;

//This event works OK too
{ Event for Page1.OnBeforeReport }
function Page1_OnBeforeReport(Self: TRavePage);
var
  s: String;
begin
  s := 'My text in param';
  s := s + ' and som more text';
  s := copy(s,1,length(s)) + s;                               //<-- This line is OK
  RaveProject.SetParam('MyTestParam', s);
end OnBeforeReport;
</code>```

We really want to stick to Rave, because we have a lot of reports (150+) with a lot of functionality (sql statements, events etc).  Besides, we have customers who have designed their own custom reports as well.

Does anybody know the reason for these errors?

Is there any solution or workaround to these problems?

答:
Since Delphi 2009 Unicode has become the default string encoding, so when you declare a String var you're getting a Unicode String instead of an Ansi String.
There's no way to change the default behaviour (which has been the source of a great deal of hard-to-find-bugs and harder-if-no-impossible-to-fix ones).
If the problem comes from your source code you can try explicitly changing the string encoding to ANSI instead of using the default.
If the problem comes from the reports created with the Rave Editor, a workaround we found was to compile the reports with an older version of Rave (prior 7.5), which seems to work fine.</p>

Title: String trouble in Rave Reports 8

Body:
We are currently working with Delphi 2006, but we are now very ready to move on to Delphi 2010.

The problem lies in our Rave reports, though...

We just get to many string errors when running our reports with Rave 8.  And they just don't make any sense.  (The reports compile with no error, and we can even run them without any error in Rave 6.)

Update:
The errors occurs inside the event scripts in the reports itself.  The errors are related to strings and string concatenation.

For instance:

//This event causes access violation (in rtl140.bpl) at run time
{ Event for Page1.OnBeforeReport }
function Page1_OnBeforeReport(Self: TRavePage);
var
  s: String;
begin
  s := 'My text in param';
  s := s + ' and som more text';
  s := copy(s,1,length(s)) + ' and then some more';           //<-- This line causes AV
  RaveProject.SetParam('MyTestParam', s);
end OnBeforeReport;

//This event works OK
{ Event for Page1.OnBeforeReport }
function Page1_OnBeforeReport(Self: TRavePage);
var
  s: String;
begin
  s := 'My text in param';
  s := s + ' and som more text';
  s := copy(s,1,length(s));                                   //<-- This line is OK
  RaveProject.SetParam('MyTestParam', s);
end OnBeforeReport;

//This event works OK too
{ Event for Page1.OnBeforeReport }
function Page1_OnBeforeReport(Self: TRavePage);
var
  s: String;
begin
  s := 'My text in param';
  s := s + ' and som more text';
  s := copy(s,1,length(s)) + s;                               //<-- This line is OK
  RaveProject.SetParam('MyTestParam', s);
end OnBeforeReport;

We really want to stick to Rave, because we have a lot of reports (150+) with a lot of functionality (sql statements, events etc).  Besides, we have customers who have designed their own custom reports as well.

Does anybody know the reason for these errors?

Is there any solution or workaround to these problems?


问:
Header wont redirect me, can't figure out why
i cannot figure out why this will not redirect me or tell me any errors, it adds to the database but it does not redirect</p>

```<code><?php
    ob_start();

        $db = mysqli_connect("localhost", "root", "", "autentificare");

        if (isset($_POST['register_btn'])){
            session_start();
            $username = mysql_real_escape_string($_POST['username']);
            $email = mysql_real_escape_string($_POST['email']);
            $password = mysql_real_escape_string($_POST['password']);
            $passwordc = mysql_real_escape_string($_POST['passwordc']);

            if ($password == $passwordc){
                    $password = md5($password);
                    $sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')" ;
                    mysqli_query($db, $sql);
                    $_SESSION['message'] = "Succesfully logged in";
                    $_SESSION['username'] = $username;
                    header( "location : home.php");
            }else{
                    $_SESSION['message'] = "Passwords do not match";

            }
        }
    ob_end_flush();
    ?>
</code>```

答:
You're sending the header, but then letting the script continue to process. Use this:</p>

```<code>header( "location : home.php");
exit();
</code>```

Body:
i cannot figure out why this will not redirect me or tell me any errors, it adds to the database but it does not redirect

<?php
    ob_start();

        $db = mysqli_connect("localhost", "root", "", "autentificare");

        if (isset($_POST['register_btn'])){
            session_start();
            $username = mysql_real_escape_string($_POST['username']);
            $email = mysql_real_escape_string($_POST['email']);
            $password = mysql_real_escape_string($_POST['password']);
            $passwordc = mysql_real_escape_string($_POST['passwordc']);

            if ($password == $passwordc){
                    $password = md5($password);
                    $sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')" ;
                    mysqli_query($db, $sql);
                    $_SESSION['message'] = "Succesfully logged in";
                    $_SESSION['username'] = $username;
                    header( "location : home.php");
            }else{
                    $_SESSION['message'] = "Passwords do not match";

            }
        }
    ob_end_flush();
    ?>

Body:
You're sending the header, but then letting the script continue to process. Use this:

header( "location : home.php");
exit();


问:
PHP Session Variables Session_name
Good day!

How can I change the name of my session_name() variable. Below are my sample codes from php.net

```<code><?php
$previous_name = session_name("WebsiteID");
echo "The previous session name was $previous_name<br />";
?>
</code>```

It still echoes PHPSESSID instead of WebsiteID, I'm using PHP 7 and alsor trying it to my other workstation running PHP 5.3. Did I missed something?? Please Advise.

Thanks!

答:
From the manual

Return Values

Returns the name of the current session. If name is given and function
  updates the session name, name of the old session is returned

so this is expected behaviour: the result is the OLD value, not the new value.

That's why the example text is talking about The previous session, and not the current session I'd assume :D

Title: PHP Session Variables Session_name

Body:
Good day!

How can I change the name of my session_name() variable. Below are my sample codes from php.net

<?php
$previous_name = session_name("WebsiteID");
echo "The previous session name was $previous_name
";
?>

It still echoes PHPSESSID instead of WebsiteID, I'm using PHP 7 and alsor trying it to my other workstation running PHP 5.3. Did I missed something?? Please Advise.

Thanks!


问:
Understanding unquoteDecl in Agda
I'm trying to understand Agda's built in reflection mechanisms, so I decided to write a simple function that takes a string for an identifier,
a quoted type, and a quoted term, and simply defines a term of the given type with the given string identifier. Thus, I wrote the following:

```<code>testDefineName' : String → TC Type → TC Term → TC ⊤
testDefineName' s t a =
   bindTC (freshName s)
     (λ n → bindTC t
     (λ t' → bindTC a
     (λ a' → (bindTC (declareDef (arg (arg-info visible relevant) n) t')
     (λ _ → defineFun n ((clause [] a') ∷ []))))))

unquoteDecl = (testDefineName' "test" (quoteTC ℕ) (quoteTC zero))
</code>```

This type-checks, but, when I try to use "test" elsewhere I get a Not in scope: test error.

The documentation for unquoteDecl is kind of opaque. Appaently declarations should be of the form

```<code>unquoteDecl x_1 x_2 ... x_n = m
</code>```

where the x_i are Names, and m has type TC \top, so maybe what I was trying to do isn't actually possible, but I still don't understand how this mechanism works: if m has to be of type TC ⊤, and thus cannot be a function of the names x_1 x_2 ... x_n, I don't see how it is possible to bring any new names into scope using unquoteDecl at all!

So, to sum up:

Is it possible to define a function like mine using Agda's reflection mechanism so that I can bring new names into scope using a String argument? What I want is something like:

```<code><boilerplate code for unquoting> testDefineName' "test" (quoteTC ℕ) (quoteTC zero)
test' : ℕ
test' = test
</code>```

to compile (i.e. I can actually use the new name, "test")

and if not, by what mechanism can m make use of the names x_1 ... x_n? Can m actually have a type like List Name → TC ⊤, contrary to the documentation?

答:
Based on the way Ulf uses unquoteDecl, I have the impression that you need to list on the LHS the names which are going to extend the scope.

The problem with your setup is that you don't know the Name as you generate a fresh one from a String and have no way of getting hold of it AFAIK. I have the impression that freshName is only supposed to be used to generate internal names from inside a tactic.

If you make testDefineName' take a Name rather than a String then everything works out:

```<code>testDefineName' : Name → TC Type → TC Term → TC ⊤
testDefineName' n t a = bindTC t
               $ λ t' → bindTC a
               $ λ a' → bindTC (declareDef (arg (arg-info visible relevant) n) t')
               $ λ _  → defineFun n ((clause [] a') ∷ [])

unquoteDecl test = testDefineName' test (quoteTC ℕ) (quoteTC zero)
</code>```

Title: Understanding unquoteDecl in Agda

Body:
I'm trying to understand Agda's built in reflection mechanisms, so I decided to write a simple function that takes a string for an identifier,
a quoted type, and a quoted term, and simply defines a term of the given type with the given string identifier. Thus, I wrote the following:

testDefineName' : String → TC Type → TC Term → TC ⊤
testDefineName' s t a =
   bindTC (freshName s)
     (λ n → bindTC t
     (λ t' → bindTC a
     (λ a' → (bindTC (declareDef (arg (arg-info visible relevant) n) t')
     (λ _ → defineFun n ((clause [] a') ∷ []))))))

unquoteDecl = (testDefineName' "test" (quoteTC ℕ) (quoteTC zero))

This type-checks, but, when I try to use "test" elsewhere I get a Not in scope: test error.

The documentation for unquoteDecl is kind of opaque. Appaently declarations should be of the form

unquoteDecl x_1 x_2 ... x_n = m

where the x_i are Names, and m has type TC \top, so maybe what I was trying to do isn't actually possible, but I still don't understand how this mechanism works: if m has to be of type TC ⊤, and thus cannot be a function of the names x_1 x_2 ... x_n, I don't see how it is possible to bring any new names into scope using unquoteDecl at all!

So, to sum up:

Is it possible to define a function like mine using Agda's reflection mechanism so that I can bring new names into scope using a String argument? What I want is something like:

<boilerplate code for unquoting> testDefineName' "test" (quoteTC ℕ) (quoteTC zero)
test' : ℕ
test' = test

to compile (i.e. I can actually use the new name, "test")

and if not, by what mechanism can m make use of the names x_1 ... x_n? Can m actually have a type like List Name → TC ⊤, contrary to the documentation?

Body:
Based on the way Ulf uses unquoteDecl, I have the impression that you need to list on the LHS the names which are going to extend the scope.

The problem with your setup is that you don't know the Name as you generate a fresh one from a String and have no way of getting hold of it AFAIK. I have the impression that freshName is only supposed to be used to generate internal names from inside a tactic.

If you make testDefineName' take a Name rather than a String then everything works out:

testDefineName' : Name → TC Type → TC Term → TC ⊤
testDefineName' n t a = bindTC t
               $ λ t' → bindTC a
               $ λ a' → bindTC (declareDef (arg (arg-info visible relevant) n) t')
               $ λ _  → defineFun n ((clause [] a') ∷ [])

unquoteDecl test = testDefineName' test (quoteTC ℕ) (quoteTC zero)


问:
Android studio Gradle build speed up
Since the last update (Build from june 25) any changes in the Android studio Gradle is painfully slow. And it also seems to autotrack changes when you edit the file and recompile on keyup.

Each change takes several minutes on my i5.

Any idea how I can speed up my Gradle changes?

答:
Try to avoid using a Mac/PC that has only 8 GB of RAM when doing Android development. As soon as you launch even 1 emulator (Genymotion or otherwise), your build times become extremely slow in Android Studio with gradle builds. This happens even if you make a simple one-line change to 1 source file.

Closing the emulator and using a real device helps a lot, but of course this is very limiting and less flexible. Reducing the RAM usage setting of the emulator can help, but the best way is to ensure your laptop has at least 12-16 GB of RAM.

Update (June 2017): There are now several good medium.com articles that explain how to speed up Android Studio gradle builds in detail, and it even works on 8 GB machines:

How to decrease your Gradle build time by 65%:
https://medium.com/@kevalpatel2106/how-to-decrease-your-gradle-build-time-by-65-310b572b0c43

Make your Gradle builds fast again!: https://medium.com/@wasyl/make-your-gradle-builds-fast-again-ea323ce6a435

The summarised consensus is:

Create a gradle.properties file (either global at ~/.gradle/gradle.properties or local to project), and add the following lines:

```<code>org.gradle.daemon=true
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configureondemand=true
</code>```

Title: Android studio Gradle build speed up

Body:
Try to avoid using a Mac/PC that has only 8 GB of RAM when doing Android development. As soon as you launch even 1 emulator (Genymotion or otherwise), your build times become extremely slow in Android Studio with gradle builds. This happens even if you make a simple one-line change to 1 source file.

Closing the emulator and using a real device helps a lot, but of course this is very limiting and less flexible. Reducing the RAM usage setting of the emulator can help, but the best way is to ensure your laptop has at least 12-16 GB of RAM.

Update (June 2017): There are now several good medium.com articles that explain how to speed up Android Studio gradle builds in detail, and it even works on 8 GB machines:

How to decrease your Gradle build time by 65%:
https://medium.com/@kevalpatel2106/how-to-decrease-your-gradle-build-time-by-65-310b572b0c43

Make your Gradle builds fast again!: https://medium.com/@wasyl/make-your-gradle-builds-fast-again-ea323ce6a435

The summarised consensus is:

Create a gradle.properties file (either global at ~/.gradle/gradle.properties or local to project), and add the following lines:

org.gradle.daemon=true
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configureondemand=true


问:
How to use Date function in hibernate query language
Hi trying to fetch the records from database based on the date wise,how can i achieve this
in database i have column like start_date with datatype datetime and in model class i have data member like

```<code>public class Records {
private Date startDate
// getters and setters
}
</code>```

am trying to write query like below

```<code>String hql = "from Records where  DATE(startDate)=? ";
Query query = session.createQuery(hql);
query.setParameter(0, getStartDate());
</code>```

答:
Use this:</p>

```<code>  String hql = "from Records where  DATE(startDate)= DATE(:date) ";
        Query query = session.createQuery(hql);
        query.setParameter("date", new Date());
        System.out.println(query.list().size());
</code>```

Body:
Hi trying to fetch the records from database based on the date wise,how can i achieve this
in database i have column like start_date with datatype datetime and in model class i have data member like

public class Records {
private Date startDate
// getters and setters
}

am trying to write query like below

String hql = "from Records where  DATE(startDate)=? ";
Query query = session.createQuery(hql);
query.setParameter(0, getStartDate());

Body:
Use this:

  String hql = "from Records where  DATE(startDate)= DATE(:date) ";
        Query query = session.createQuery(hql);
        query.setParameter("date", new Date());
        System.out.println(query.list().size());


问:
Type 'Tamir.SharpSsh.jsch.JSchException' is not marked as serializable
I have a .NET 3.5 MVC2 web app that runs fine from Visual Studio 2008 but when I publish to a remote site, I get an error in a certain function.

Any idea what I should be looking for here?

```<code>Event Type: Error
Event Source:   ASP.NET 2.0.50727.0
Event Category: None
Event ID:   1334
Date:       24/08/2010
Time:       13:58:55
User:       N/A
Computer:   MSVSC01-G124NW
Description:
An unhandled exception occurred and the process was terminated.

Application ID: DefaultDomain

Process ID: 17048

Exception: System.Runtime.Serialization.SerializationException

Message: Type 'Tamir.SharpSsh.jsch.JSchException' in Assembly 'Tamir.SharpSSH, Version=1.1.1.13, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

StackTrace:    at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
   at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
   at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
   at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.SerializeObject(Object obj, MemoryStream stm)
   at System.AppDomain.Serialize(Object o)
   at System.AppDomain.MarshalObject(Object o)

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
</code>```

答:
Are you using that class in a member of another class that is serializable? if so, you may need to add these attributes to that variable

```<code>[XmlIgnore][field: NonSerialized]   private JSch                _jsch
</code>```

I hope that helps

Body:
I have a .NET 3.5 MVC2 web app that runs fine from Visual Studio 2008 but when I publish to a remote site, I get an error in a certain function.

Any idea what I should be looking for here?

Event Type: Error
Event Source:   ASP.NET 2.0.50727.0
Event Category: None
Event ID:   1334
Date:       24/08/2010
Time:       13:58:55
User:       N/A
Computer:   MSVSC01-G124NW
Description:
An unhandled exception occurred and the process was terminated.

Application ID: DefaultDomain

Process ID: 17048

Exception: System.Runtime.Serialization.SerializationException

Message: Type 'Tamir.SharpSsh.jsch.JSchException' in Assembly 'Tamir.SharpSSH, Version=1.1.1.13, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

StackTrace:    at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
   at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
   at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
   at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.SerializeObject(Object obj, MemoryStream stm)
   at System.AppDomain.Serialize(Object o)
   at System.AppDomain.MarshalObject(Object o)

For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

Body:
Are you using that class in a member of another class that is serializable? if so, you may need to add these attributes to that variable

[XmlIgnore][field: NonSerialized]   private JSch                _jsch

I hope that helps


问:
PyCharm: IDE does not seem to recognise Python 3 even with 3.x interpreter set
I am using the latest version of Pycharm(pycharm-2017.1) and have used Pycharm for a couple of years without issue. However, I have never written Python 3 scripts with it before, and have issues now. I am getting red underlined syntax errors which appear to clearly indicate that Pycharm doesn't understand that I'm using Python 3.

In 'Edit configurations', I have set Python 3.x to be the default interpreter... I'm not sure what I'm doing wrong.

Note: I have the correct python3 shebang lines in my scripts, and running them both straight from a terminal, or even by pressing 'run' in Pycharm works no problem.. this latter fact just adds to the mystery.

I also tried adding (with the '+' in 'Edit configurations', specific profiles for each of the scripts concerned, with Python3.x as the interpreters, to no avail)

Thanks for reading

答:
The Edit configurations settings refers to the running options only.

To use python3 at project level you need to change the interpreter in File > Settings > Project: project-name > Project Interpreter

This allow to have correct syntax-checking, import-checking and others