问:
Find Normal and Tangential components of motion in box2d/matter.js
I'm trying to recreate a fluid-drag model as seen in
paragraph 2.2.1 of this paper. A working version can be seen in this this youtube movie (where I found the paper).

In the paper they state that they calculate the normal and tangential forces of the velocity of an edge of a soft body. I've tried to understand how to get from edge velocity to these two force components. However I can only find resources about calculating the components based on a function (e.g. this), and I'm struggling to translate that to my physics environment. What would be a way to achieve this fluid drag model?

Here is a fiddle to show my environment:
https://jsfiddle.net/Swendude/1nnckp5p/

```<code>// module aliases
var Engine = Matter.Engine,
    Render = Matter.Render,
    World = Matter.World,
    Bodies = Matter.Bodies,
    Body = Matter.Body,
    Vector = Matter.Vector,
    Composite = Matter.Composite,
    Composites = Matter.Composites,
    Constraint = Matter.Constraint,
    Events = Matter.Events;

// create an engine
var engine = Engine.create();

// create a canvas
var canvas = document.getElementById("maincanvas");

var render = Render.create({
    element: document.body,
    canvas: canvas,
    engine: engine,
    options: {
        background: "#fff",
        height: 400,
        width: 400,
        wireframes: false,
    }
});

engine.world.gravity = {x:0, y:0};

// Create a soft body composite, see
// http://brm.io/matter-js/docs/classes/Composites.html#method_softBody
var softbox = Composites.softBody(100,100,2,2,40,40,true,1);

World.add(engine.world, softbox);

// This functions makes some constraints move.

function pulse(composite) {
  var allcons = Composite.allConstraints(composite);
  allcons[0].length += 5;
  allcons[4].length += 5;

  // Set a timeout to make the constraints short again
  setTimeout(function (cons) { cons.length -= 5;}, 1000, allcons[0]);
  setTimeout(function (cons) { cons.length -= 5;}, 1000, allcons[4]);
}

setInterval(pulse, 2000, softbox);

function applyForcesOnEdge() {
    var allcons = Composite.allConstraints(engine.world);

    allcons.forEach( function(cons, index) {
        // Edge speed defined as the average of both connected body's speed.
        var constraintspeed = Vector.div(Vector.add(cons.bodyA.velocity, cons.bodyA.velocity),2);
        if (constraintspeed.x != 0 && constraintspeed.y != 0) {
          console.log(constraintspeed); // How to get the tangential and normal components from this?
        }
    });
}

Events.on(engine, 'beforeUpdate', function () {
  applyForcesOnEdge();
})

Engine.run(engine);

Render.run(render);
</code>```

Most of it is matter.js boilerplate, the interesting parts are the functions: pulse() and applyForcesOnEdge()

I'm using matter.js, but I can imagine the same question might apply to a box2d environment.

答:
Just take the difference between the positions of the objects on either side of the constraint. It's better explained in code:</p>

```<code>allcons.forEach( function(cons, index) {
    // Edge speed defined as the average of both connected body's speed.
    var constraintspeed = Vector.div(
        Vector.add(
            cons.bodyA.velocity,
            cons.bodyB.velocity),
        2);
    var constraintpos = Vector.div(
        Vector.add(
            cons.bodyA.position,
            cons.bodyB.position),
        2);
    var tangent = Vector.normalise(
        cons.bodyB.position -
        cons.bodyA.position);
    var normal = Vector.perp(tangent);
    var v_T = Vector.dot(constraintspeed, tangent);
    var v_N = Vector.dot(constraintspeed, normal);
    var F_T = - lambda_T * Math.sign(v_T) * v_T * v_T;
    var F_N = - lambda_N * Math.sign(v_N) * v_N * v_N;
    var F = Vector.add(
        Vector.mult(tangent, F_T),
        Vector.mult(normal, F_N));
    Body.applyForce(cons.bodyA, constraintpos, F);
    Body.applyForce(cons.bodyB, constraintpos, F);
});
</code>```

Body:
I'm trying to recreate a fluid-drag model as seen in
paragraph 2.2.1 of this paper. A working version can be seen in this this youtube movie (where I found the paper).

In the paper they state that they calculate the normal and tangential forces of the velocity of an edge of a soft body. I've tried to understand how to get from edge velocity to these two force components. However I can only find resources about calculating the components based on a function (e.g. this), and I'm struggling to translate that to my physics environment. What would be a way to achieve this fluid drag model?

Here is a fiddle to show my environment:
https://jsfiddle.net/Swendude/1nnckp5p/

// module aliases
var Engine = Matter.Engine,
    Render = Matter.Render,
    World = Matter.World,
    Bodies = Matter.Bodies,
    Body = Matter.Body,
    Vector = Matter.Vector,
    Composite = Matter.Composite,
    Composites = Matter.Composites,
    Constraint = Matter.Constraint,
    Events = Matter.Events;

// create an engine
var engine = Engine.create();

// create a canvas
var canvas = document.getElementById("maincanvas");

var render = Render.create({
    element: document.body,
    canvas: canvas,
    engine: engine,
    options: {
        background: "#fff",
        height: 400,
        width: 400,
        wireframes: false,
    }
});

engine.world.gravity = {x:0, y:0};

// Create a soft body composite, see
// http://brm.io/matter-js/docs/classes/Composites.html#method_softBody
var softbox = Composites.softBody(100,100,2,2,40,40,true,1);

World.add(engine.world, softbox);

// This functions makes some constraints move.

function pulse(composite) {
  var allcons = Composite.allConstraints(composite);
  allcons[0].length += 5;
  allcons[4].length += 5;

  // Set a timeout to make the constraints short again
  setTimeout(function (cons) { cons.length -= 5;}, 1000, allcons[0]);
  setTimeout(function (cons) { cons.length -= 5;}, 1000, allcons[4]);
}

setInterval(pulse, 2000, softbox);

function applyForcesOnEdge() {
    var allcons = Composite.allConstraints(engine.world);

    allcons.forEach( function(cons, index) {
        // Edge speed defined as the average of both connected body's speed.
        var constraintspeed = Vector.div(Vector.add(cons.bodyA.velocity, cons.bodyA.velocity),2);
        if (constraintspeed.x != 0 && constraintspeed.y != 0) {
          console.log(constraintspeed); // How to get the tangential and normal components from this?
        }
    });
}

Events.on(engine, 'beforeUpdate', function () {
  applyForcesOnEdge();
})

Engine.run(engine);

Render.run(render);

Most of it is matter.js boilerplate, the interesting parts are the functions: pulse() and applyForcesOnEdge()

I'm using matter.js, but I can imagine the same question might apply to a box2d environment.

Body:
Just take the difference between the positions of the objects on either side of the constraint. It's better explained in code:

allcons.forEach( function(cons, index) {
    // Edge speed defined as the average of both connected body's speed.
    var constraintspeed = Vector.div(
        Vector.add(
            cons.bodyA.velocity,
            cons.bodyB.velocity),
        2);
    var constraintpos = Vector.div(
        Vector.add(
            cons.bodyA.position,
            cons.bodyB.position),
        2);
    var tangent = Vector.normalise(
        cons.bodyB.position -
        cons.bodyA.position);
    var normal = Vector.perp(tangent);
    var v_T = Vector.dot(constraintspeed, tangent);
    var v_N = Vector.dot(constraintspeed, normal);
    var F_T = - lambda_T * Math.sign(v_T) * v_T * v_T;
    var F_N = - lambda_N * Math.sign(v_N) * v_N * v_N;
    var F = Vector.add(
        Vector.mult(tangent, F_T),
        Vector.mult(normal, F_N));
    Body.applyForce(cons.bodyA, constraintpos, F);
    Body.applyForce(cons.bodyB, constraintpos, F);
});


来源: stackexchange

问:
Save multiple times in Cakephp
I want to save 10 times in Cakephp using Save function with for loop but it doesn't seem to work. It only saves one data.

How can we make it so it saves multiple data at one call?

Below is my code...

```<code>        for($i=0;$i<10;$i++){
        $unique_id = $this->_unique($userData['User']['id']); // Unique id with userid as initial prefix
        $this->data['Invite'] = array('invited_user' => $userData['User']['id'], 'unique_id' => $unique_id);
        $this->User->Invite->save($this->data['Invite']);
            }
</code>```

答:
The answer is in the following book, page 94: Source: Bari, Ahsanul. CakePHP Application Development (p. 94). Packt Publishing. Kindle Edition. This is the what you can find in the book, and the answer to this question:

```<code>$this->Book->create();
$this->Book->save($this->data);
</code>```

Note: It is important to call the model's create() method just ahead
  of calling the model's save() method if the intention is to create a
  new record.

In other words, you need to use create() before save() every time you use save().

ContentLicense: CC BY-SA 3.0

Title: Save multiple times in Cakephp

Body:
I want to save 10 times in Cakephp using Save function with for loop but it doesn't seem to work. It only saves one data.

How can we make it so it saves multiple data at one call?

Below is my code...

        for($i=0;$i<10;$i++){
        $unique_id = $this->_unique($userData['User']['id']); // Unique id with userid as initial prefix
        $this->data['Invite'] = array('invited_user' => $userData['User']['id'], 'unique_id' => $unique_id);
        $this->User->Invite->save($this->data['Invite']);
            }

Body:
The answer is in the following book, page 94: Source: Bari, Ahsanul. CakePHP Application Development (p. 94). Packt Publishing. Kindle Edition. This is the what you can find in the book, and the answer to this question:

$this->Book->create();
$this->Book->save($this->data);

Note: It is important to call the model's create() method just ahead
  of calling the model's save() method if the intention is to create a
  new record.

In other words, you need to use create() before save() every time you use save().


问:
LINQ to SQL using GROUP BY and COUNT(DISTINCT)
I have to perform the following SQL query:

```<code>select answer_nbr, count(distinct user_nbr)
from tpoll_answer
where poll_nbr = 16
group by answer_nbr
</code>```

The LINQ to SQL query

```<code>from a in tpoll_answer
where a.poll_nbr = 16 select a.answer_nbr, a.user_nbr distinct
</code>```

maps to the following SQL query:

```<code>select distinct answer_nbr, distinct user_nbr
from tpoll_answer
where poll_nbr = 16
</code>```

So far, so good. However the problem raises when trying to GROUP the results, as I'm not being able to find a LINQ to SQL query that maps to the first query I wrote here (thank you LINQPad for making this process a lot easier). The following is the only one that I've found that gives me the desired result:

```<code>from answer in tpoll_answer where answer.poll_nbr = 16 _
group by a_id = answer.answer_nbr into votes = count(answer.user_nbr)
</code>```

Which in turns produces the follwing ugly and non-optimized at all SQL query:

```<code>SELECT [t1].[answer_nbr] AS [a_id], (
    SELECT COUNT(*)
    FROM (
        SELECT CONVERT(Bit,[t2].[user_nbr]) AS [value], [t2].[answer_nbr], [t2].[poll_nbr]
        FROM [TPOLL_ANSWER] AS [t2]
        ) AS [t3]
    WHERE ([t3].[value] = 1) AND ([t1].[answer_nbr] = [t3].[answer_nbr]) AND ([t3].[poll_nbr] = @p0)
    ) AS [votes]
FROM (
    SELECT [t0].[answer_nbr]
    FROM [TPOLL_ANSWER] AS [t0]
    WHERE [t0].[poll_nbr] = @p0
    GROUP BY [t0].[answer_nbr]
    ) AS [t1]
-- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [16]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1
</code>```

Any help will be more than appreciated.

答:
Linq to sql has no support for Count(Distinct ...). You therefore have to map a .NET method in code onto a Sql server function (thus Count(distinct.. )) and use that. </p>

<p>btw, it doesn't help if you post pseudo code copied from a toolkit in a format that's neither VB.NET nor C#. </p>

OwnerDisplayName: Leandro López

ContentLicense: CC BY-SA 2.5

Body:
I have to perform the following SQL query:

select answer_nbr, count(distinct user_nbr)
from tpoll_answer
where poll_nbr = 16
group by answer_nbr

The LINQ to SQL query

from a in tpoll_answer
where a.poll_nbr = 16 select a.answer_nbr, a.user_nbr distinct

maps to the following SQL query:

select distinct answer_nbr, distinct user_nbr
from tpoll_answer
where poll_nbr = 16

So far, so good. However the problem raises when trying to GROUP the results, as I'm not being able to find a LINQ to SQL query that maps to the first query I wrote here (thank you LINQPad for making this process a lot easier). The following is the only one that I've found that gives me the desired result:

from answer in tpoll_answer where answer.poll_nbr = 16 _
group by a_id = answer.answer_nbr into votes = count(answer.user_nbr)

Which in turns produces the follwing ugly and non-optimized at all SQL query:

SELECT [t1].[answer_nbr] AS [a_id], (
    SELECT COUNT(*)
    FROM (
        SELECT CONVERT(Bit,[t2].[user_nbr]) AS [value], [t2].[answer_nbr], [t2].[poll_nbr]
        FROM [TPOLL_ANSWER] AS [t2]
        ) AS [t3]
    WHERE ([t3].[value] = 1) AND ([t1].[answer_nbr] = [t3].[answer_nbr]) AND ([t3].[poll_nbr] = @p0)
    ) AS [votes]
FROM (
    SELECT [t0].[answer_nbr]
    FROM [TPOLL_ANSWER] AS [t0]
    WHERE [t0].[poll_nbr] = @p0
    GROUP BY [t0].[answer_nbr]
    ) AS [t1]
-- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [16]
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1

Any help will be more than appreciated.

Body:
Linq to sql has no support for Count(Distinct ...). You therefore have to map a .NET method in code onto a Sql server function (thus Count(distinct.. )) and use that.

btw, it doesn't help if you post pseudo code copied from a toolkit in a format that's neither VB.NET nor C#.

OwnerDisplayName: Frans Bouma


问:
How to parse an  that is deep within a div using Element Parser?
I'm currently using an parser called Element Parser and I'm trying to parse an img tag that is the 4th img tag down under the div id "Group-E". I can retrieve the 2nd img but not anything after the 2nd img. The img that I'm wanting to parse is:

```<code><img src="http://example.com/I_need_this_image_here.jpg" />.
</code>```

How can this be done? So far I've used the following code to get the 1st img tag:

```<code>Element* needIMG = [document selectElement: @"div.edgeTop div#Group-E img"];
</code>```

HTML Code trying to parse

```<code><div class="edgeTop">
<div id="Group-E">
    <img src="http://example.com/image.jpg" id="image" />        <img src="http://example.com/image2.png" border="5" />

    <h4>Group - Section E</h4>

    <div class="efs" style="width:28px;">Group:</div>E<br />
    <div class="efs" style="width:28px;">Link:</div><a href="Group/E">Group E</a><br />
    <div class="efs" style="width:28px;">Date:</div><strong>Febuary 15, 2001</strong> by <strong><a href="http://example.com/date">Date</a></strong><br />
    <br />

    <img src="http://example.com/image3.gif" class="image" style="padding: 0 4px 7px 0;" />Group;.  <b>Group E</b><br /><br />Group E Other:
    <img src="http://example.com/I_need_this_image_here.jpg" />  Other:<br /><a href="http://www.example.com/other" target="_blank" class="url">Group Site</a>
    <div class="efs">
        <div style="padding:18px 0 1px 8px;">Link Pics:</div>
        <img src="http://example.com/linkpic.gif" class="imagelink"/> </div>
</div>
<div class="efsl"></div>
</code>```

Thanks for the help.

答:
Could you not add a class to the image you want to parse such as...</p>

```<code><img class="imgtoparse" src="http://example.com/I_need_this_image_here.jpg" />
</code>```

Title: How to parse an <img> that is deep within a div using Element Parser?

Body:
I'm currently using an parser called Element Parser and I'm trying to parse an img tag that is the 4th img tag down under the div id "Group-E". I can retrieve the 2nd img but not anything after the 2nd img. The img that I'm wanting to parse is:

.

How can this be done? So far I've used the following code to get the 1st img tag:

Element* needIMG = [document selectElement: @"div.edgeTop div#Group-E img"];

HTML Code trying to parse

Group - Section E

Group:
E

Link:
Group E

Date:
Febuary 15, 2001 by Date

    Group;.  Group E

Group E Other:
      Other:
Group Site

Link Pics:

Thanks for the help.

Body:
Could you not add a class to the image you want to parse such as...

<img class="imgtoparse" src="http://example.com/I_need_this_image_here.jpg" />


问:
Why is RuntimeException legal here?
This is my code:

```<code> import java.io.*;
 import java.sql.*;
 import java.io.*;
 import java.sql.*;
 class Vehicle{
    public void park()throws IOException {//compiletime checked
    }
 }
 class Car extends Vehicle{
     public void park()throws RuntimeException{//compile time unchecked
         //
     }
 }
</code>```

Why compile time unchecked exceptions is legal here?

答:
It is legal because:

restricting derived methods is OK (if you are prepared to catch an io exception you have no problem if no such exception is thrown).

putting up RuntimeException is always possible because it is not a checked exception - so the compiler does not care anyway.

So your subclass simply overrides a method dropping a checked exception from the signature.

This is all rooted in the Liskov substitution principle: the idea is that you must be able to perform any call that is possible on a super class method also on the derived class.

When you think about this requirement it becomes clear quickly that it is perfectly fine when a derived method returns or throws "less"  than the super class method.

Title: Why is RuntimeException legal here?

Body:
This is my code:

 import java.io.*;
 import java.sql.*;
 import java.io.*;
 import java.sql.*;
 class Vehicle{
    public void park()throws IOException {//compiletime checked
    }
 }
 class Car extends Vehicle{
     public void park()throws RuntimeException{//compile time unchecked
         //
     }
 }

Why compile time unchecked exceptions is legal here?


问:
Nginx wordpress rewrites for pattern to a particular page
I'm trying to set it up so that certain URLs will rewrite (not change URL in address bar) to a particular page with identifying parameters.

I would like

```<code>site.com/reviews/froot_loops_review.php AND
site.com/reviews/froot_loops_review
</code>```

to actually show

```<code>site.com/review?title=froot_loops
</code>```

Additionally, I would like to be able to append any other parameters so:

```<code>site.com/reviews/froot_loops_review.php?var=1
</code>```

would show what's at:

```<code>site.com/review?title=froot_loops&var=1
</code>```

I'm having a hard time with this because it's my first time editing nginx conf files this is as far as I've got but it doesn't work (I think because it doesn't make the first match):

```<code>  location /reviews/ {
    rewrite ^/reviews/(.*)_review.php(.*) /review?title=$1 break;
    return  403;
  }
</code>```

What am I doing wrong here? What should my next step be? What is a good resource for learning Nginx rewrites?

答:
I am not sure if this is strictly an answer. But there are multiple issues with your current solution.

This is a WordPress site, so there is already a location ~ \.php$ block which is handling any URI that ends with .php. The URI /reviews/froot_loops_review.php will never make it to the location /reviews/ block in your question.

You can use the ^~ modifier on the location directive to force nginx to ignore any matching regular expression location block. See this document for details.

The rewritten URI cannot be processed within the same location block, so break is the wrong suffix to use. You will have more success using last. See this document for details.

But the main problem is WordPress itself. WordPress normally uses the REQUEST_URI (which is the URI as originally presented) to identify the requested page. Which is why we can rewrite everything to /index.php and still get the right page.

Trying to make WordPress use your rewritten URI without an external redirect (which you say you do not want to do) is tricky. You may be better off looking for a WordPress plugin to achieve it - or try to make the pretty permalinks work the way you want.

Body:
I'm trying to set it up so that certain URLs will rewrite (not change URL in address bar) to a particular page with identifying parameters.

I would like

site.com/reviews/froot_loops_review.php AND
site.com/reviews/froot_loops_review

to actually show

site.com/review?title=froot_loops

Additionally, I would like to be able to append any other parameters so:

site.com/reviews/froot_loops_review.php?var=1

would show what's at:

site.com/review?title=froot_loops&var=1

I'm having a hard time with this because it's my first time editing nginx conf files this is as far as I've got but it doesn't work (I think because it doesn't make the first match):

  location /reviews/ {
    rewrite ^/reviews/(.*)_review.php(.*) /review?title=$1 break;
    return  403;
  }

What am I doing wrong here? What should my next step be? What is a good resource for learning Nginx rewrites?


问:
Android App still remains connected to Google Sign in even after Uninstalling and reinstalling it
I have this strange problem in my App. My app has a GSigninActivity which is shown after Splash screen to facilitate Single Sign On with Google and Firebase. The problem is that on First Install and Launch, the app directly goes MainActivity without asking for Sign In.I have to the log Out from there and then Sign In. How is it that some Sign in data is present. Please Help.

GSigninActivity Code

```<code>    package com.example.joelmathew.firebidtest;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.example.joelmathew.firebidtest.models.User;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.GoogleApiClient;

/**
 * Created by Joel Mathew on 01-Jul-17.
 */

public class GSignInActivity extends BaseActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {

    private static final String TAG = "GoogleActivity";
    private static final int RC_SIGN_IN = 9001;

    // [START declare_auth]
    private FirebaseAuth mAuth;
    private DatabaseReference mDatabase;
    // [END declare_auth]

    protected GoogleApiClient mGoogleApiClient;
    private String signout="false";
    public String personName;
   // private TextView mStatusTextView;
   // private TextView mDetailTextView;

    @Override
    @TargetApi(21)
    protected void onCreate(Bundle savedInstanceState) {
        FirebaseApp.initializeApp(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gsignin_activity);

        getSupportActionBar().hide();
        Window w = getWindow();
        w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        w.setStatusBarColor(ContextCompat.getColor(this, R.color.statusSplash));

        // Views
      //  mStatusTextView = (TextView) findViewById(R.id.status);
      //  mDetailTextView = (TextView) findViewById(R.id.detail);

        // Button listeners
        findViewById(R.id.sign_in_button).setOnClickListener(this);
        //findViewById(R.id.sign_out_button).setOnClickListener(this);
      //  findViewById(R.id.disconnect_button).setOnClickListener(this);

        // [START config_signin]
        // Configure Google Sign In
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        // [END config_signin]

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        // [START initialize_auth]
        mDatabase = FirebaseDatabase.getInstance().getReference();
        mAuth = FirebaseAuth.getInstance();
        // [END initialize_auth]

         /*Bundle b = getIntent().getExtras();
        if(b!=null) {
            signout = b.getString("Signout");
            if (signout.equals("true")) {
                Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                        new ResultCallback<Status>() {
                            @Override
                            public void onResult(@NonNull Status status) {
                                updateUI(null);
                            }
                        });
            }
        }*/

    }

    // [START on_start_check_user]
    @Override
    public void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        updateUI(currentUser);
    }
    // [END on_start_check_user]

    // [START onactivityresult]
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = result.getSignInAccount();
                personName = account.getDisplayName();
                Log.v("LOG_VAL","GSigninActivity,onActivityResult: Person Name : "+ personName);
                PostKeyHolder.setGlobalPersonName(personName);
                Log.v("LOG_VAL","GSigninActivity,onActivityResult: Returned from Person Name : "+ PostKeyHolder.getGlobalPersonName());

                //String Number = account.
                firebaseAuthWithGoogle(account);
            } else {
                // Google Sign In failed, update UI appropriately
                // [START_EXCLUDE]
                updateUI(null);
                // [END_EXCLUDE]
            }
        }
    }
    // [END onactivityresult]

    // [START auth_with_google]
    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
        // [START_EXCLUDE silent]
        showProgressDialog();
        // [END_EXCLUDE]
       final GoogleSignInAccount temp = acct;

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            personName = temp.getDisplayName();
                            Log.v("LOG_VAL","GSigninActivity,firebaseAuthWithGoogle: Person Name : "+ personName);
                            PostKeyHolder.setGlobalPersonName(personName);
                            Log.v("LOG_VAL","GSigninActivity,firebaseAuthWithGoogle: REturned from setting Person Name : "+ PostKeyHolder.getGlobalPersonName());
                            updateUI(user);
                            onAuthSuccess(user);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(GSignInActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            updateUI(null);
                        }

                        // [START_EXCLUDE]
                        hideProgressDialog();
                        // [END_EXCLUDE]
                    }
                });
    }
    // [END auth_with_google]

    // [START signin]
    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
    // [END signin]

    private void signOut() {
        // Firebase sign out
        mAuth.signOut();

        // Google sign out
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(@NonNull Status status) {
                        updateUI(null);
                    }
                });
    }

    private void onAuthSuccess(FirebaseUser user) {
        String username = usernameFromEmail(user.getEmail());
        personName = user.getDisplayName();

        Log.v("LOG_VAL","GSigninActivity,onAuthSuccess: Person Name : "+ personName);
        PostKeyHolder.setGlobalPersonName(personName);
        Log.v("LOG_VAL","GSigninActivity,onAuthSuccess: Returned from Person Name : "+ PostKeyHolder.getGlobalPersonName());

        // Write new user
        writeNewUser(user.getUid(), username, user.getEmail(),personName);

       // PostKeyHolder.setGlobalPersonName(personName); //Setting Global Person handler

        // Go to MainActivity

        //Intent apiClient = new Intent(GSignInActivity.this,MainActivity.class);
        //apiClient.putExtra("ApiClient",mGoogleApiClient);
        updateUI(user);
        //startActivity(new Intent(GSignInActivity.this, MainActivity.class));
        finish();
    }

    private String usernameFromEmail(String email) {
        if (email.contains("@")) {
            return email.split("@")[0];
        } else {
            return email;
        }
    }

    // [START basic_write]
    private void writeNewUser(String userId, String username, String email, String personName) {
        User user = new User(username, email, personName);
        Log.v("LOG_VAL","GSigninActivity,writeNewUser: Person Name : "+ personName);
        PostKeyHolder.setGlobalPersonName(personName);
        Log.v("LOG_VAL","GSigninActivity,onActivityResult: Returned Person Name : "+ PostKeyHolder.getGlobalPersonName());

        mDatabase.child("GoogleSignIn").child(userId).setValue(user);
        mDatabase.child("users").child("GoogleSignIn").child(userId).setValue(user);
    }
    // [END basic_write]

    private void revokeAccess() {
        // Firebase sign out
        mAuth.signOut();

        // Google revoke access
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(@NonNull Status status) {
                        //updateUI(null);
                    }
                });
    }

    private void updateUI(FirebaseUser user) {
        hideProgressDialog();
        if (user != null) {

            personName = user.getDisplayName();
            Log.v("LOG_VAL","GSigninActivity,updateUI: Person Name : "+ personName);

            PostKeyHolder.setGlobalPersonName(personName);
            Log.v("LOG_VAL","GSigninActivity,updateUI: Returned Person Name : "+ PostKeyHolder.getGlobalPersonName());

            //  mStatusTextView.setText(getString(R.string.google_status_fmt, user.getEmail()));
           // mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid()));

           findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
           startActivity(new Intent(GSignInActivity.this, MainActivity.class));
            finish();
          //  findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
        } else {

          //  mStatusTextView.setText(R.string.signed_out);
//            mDetailTextView.setText(null);

            findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
         //   findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        // An unresolvable error has occurred and Google APIs (including Sign-In) will not
        // be available.
        Log.d(TAG, "onConnectionFailed:" + connectionResult);
        Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.sign_in_button) {
            signIn();
        } //else if (i == R.id.sign_out_button)
       /* // {
            signOut();
        } //else if (i == R.id.disconnect_button)
        /* {
            //evokeAccess();
        }*/
    }

}
</code>```

Manifest.XML

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.joelmathew.firebidtest">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" />
        <activity android:name=".NewPostActivity"
            android:windowSoftInputMode="adjustPan"/>

        <activity android:name=".BuyNow"/>
        <activity android:name=".BidMainScreen3"
            android:windowSoftInputMode="adjustPan"/>

        <!--activity android:name=".SignInActivity"-->
            <!--intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter-->
        <!--/activity-->

        <activity android:name=".SplashScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <activity android:name=".GSignInActivity"></activity>
        <activity android:name=".PostDetailActivity"></activity>
        <activity android:name=".TopBidsActivity"></activity>
        <activity android:name=".OrdersActivity"></activity>
    </application>

</manifest>
</code>```

答:
You need to Clear App data When required. Like on Logout or something Like that. THis will resolve all your Issue</p>

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                            ((ActivityManager) context.getSystemService(ACTIVITY_SERVICE))
                                    .clearApplicationUserData(); // note: it has a return value!
                        } else {
                            clearApplicationData();
                        }

 public void clearApplicationData() {
        File cache = getCacheDir();
        File appDir = new File(cache.getParent());
        if (appDir.exists()) {
            String[] children = appDir.list();
            for (String s : children) {
                if (!s.equals("lib")) {
                    deleteDir(new File(appDir, s));
                    Log.i("TAG", "File /data/data/APP_PACKAGE/" + s + " DELETED");
                }
            }
        }
    }
</code>```

Body:
I have this strange problem in my App. My app has a GSigninActivity which is shown after Splash screen to facilitate Single Sign On with Google and Firebase. The problem is that on First Install and Launch, the app directly goes MainActivity without asking for Sign In.I have to the log Out from there and then Sign In. How is it that some Sign in data is present. Please Help.

GSigninActivity Code

    package com.example.joelmathew.firebidtest;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.example.joelmathew.firebidtest.models.User;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.GoogleApiClient;

/**
 * Created by Joel Mathew on 01-Jul-17.
 */

public class GSignInActivity extends BaseActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {

    private static final String TAG = "GoogleActivity";
    private static final int RC_SIGN_IN = 9001;

    // [START declare_auth]
    private FirebaseAuth mAuth;
    private DatabaseReference mDatabase;
    // [END declare_auth]

    protected GoogleApiClient mGoogleApiClient;
    private String signout="false";
    public String personName;
   // private TextView mStatusTextView;
   // private TextView mDetailTextView;

    @Override
    @TargetApi(21)
    protected void onCreate(Bundle savedInstanceState) {
        FirebaseApp.initializeApp(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gsignin_activity);

        getSupportActionBar().hide();
        Window w = getWindow();
        w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        w.setStatusBarColor(ContextCompat.getColor(this, R.color.statusSplash));

        // Views
      //  mStatusTextView = (TextView) findViewById(R.id.status);
      //  mDetailTextView = (TextView) findViewById(R.id.detail);

        // Button listeners
        findViewById(R.id.sign_in_button).setOnClickListener(this);
        //findViewById(R.id.sign_out_button).setOnClickListener(this);
      //  findViewById(R.id.disconnect_button).setOnClickListener(this);

        // [START config_signin]
        // Configure Google Sign In
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        // [END config_signin]

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        // [START initialize_auth]
        mDatabase = FirebaseDatabase.getInstance().getReference();
        mAuth = FirebaseAuth.getInstance();
        // [END initialize_auth]

         /*Bundle b = getIntent().getExtras();
        if(b!=null) {
            signout = b.getString("Signout");
            if (signout.equals("true")) {
                Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                        new ResultCallback<Status>() {
                            @Override
                            public void onResult(@NonNull Status status) {
                                updateUI(null);
                            }
                        });
            }
        }*/

    }

    // [START on_start_check_user]
    @Override
    public void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        updateUI(currentUser);
    }
    // [END on_start_check_user]

    // [START onactivityresult]
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = result.getSignInAccount();
                personName = account.getDisplayName();
                Log.v("LOG_VAL","GSigninActivity,onActivityResult: Person Name : "+ personName);
                PostKeyHolder.setGlobalPersonName(personName);
                Log.v("LOG_VAL","GSigninActivity,onActivityResult: Returned from Person Name : "+ PostKeyHolder.getGlobalPersonName());

                //String Number = account.
                firebaseAuthWithGoogle(account);
            } else {
                // Google Sign In failed, update UI appropriately
                // [START_EXCLUDE]
                updateUI(null);
                // [END_EXCLUDE]
            }
        }
    }
    // [END onactivityresult]

    // [START auth_with_google]
    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
        // [START_EXCLUDE silent]
        showProgressDialog();
        // [END_EXCLUDE]
       final GoogleSignInAccount temp = acct;

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            personName = temp.getDisplayName();
                            Log.v("LOG_VAL","GSigninActivity,firebaseAuthWithGoogle: Person Name : "+ personName);
                            PostKeyHolder.setGlobalPersonName(personName);
                            Log.v("LOG_VAL","GSigninActivity,firebaseAuthWithGoogle: REturned from setting Person Name : "+ PostKeyHolder.getGlobalPersonName());
                            updateUI(user);
                            onAuthSuccess(user);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(GSignInActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            updateUI(null);
                        }

                        // [START_EXCLUDE]
                        hideProgressDialog();
                        // [END_EXCLUDE]
                    }
                });
    }
    // [END auth_with_google]

    // [START signin]
    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
    // [END signin]

    private void signOut() {
        // Firebase sign out
        mAuth.signOut();

        // Google sign out
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(@NonNull Status status) {
                        updateUI(null);
                    }
                });
    }

    private void onAuthSuccess(FirebaseUser user) {
        String username = usernameFromEmail(user.getEmail());
        personName = user.getDisplayName();

        Log.v("LOG_VAL","GSigninActivity,onAuthSuccess: Person Name : "+ personName);
        PostKeyHolder.setGlobalPersonName(personName);
        Log.v("LOG_VAL","GSigninActivity,onAuthSuccess: Returned from Person Name : "+ PostKeyHolder.getGlobalPersonName());

        // Write new user
        writeNewUser(user.getUid(), username, user.getEmail(),personName);

       // PostKeyHolder.setGlobalPersonName(personName); //Setting Global Person handler

        // Go to MainActivity

        //Intent apiClient = new Intent(GSignInActivity.this,MainActivity.class);
        //apiClient.putExtra("ApiClient",mGoogleApiClient);
        updateUI(user);
        //startActivity(new Intent(GSignInActivity.this, MainActivity.class));
        finish();
    }

    private String usernameFromEmail(String email) {
        if (email.contains("@")) {
            return email.split("@")[0];
        } else {
            return email;
        }
    }

    // [START basic_write]
    private void writeNewUser(String userId, String username, String email, String personName) {
        User user = new User(username, email, personName);
        Log.v("LOG_VAL","GSigninActivity,writeNewUser: Person Name : "+ personName);
        PostKeyHolder.setGlobalPersonName(personName);
        Log.v("LOG_VAL","GSigninActivity,onActivityResult: Returned Person Name : "+ PostKeyHolder.getGlobalPersonName());

        mDatabase.child("GoogleSignIn").child(userId).setValue(user);
        mDatabase.child("users").child("GoogleSignIn").child(userId).setValue(user);
    }
    // [END basic_write]

    private void revokeAccess() {
        // Firebase sign out
        mAuth.signOut();

        // Google revoke access
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(@NonNull Status status) {
                        //updateUI(null);
                    }
                });
    }

    private void updateUI(FirebaseUser user) {
        hideProgressDialog();
        if (user != null) {

            personName = user.getDisplayName();
            Log.v("LOG_VAL","GSigninActivity,updateUI: Person Name : "+ personName);

            PostKeyHolder.setGlobalPersonName(personName);
            Log.v("LOG_VAL","GSigninActivity,updateUI: Returned Person Name : "+ PostKeyHolder.getGlobalPersonName());

            //  mStatusTextView.setText(getString(R.string.google_status_fmt, user.getEmail()));
           // mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid()));

           findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
           startActivity(new Intent(GSignInActivity.this, MainActivity.class));
            finish();
          //  findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
        } else {

          //  mStatusTextView.setText(R.string.signed_out);
//            mDetailTextView.setText(null);

            findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
         //   findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        // An unresolvable error has occurred and Google APIs (including Sign-In) will not
        // be available.
        Log.d(TAG, "onConnectionFailed:" + connectionResult);
        Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.sign_in_button) {
            signIn();
        } //else if (i == R.id.sign_out_button)
       /* // {
            signOut();
        } //else if (i == R.id.disconnect_button)
        /* {
            //evokeAccess();
        }*/
    }

}

Manifest.XML

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.joelmathew.firebidtest">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" />
        <activity android:name=".NewPostActivity"
            android:windowSoftInputMode="adjustPan"/>

        <activity android:name=".BuyNow"/>
        <activity android:name=".BidMainScreen3"
            android:windowSoftInputMode="adjustPan"/>

        <activity android:name=".SplashScreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <activity android:name=".GSignInActivity"></activity>
        <activity android:name=".PostDetailActivity"></activity>
        <activity android:name=".TopBidsActivity"></activity>
        <activity android:name=".OrdersActivity"></activity>
    </application>

</manifest>

Body:
You need to Clear App data When required. Like on Logout or something Like that. THis will resolve all your Issue

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                            ((ActivityManager) context.getSystemService(ACTIVITY_SERVICE))
                                    .clearApplicationUserData(); // note: it has a return value!
                        } else {
                            clearApplicationData();
                        }

 public void clearApplicationData() {
        File cache = getCacheDir();
        File appDir = new File(cache.getParent());
        if (appDir.exists()) {
            String[] children = appDir.list();
            for (String s : children) {
                if (!s.equals("lib")) {
                    deleteDir(new File(appDir, s));
                    Log.i("TAG", "File /data/data/APP_PACKAGE/" + s + " DELETED");
                }
            }
        }
    }


问:
Why does "1" in awk print the current line?
In this answer,

```<code>awk '$2=="no"{$3="N/A"}1' file
</code>```

was accepted. Note the 1 at the end of the AWK script. In the comments, the author of the answer said

[1 is] a cryptic way to display the current line.

I'm puzzled. How does that work?

答:
AWK works on method of condition and then action. So if any condition is TRUE any action which we mention to happen will be executed then.

In case of 1 it means we are making that condition TRUE and in this case we are not mentioning any action to happen, so awk's by default action print will happen.

So this is why we write 1 in shortcut actually speaking.

Body:
In this answer,

awk '$2=="no"{$3="N/A"}1' file

was accepted. Note the 1 at the end of the AWK script. In the comments, the author of the answer said

[1 is] a cryptic way to display the current line.

I'm puzzled. How does that work?


问:
How to retrieve one table row and list of rows that are connected to the first row in Linq .NET
I have specific problem. I'm not too experienced with SQL so this may be a silly question. I have the following class

```<code>class StructuredResult
{
    public Pay Pay{ get; set; }
    public Processing Processing{ get; set; }
    public Member Member { get; set; }

    public StructuredResult()
    {
    }
}
</code>```

And this is the code I'm getting this with

```<code>var allPaying = (from pay in Entities.Pays
                join prc in Entities.Processingss on pay.IDCalculation equals cal.IDCalculation
                join mbr in Entities.Members on pay.IDMember equals mbr.IDMember

                where pay.IDMember == IDMember
                orderby prc.DateFrom descending
                select new StructuredResult()
                {
                    Pay = pay,
                    Processing = prc,
                    Member = mbr
                }).ToList();
</code>```

The code is working fine I changed things for posting here, maybe some name changes are not ok. What I need to get is this:

```<code>class StructuredResult
{
    public Pay Pay{ get; set; }
    public Processing Processing{ get; set; }
    public Member Member { get; set; }
    public List<PayDetail> PayDetails { get; set; }

    public StructuredResult()
    {
    }
}
</code>```

Does anyone know if this is even possible? Pay detail is connected with Pay.ID = PayDetail.ID
Thanks in advance

答:
This may help you:</p>

```<code>var allPaying = (from pay in Entities.Pays
                 join prc in Entities.Processingss on pay.IDCalculation equals cal.IDCalculation
                 join mbr in Entities.Members on pay.IDMember equals mbr.IDMember

                 where pay.IDMember == IDMember
                 orderby prc.DateFrom descending
                 select new StructuredResult()
                 {
                     Pay = pay,
                     Processing = prc,
                     Member = mbr,
                     PayDetails = (from pd in Entities.PayDetails
                                   where pd.ID == pay.IDMember
                                   select pd).ToList())
                 }).ToList();
</code>```

Body:
I have specific problem. I'm not too experienced with SQL so this may be a silly question. I have the following class

class StructuredResult
{
    public Pay Pay{ get; set; }
    public Processing Processing{ get; set; }
    public Member Member { get; set; }

    public StructuredResult()
    {
    }
}

And this is the code I'm getting this with

var allPaying = (from pay in Entities.Pays
                join prc in Entities.Processingss on pay.IDCalculation equals cal.IDCalculation
                join mbr in Entities.Members on pay.IDMember equals mbr.IDMember

                where pay.IDMember == IDMember
                orderby prc.DateFrom descending
                select new StructuredResult()
                {
                    Pay = pay,
                    Processing = prc,
                    Member = mbr
                }).ToList();

The code is working fine I changed things for posting here, maybe some name changes are not ok. What I need to get is this:

class StructuredResult
{
    public Pay Pay{ get; set; }
    public Processing Processing{ get; set; }
    public Member Member { get; set; }
    public List<PayDetail> PayDetails { get; set; }

    public StructuredResult()
    {
    }
}

Does anyone know if this is even possible? Pay detail is connected with Pay.ID = PayDetail.ID
Thanks in advance

Body:
This may help you:

var allPaying = (from pay in Entities.Pays
                 join prc in Entities.Processingss on pay.IDCalculation equals cal.IDCalculation
                 join mbr in Entities.Members on pay.IDMember equals mbr.IDMember

                 where pay.IDMember == IDMember
                 orderby prc.DateFrom descending
                 select new StructuredResult()
                 {
                     Pay = pay,
                     Processing = prc,
                     Member = mbr,
                     PayDetails = (from pd in Entities.PayDetails
                                   where pd.ID == pay.IDMember
                                   select pd).ToList())
                 }).ToList();


问:
How to get the position of a field using pdfbox?
I got stuck in one area. I need to identify the positions of the PDAcroForm fields in one pdf. I need to do some processing with the x and y value of the fields.

Any idea how to do this? Is the information present in the COS object?

答:
The accepted answer does not work anymore. I have tried the approach and received NullPointerException for some elements. In PDFBOX 2.x, you can obtain the rectangle without querying the COS object tree directly.

The information about the field position is stored in PDAnnotationWidget. There can be more widgets associated with the field. To obtain the first one (without checking whether these is one).

```<code>PDRectangle rectangle = field.getWidgets().get(0).getRectangle();
</code>```

To obtain all rectangles (in cases there can be more):

```<code>List<PDRectangle> rectangles = field.getWidgets().stream().map(PDAnnotation::getRectangle).collect(Collectors.toList());
</code>```

Body:
The accepted answer does not work anymore. I have tried the approach and received NullPointerException for some elements. In PDFBOX 2.x, you can obtain the rectangle without querying the COS object tree directly.

The information about the field position is stored in PDAnnotationWidget. There can be more widgets associated with the field. To obtain the first one (without checking whether these is one).

PDRectangle rectangle = field.getWidgets().get(0).getRectangle();

To obtain all rectangles (in cases there can be more):

List<PDRectangle> rectangles = field.getWidgets().stream().map(PDAnnotation::getRectangle).collect(Collectors.toList());


问:
Transferring an array pointer into CUDA memory via separate class
I have a class named "Coordinate" which consist of an int array pointer and a bool variable. I want to send this pointer into CUDA, modify it and then use it back in CPU memory.

Here is Coordinate.h :

```<code>#ifndef __COORDINATE_H
#define __COORDINATE_H

#include <stdlib.h>
#include <cuda.h>

using namespace std;

class Coordinate {

public:
    int *array_pointer;
    bool flag;

    Coordinate() { flag = false; }

    Coordinate(int array_length) {
        flag = false;
        array_pointer = new int[array_length];
        for (int i = 0; i < array_length; i++) {
            array_pointer[i] = -1;
        }
    }
};

#endif
</code>```

I have made 2 global functions in cudamain.cu Check1 and Check2, both will take a Coordinate as argument. Check1 function will change only boolean flag which Check2 will change boolean flag and also modify the array.

Here is cudamain.cu :

```<code>#include <iostream>
#include <cuda.h>
#include "Coordinate.h"

using namespace std;

__global__ void check1(Coordinate *ptr) {
    c->flag = true;
}

__global__ void check2(Coordinate *c) {
    c->flag = true;
    for (int i = 0; i < 10; i++) {
        c->array_pointer[i] = i;
    }
}

int main() {
    Coordinate *d_a, *d_b, a, b;
    a = Coordinate(10); b = Coordinate(10);

    size_t size = sizeof(Coordinate);

    cudaMalloc((void**)&d_a, size); cudaMalloc((void**)&d_b, size);
    cudaMemcpy(d_a, &a, size, cudaMemcpyHostToDevice); cudaMemcpy(d_b, &b, size, cudaMemcpyHostToDevice);

    check1 << <1, 1 >> > (d_a);
    cudaMemcpy(&a, d_a, size, cudaMemcpyDeviceToHost);
    cout <<"d_a result-> " <<a.flag <<" " <<a.array_pointer[9] << endl;

    check2 << <1, 1 >> > (d_b);
    cudaMemcpy(&b, d_b, size, cudaMemcpyDeviceToHost);
    cout << "d_b result-> " << b.flag << " " << b.array_pointer[9] << endl;
    return 0;
}
</code>```

I made 2 separate coordinate objects a and b, a will go with check1 and b will go with check2. Both a and b are initialized in same way.

The result I get is

```<code>d_a result-> 1 -1
d_b result-> 0 -1
</code>```

Expected result:

```<code>d_a result-> 1 -1
d_b result-> 1 9
</code>```

Different Coordinate objects may have different array length so I can't initialize the array pointer in the coordinate class.

答:
You cannot access host memory from a CUDA kernel by dereferncing, unless that piece of memory was specially-allocated to allow this, e.g. using cudaMallocManaged(). So your program cannot work. Read this Parallel4All post on accessing the same memory both from the host and the device. Another alternative is the one @RobertCrovella linked to, involving allocating device-side memory.

But, frankly, I doubt any of these two options are what you should go for in this case, since a class named Coordinate does not seem to be something which would need a variable-size array of integers. Are you sure something like

```<code>template <unsigned NumDimensions>
class Coordinate<N> {
    std::array<int, NumDimensions> a;
    // etc. etc.
}
</code>```

won't do?

(Note that the std::array class itself cannot really be used in device code, like most of the standard library. But you can easily clone std::array and then use your cuda::array class on both the host and the device side.)

Even if dynamic allocation of memory is required for some reason, it is not a good idea to have a class which, it seems, would be used many times, allocate its own memory. Consider using some pre-allocated buffer and have your Coordinates just advance an offset into it (although this would require synchronization for thread safety, or making the buffer thread-local).

Body:
I have a class named "Coordinate" which consist of an int array pointer and a bool variable. I want to send this pointer into CUDA, modify it and then use it back in CPU memory.

Here is Coordinate.h :

#ifndef __COORDINATE_H
#define __COORDINATE_H

#include <stdlib.h>
#include <cuda.h>

using namespace std;

class Coordinate {

public:
    int *array_pointer;
    bool flag;

    Coordinate() { flag = false; }

    Coordinate(int array_length) {
        flag = false;
        array_pointer = new int[array_length];
        for (int i = 0; i < array_length; i++) {
            array_pointer[i] = -1;
        }
    }
};

#endif

I have made 2 global functions in cudamain.cu Check1 and Check2, both will take a Coordinate as argument. Check1 function will change only boolean flag which Check2 will change boolean flag and also modify the array.

Here is cudamain.cu :

#include <iostream>
#include <cuda.h>
#include "Coordinate.h"

using namespace std;

__global__ void check1(Coordinate *ptr) {
    c->flag = true;
}

__global__ void check2(Coordinate *c) {
    c->flag = true;
    for (int i = 0; i < 10; i++) {
        c->array_pointer[i] = i;
    }
}

int main() {
    Coordinate *d_a, *d_b, a, b;
    a = Coordinate(10); b = Coordinate(10);

    size_t size = sizeof(Coordinate);

    cudaMalloc((void**)&d_a, size); cudaMalloc((void**)&d_b, size);
    cudaMemcpy(d_a, &a, size, cudaMemcpyHostToDevice); cudaMemcpy(d_b, &b, size, cudaMemcpyHostToDevice);

    check1 << <1, 1 >> > (d_a);
    cudaMemcpy(&a, d_a, size, cudaMemcpyDeviceToHost);
    cout <<"d_a result-> " <<a.flag <<" " <<a.array_pointer[9] << endl;

    check2 << <1, 1 >> > (d_b);
    cudaMemcpy(&b, d_b, size, cudaMemcpyDeviceToHost);
    cout << "d_b result-> " << b.flag << " " << b.array_pointer[9] << endl;
    return 0;
}

I made 2 separate coordinate objects a and b, a will go with check1 and b will go with check2. Both a and b are initialized in same way.

The result I get is

d_a result-> 1 -1
d_b result-> 0 -1

Expected result:

d_a result-> 1 -1
d_b result-> 1 9

Different Coordinate objects may have different array length so I can't initialize the array pointer in the coordinate class.

Body:
You cannot access host memory from a CUDA kernel by dereferncing, unless that piece of memory was specially-allocated to allow this, e.g. using cudaMallocManaged(). So your program cannot work. Read this Parallel4All post on accessing the same memory both from the host and the device. Another alternative is the one @RobertCrovella linked to, involving allocating device-side memory.

But, frankly, I doubt any of these two options are what you should go for in this case, since a class named Coordinate does not seem to be something which would need a variable-size array of integers. Are you sure something like

template <unsigned NumDimensions>
class Coordinate<N> {
    std::array<int, NumDimensions> a;
    // etc. etc.
}

won't do?

(Note that the std::array class itself cannot really be used in device code, like most of the standard library. But you can easily clone std::array and then use your cuda::array class on both the host and the device side.)

Even if dynamic allocation of memory is required for some reason, it is not a good idea to have a class which, it seems, would be used many times, allocate its own memory. Consider using some pre-allocated buffer and have your Coordinates just advance an offset into it (although this would require synchronization for thread safety, or making the buffer thread-local).


问:
Can a digital currency be involved in Hyper Ledger Fabric
Just like Bitcoin or Ethereum, can there be a digital currency involved in Hyper Ledger Fabric ?</p>

答: Since the chaincode can read and write any byte arrays and can execute any arbitrary logic implemented in Go (in the future in other languages), you can implement digital currency if you want, and make the applications that consume the chaincode - use it. But the infrastructure itself would not enforce it</p>


问:
Android Room - emit single item update
I'm using Android Room to load data.
my query is this:

```<code>@Query("SELECT * FROM TrackedItem where isArchived = 0 ORDER BY creationDate DESC")
Flowable<List<TrackedItem>> getAll();
</code>```

When calling getAll() I get all the items at the first time.
Then, I'm updating all the items using a network request.
What happens is that if I have 100 items, the getAll() will emit 100 times the entire list, which will update the RecyclerView 100 times.

Best practice for getting a single item that was changed and calling notifyItemChanged?

Thanks.

答:
Answering my own question, if someone gets the same issue.
Instead of saving each item after an update, I save all of them once
calling @Insert with (TrackedItem... items).
which will only emits one update.</p>

Title: Android Room - emit single item update

Body:
I'm using Android Room to load data.
my query is this:

@Query("SELECT * FROM TrackedItem where isArchived = 0 ORDER BY creationDate DESC")
Flowable<List<TrackedItem>> getAll();

When calling getAll() I get all the items at the first time.
Then, I'm updating all the items using a network request.
What happens is that if I have 100 items, the getAll() will emit 100 times the entire list, which will update the RecyclerView 100 times.

Best practice for getting a single item that was changed and calling notifyItemChanged?

Thanks.


问:
best way for substring pandas data frame

Q1

I want to extract the Title of each person from the Name attribute of concat data frame. what is the best way of doing this?

```<code>concat['Title'][concat['Title'] == 'Mlle'] = 'Miss'
concat['Title'][concat['Title'] == 'Ms'] = 'Miss'
concat['Title'][concat['Title'] == 'Mme'] = 'Mrs'
concat['Title'][concat['Title'] == 'Dona' or 'Lady'or 'Countess'or'Capt' or 'Col'or'Don'or 'Dr'or 'Major'or 'Rev'or 'Sir'or 'Jonkheer' ] = 'Rare'
</code>```

Q2

when i run the above code i get this error:

```<code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

why?

Refrences

the full problem with datasets : Titanic

答:
Use str.split, and then extract the second item from the resultant list.

```<code>In [37]: df['Name'].head()
Out[37]:
0                              Braund, Mr. Owen Harris
1    Cumings, Mrs. John Bradley (Florence Briggs Th...
2                               Heikkinen, Miss. Laina
3         Futrelle, Mrs. Jacques Heath (Lily May Peel)
4                             Allen, Mr. William Henry
Name: Name, dtype: object
</code>```

An observation here is that names follow this format: Last Name, Salutation Given Name. We'll split on spaces and extract the Salutation from the split lists using df.apply:

```<code>In [38]: df['Title'] = df['Name'].str.split(' ').apply(lambda x: x[1])

In [39]: df['Title'].head()
Out[39]:
0      Mr.
1     Mrs.
2    Miss.
3     Mrs.
4      Mr.
Name: Title, dtype: object
</code>```

Body:
Q1

I want to extract the Title of each person from the Name attribute of concat data frame. what is the best way of doing this?

concat['Title'][concat['Title'] == 'Mlle'] = 'Miss'
concat['Title'][concat['Title'] == 'Ms'] = 'Miss'
concat['Title'][concat['Title'] == 'Mme'] = 'Mrs'
concat['Title'][concat['Title'] == 'Dona' or 'Lady'or 'Countess'or'Capt' or 'Col'or'Don'or 'Dr'or 'Major'or 'Rev'or 'Sir'or 'Jonkheer' ] = 'Rare'

Q2

when i run the above code i get this error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

why?

Refrences

the full problem with datasets : Titanic

Body:
Use str.split, and then extract the second item from the resultant list.

In [37]: df['Name'].head()
Out[37]:
0                              Braund, Mr. Owen Harris
1    Cumings, Mrs. John Bradley (Florence Briggs Th...
2                               Heikkinen, Miss. Laina
3         Futrelle, Mrs. Jacques Heath (Lily May Peel)
4                             Allen, Mr. William Henry
Name: Name, dtype: object

An observation here is that names follow this format: Last Name, Salutation Given Name. We'll split on spaces and extract the Salutation from the split lists using df.apply:

In [38]: df['Title'] = df['Name'].str.split(' ').apply(lambda x: x[1])

In [39]: df['Title'].head()
Out[39]:
0      Mr.
1     Mrs.
2    Miss.
3     Mrs.
4      Mr.
Name: Title, dtype: object


问:
Why we lose text value (defined in customize option) on moving Wordpress website from local to live
I have migrated around 8-10 websites from Local machine to live server. But every time after following all the required process mention in the below article, I tend to loose customize data (Text In widgets especially).

http://www.wpbeginner.com/wp-tutorials/how-to-move-wordpress-from-local-server-to-live-site/

Could anyone help me understand where WordPress stores widget data? or is it just my theme problem?

Thanks in Advance!

答:
This article has a good explanation why this happens.

Basically, WordPress stores widget data in a serialized array and when the new URL contains a number of characters that differ than the previous URL,it will invalidate the serialized array.


问:
Find corresponding solid to a given shell
The problem I am working on is CAE / FEM related and can be summarized as followed:

I'm reading a file that contains nodes (points in 3D, defined by a node number and X / Y / Z coordinates), triangular shell elements (defined by an element number and 3 nodes) and tetrahedral solid elements (defined by an element number and 4 nodes). The data is stored in 3 dictioniaries:

```<code>nodes  = {'Node_ID' : [X, Y, Z]};
shells = {'Shell_ID': ['Node_ID_1', 'Node_ID_2', 'Node_ID_3']};
solids = {'Solid_ID': ['Node_ID_1', 'Node_ID_2', 'Node_ID_3', 'Node_ID_4']};
</code>```

Every shell has a corresponding solid with same nodes:

```<code>for shell_k, shell_v in shells.iteritems():
  for solid_k, solid_v in solids.iteritems():
    if((shell_v[0] in solid_v) and (shell_v[1] in solid_v) and (shell_v[2] in solid_v)):
      # This is true for one combination of shell and solid
</code>```

Python needs for this approximately 100 seconds (number of shells is about 12,000, number of solids is about 40,000, therefore the if-query has to be performed 480,000,000 times. Is it possible to reduce the complexity from O(mn) to something faster with small effort?

Edit: Some examples of nodes, shells, solids:

Nodes:

```<code> # In file:

 2504888, 190.05780, 101.70673, 320.68655
 2504889, 187.96325, 101.82080, 322.86340
 2504890, 192.14670, 103.65783, 320.42405
 2504891, 188.52980, 105.40890, 320.94880
 2504892, 190.05215, 103.77190, 322.60090

 # As dict:

 nodes[2504888] = [190.05780, 101.70673, 320.68655];
 nodes[2504889] = [187.96325, 101.82080, 322.86340];
 nodes[2504890] = [192.14670, 103.65783, 320.42405];
 nodes[2504891] = [188.52980, 105.40890, 320.94880];
 nodes[2504892] = [190.05215, 103.77190, 322.60090];
</code>```

Shells:

```<code> # In file:

 227, 3866603, 3862785, 3862784
 228, 3866603, 3862784, 3866559
 229, 3866585, 3866603, 3866559
 230, 3866635, 3866603, 3866585
 231, 3866208, 3866635, 3866585

 # As dict:

 shells[227] = [3866603, 3862785, 3862784];
 shells[228] = [3866603, 3862784, 3866559];
 shells[229] = [3866585, 3866603, 3866559];
 shells[230] = [3866635, 3866603, 3866585];
 shells[231] = [3866208, 3866635, 3866585];
</code>```

Solids:

```<code> # In file:

 3622889, 4130281, 4130283, 4126885, 4126884
 3622890, 4130281, 4126885, 4129084, 4126884
 3622891, 4130281, 4129084, 4129080, 4126884
 3622892, 4129080, 4129084, 4129083, 4126884
 3622895, 4129080, 4129083, 4129079, 4126884

 # As dict:

 solids[3622889] = [4130281, 4130283, 4126885, 4126884];
 solids[3622890] = [4130281, 4126885, 4129084, 4126884];
 solids[3622891] = [4130281, 4129084, 4129080, 4126884];
 solids[3622892] = [4129080, 4129084, 4129083, 4126884];
 solids[3622895] = [4129080, 4129083, 4129079, 4126884];
</code>```

An example for a shell / solid pair would be:

```<code># Nodes:
3854247, 19.82965, 133.65520, 203.52418
3867556, 18.85539, 132.60338, 203.77993
3866448, 18.66001, 134.38551, 204.89977
3867528, 18.34272, 134.38552, 203.95146

# Shell:
415734, 3867556, 3866448, 3867528

# Solid:
3478898, 3867528, 3866448, 3867556, 3854247
</code>```

答:
Question: Is it possible to reduce the complexity from O(mn) to something faster with small effort?

Note: Your Python Version is outdated, couldn't use your notation.

To simplify the if condition using set()

```<code>for shell_k in shells:
    for solid_k in solids:
        if set(shells[shell_k]).issubset(set(solids[solid_k])):
            # This is true for one combination of shell and solid
</code>```

Or, Precondition Values are of Type set() to eliminate Type Casting:

```<code>for shell_k in shells_set:
    for solid_k in solids_set:
        if shells_set[shell_k].issubset(solids_set[solid_k]):
            # This is true for one combination of shell and solid
</code>```

Solution using NumPy

NumPy v1.13 Manual: numpy.in1d

```<code>numpy.in1d(ar1, ar2, assume_unique=False, invert=False)[source]
</code>```

Test whether each element of a 1-D array is also present in a second array.
  Returns a boolean array the same length as ar1 that is True where an element of ar1 is in ar2 and False otherwise.

Preconditioned Data as numpy.ndarray's

```<code>shells(4, 3): [[3866448 3867528 3867556]
                [3862784 3862785 3866603]
                [4126884 4126885 4130283]
                [3862784 3866559 3866603]]

solids(4, 4): [[3854247 3866448 3867528 3867556]
               [4126884 4126885 4130281 4130283]
               [4126884 4126885 4129084 4130281]
               [4126883 4126885 4129084 4130282]]

solids_id:[3478898 3478899 3478900 3478901]
</code>```

```<code>import numpy as np
# Get a (4,4) numpy Mask from Shells in Solids
solids_in1d = np.in1d(solids, n_shells).reshape(solids.shape)

# Get Array of y Index of Masked Solides with 3 Nodes
solids_idx = np.where(np.sum(solids_in1d, axis=1) == 3)[0]

# Print Solids - Show ID and only the 3 Solid Nodes
for y in solids_idx:
    print('Solids ID:{} Nodes:{}'.format(solids_id[y], solids[y][solids_in1d[y]]))
</code>```

Output:

```<code>Solids ID:3478898 Nodes:[3866448 3867528 3867556]
Solids ID:3478899 Nodes:[4126884 4126885 4130283]
</code>```

Alternatives

Using numpy.isin instead of numpy.in1d

Couldn't try it as it's new in version 1.13.0.

I could imagin that pandas could handle this.

Tested with Python:3.4.2 - numpy:1.12.1

Body:
The problem I am working on is CAE / FEM related and can be summarized as followed:

I'm reading a file that contains nodes (points in 3D, defined by a node number and X / Y / Z coordinates), triangular shell elements (defined by an element number and 3 nodes) and tetrahedral solid elements (defined by an element number and 4 nodes). The data is stored in 3 dictioniaries:

nodes  = {'Node_ID' : [X, Y, Z]};
shells = {'Shell_ID': ['Node_ID_1', 'Node_ID_2', 'Node_ID_3']};
solids = {'Solid_ID': ['Node_ID_1', 'Node_ID_2', 'Node_ID_3', 'Node_ID_4']};

Every shell has a corresponding solid with same nodes:

for shell_k, shell_v in shells.iteritems():
  for solid_k, solid_v in solids.iteritems():
    if((shell_v[0] in solid_v) and (shell_v[1] in solid_v) and (shell_v[2] in solid_v)):
      # This is true for one combination of shell and solid

Python needs for this approximately 100 seconds (number of shells is about 12,000, number of solids is about 40,000, therefore the if-query has to be performed 480,000,000 times. Is it possible to reduce the complexity from O(mn) to something faster with small effort?

Edit: Some examples of nodes, shells, solids:

Nodes:

 # In file:

 2504888, 190.05780, 101.70673, 320.68655
 2504889, 187.96325, 101.82080, 322.86340
 2504890, 192.14670, 103.65783, 320.42405
 2504891, 188.52980, 105.40890, 320.94880
 2504892, 190.05215, 103.77190, 322.60090

 # As dict:

 nodes[2504888] = [190.05780, 101.70673, 320.68655];
 nodes[2504889] = [187.96325, 101.82080, 322.86340];
 nodes[2504890] = [192.14670, 103.65783, 320.42405];
 nodes[2504891] = [188.52980, 105.40890, 320.94880];
 nodes[2504892] = [190.05215, 103.77190, 322.60090];

Shells:

 # In file:

 227, 3866603, 3862785, 3862784
 228, 3866603, 3862784, 3866559
 229, 3866585, 3866603, 3866559
 230, 3866635, 3866603, 3866585
 231, 3866208, 3866635, 3866585

 # As dict:

 shells[227] = [3866603, 3862785, 3862784];
 shells[228] = [3866603, 3862784, 3866559];
 shells[229] = [3866585, 3866603, 3866559];
 shells[230] = [3866635, 3866603, 3866585];
 shells[231] = [3866208, 3866635, 3866585];

Solids:

 # In file:

 3622889, 4130281, 4130283, 4126885, 4126884
 3622890, 4130281, 4126885, 4129084, 4126884
 3622891, 4130281, 4129084, 4129080, 4126884
 3622892, 4129080, 4129084, 4129083, 4126884
 3622895, 4129080, 4129083, 4129079, 4126884

 # As dict:

 solids[3622889] = [4130281, 4130283, 4126885, 4126884];
 solids[3622890] = [4130281, 4126885, 4129084, 4126884];
 solids[3622891] = [4130281, 4129084, 4129080, 4126884];
 solids[3622892] = [4129080, 4129084, 4129083, 4126884];
 solids[3622895] = [4129080, 4129083, 4129079, 4126884];

An example for a shell / solid pair would be:

# Nodes:
3854247, 19.82965, 133.65520, 203.52418
3867556, 18.85539, 132.60338, 203.77993
3866448, 18.66001, 134.38551, 204.89977
3867528, 18.34272, 134.38552, 203.95146

# Shell:
415734, 3867556, 3866448, 3867528

# Solid:
3478898, 3867528, 3866448, 3867556, 3854247

Body:
Question: Is it possible to reduce the complexity from O(mn) to something faster with small effort?

Note: Your Python Version is outdated, couldn't use your notation.

To simplify the if condition using set()

for shell_k in shells:
    for solid_k in solids:
        if set(shells[shell_k]).issubset(set(solids[solid_k])):
            # This is true for one combination of shell and solid

Or, Precondition Values are of Type set() to eliminate Type Casting:

for shell_k in shells_set:
    for solid_k in solids_set:
        if shells_set[shell_k].issubset(solids_set[solid_k]):
            # This is true for one combination of shell and solid

Solution using NumPy

NumPy v1.13 Manual: numpy.in1d

numpy.in1d(ar1, ar2, assume_unique=False, invert=False)[source]

Test whether each element of a 1-D array is also present in a second array.
  Returns a boolean array the same length as ar1 that is True where an element of ar1 is in ar2 and False otherwise.

Preconditioned Data as numpy.ndarray's

shells(4, 3): [[3866448 3867528 3867556]
                [3862784 3862785 3866603]
                [4126884 4126885 4130283]
                [3862784 3866559 3866603]]

solids(4, 4): [[3854247 3866448 3867528 3867556]
               [4126884 4126885 4130281 4130283]
               [4126884 4126885 4129084 4130281]
               [4126883 4126885 4129084 4130282]]

solids_id:[3478898 3478899 3478900 3478901]

import numpy as np
# Get a (4,4) numpy Mask from Shells in Solids
solids_in1d = np.in1d(solids, n_shells).reshape(solids.shape)

# Get Array of y Index of Masked Solides with 3 Nodes
solids_idx = np.where(np.sum(solids_in1d, axis=1) == 3)[0]

# Print Solids - Show ID and only the 3 Solid Nodes
for y in solids_idx:
    print('Solids ID:{} Nodes:{}'.format(solids_id[y], solids[y][solids_in1d[y]]))

Output:

Solids ID:3478898 Nodes:[3866448 3867528 3867556]
Solids ID:3478899 Nodes:[4126884 4126885 4130283]

Alternatives

Using numpy.isin instead of numpy.in1d

Couldn't try it as it's new in version 1.13.0.

I could imagin that pandas could handle this.

Tested with Python:3.4.2 - numpy:1.12.1


问:
Firebase Database Rules: Predefine own variables
just wanna ask if this is possible as it would the readability and maintainability of my rules.

```<code>path fireId = root.child('chat').child('$chatSpecific').child('FireId')

"chatInfo": {
      "$uid":{
          ".read": "fireId.val()===auth.uid"
</code>```

Thanks

答:
yes it is possible, </p>

```<code>"chatInfo": {
      "$uid":{
          ".read": "data.child('FireId').val()===auth.uid"
       }
    }
</code>```

Body:
just wanna ask if this is possible as it would the readability and maintainability of my rules.

path fireId = root.child('chat').child('$chatSpecific').child('FireId')

"chatInfo": {
      "$uid":{
          ".read": "fireId.val()===auth.uid"

Thanks

Body:
yes it is possible,

"chatInfo": {
      "$uid":{
          ".read": "data.child('FireId').val()===auth.uid"
       }
    }


问:
Statistical regression on multi-dimensional data
I have a set of data in (x, y, z) format where z is the output of some formula involving x and y. I want to find out what the formula is, and my Internet research suggests that statistical regression is the way to do this.

However, all of the examples I have found while researching only deal with two-dimensional data sets (x, y) which is not useful for my situation. Said examples also don't seem to provide a way to see what the resulting formula is, they just provide a function for predicting future outputs based on data not in a training data set.

The level of precision needed is that the formula for z needs to produce results within +/- 0.5 of actual values.

Can anyone tell me how I can do what I want to do? Please note I was not asking for specific recommendations on a software library to use.

答:
The most basic tool you need to use is Multiple linear regression. The basic method models z as a linear function of x and y, added a Gaussian noise e on top of them: f(x,y) = a1*x + a2*y + a3 and then z is produced as f(x,y) + e, where e is usually a zero mean Gaussian with unknown variance. You need to find the coefficients a1,a2 and the bias a3, which are usually estimated with Maximum Likelihood, which then boils down to ordinary least squares under the Gaussian assumption. It has closed form analytic solution.

Since you have access to Python, take a look to linear regression in scikit-learn:
http://scikit-learn.org/stable/modules/linear_model.html#ordinary-least-squares


问:
How to show alert pop-up in in Cocoa on macOS?
I want to display a pop-up for displaying information in macOS, similar to a UIAlert or UIAlertController in iOS.

Is their anything in Cocoa similar to UIAlertView in iOS? How can I pop-up an alert in macOS?

答:
Swift 3.0 Example :

Declaration:

```<code> func showCloseAlert(completion: (Bool) -> Void) {
        let alert = NSAlert()
        alert.messageText = "Warning!"
        alert.informativeText = "Nothing will be saved!"
        alert.alertStyle = NSAlertStyle.warning
        alert.addButton(withTitle: "OK")
        alert.addButton(withTitle: "Cancel")
        completion(alert.runModal() == NSAlertFirstButtonReturn)
 }
</code>```

Usage :

```<code>    showCloseAlert { answer in
        if answer {
            self.dismissViewController(self)
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Swift 3.0 Example :

Declaration:

 func showCloseAlert(completion: (Bool) -> Void) {
        let alert = NSAlert()
        alert.messageText = "Warning!"
        alert.informativeText = "Nothing will be saved!"
        alert.alertStyle = NSAlertStyle.warning
        alert.addButton(withTitle: "OK")
        alert.addButton(withTitle: "Cancel")
        completion(alert.runModal() == NSAlertFirstButtonReturn)
 }

Usage :

    showCloseAlert { answer in
        if answer {
            self.dismissViewController(self)
        }
    }


问:
Why do I keep getting the $[injector:modulerr] uncaught error when all dependencies have been injected?
Below is my index.html page which has two buttons which links to 2 different views which i intend to show using angular routing.

Below is my

HTML

```<code><!DOCTYPE html>
<html>
<head>
    <title>PR_APP</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-route.js"></script>
    <script src="js/main.js"></script>
    <script src="js/services.js"></script>
</head>
<body ng-app="new_pr_app">
    <h2>Please select an option</h2><br>
    <div ng-controller="view_controller">
        <button id="view_details" ng-click="view()">View Details</button>
    </div>

    <div ng-controller="update_controller">
        <button id="update_details" ng-click="update()">Update Details</button>
    </div>

    <div ng-view>

    </div>

</body>
</code>```

Below is my main.js file which houses both above mentioned controller and logic for angular routing.

main.js

```<code>var app = angular.module('new_pr_app', ['ngRoute']);

app.config('$routeProvider','$locationProvider', function($routeProvider,$locationProvider){
        $routeProvider.when("/update",
        {
            templateUrl:"update.html",
            controller: "update_controller"
        })
        .when("/view",
        {
            templateUrl: "view.html",
            controller: "view_controller"
        });
});

app.controller("view_controller",function($scope, $location, http_factory){
$scope.view = function(){
    $location.path("/view");
}
    $scope.result =[];
    http_factory.get_request().then(function(response){
        $scope.result = response.data;
    });
});

app.controller("update_controller",function($scope, $location, http_factory){
$scope.update_details = function(){
    $location.path("/update");
}
    $scope.names = [];
    http_factory.get_request().then(function(response){
        $scope.names = response.data;
    });
});
</code>```

I have another file called services.js which has a service factory to get details from a json file using an http get.

My only problem seems to be in the above main.js which gives the error below everytime index.html loads

angular.js:88 Uncaught Error: [$injector:modulerr]

答:
You can check with below code.

<!DOCTYPE html>

Please select an option

        <button id="view_details" ng-click="view()">View Details</button>

        <button id="update_details" ng-click="update_details()">Update Details</button>

```

Body:
Below is my index.html page which has two buttons which links to 2 different views which i intend to show using angular routing.

Below is my

HTML

<!DOCTYPE html>

    <title>PR_APP</title>
    <link rel="stylesheet" href="css/style.css">

Please select an option

        <button id="view_details" ng-click="view()">View Details</button>

        <button id="update_details" ng-click="update()">Update Details</button>

Below is my main.js file which houses both above mentioned controller and logic for angular routing.

main.js

var app = angular.module('new_pr_app', ['ngRoute']);

app.config('$routeProvider','$locationProvider', function($routeProvider,$locationProvider){
        $routeProvider.when("/update",
        {
            templateUrl:"update.html",
            controller: "update_controller"
        })
        .when("/view",
        {
            templateUrl: "view.html",
            controller: "view_controller"
        });
});

app.controller("view_controller",function($scope, $location, http_factory){
$scope.view = function(){
    $location.path("/view");
}
    $scope.result =[];
    http_factory.get_request().then(function(response){
        $scope.result = response.data;
    });
});

app.controller("update_controller",function($scope, $location, http_factory){
$scope.update_details = function(){
    $location.path("/update");
}
    $scope.names = [];
    http_factory.get_request().then(function(response){
        $scope.names = response.data;
    });
});

I have another file called services.js which has a service factory to get details from a json file using an http get.

My only problem seems to be in the above main.js which gives the error below everytime index.html loads

angular.js:88 Uncaught Error: [$injector:modulerr]

Body:
You can check with below code.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-route.js"></script>
<body ng-app="new_pr_app">

  <h2>Please select an option</h2><br>
    <div ng-controller="view_controller">
        <button id="view_details" ng-click="view()">View Details</button>
    </div>

    <div ng-controller="update_controller">
        <button id="update_details" ng-click="update_details()">Update Details</button>
    </div>

    <div ng-view>

    </div>

<script>
var app = angular.module('new_pr_app', ['ngRoute']);

app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider){
        $routeProvider.when("/update",
        {
            template:"update template"
           // controller: "update_controller"
        })
        .when("/view",
        {
            template: "view template"
           // controller: "view_controller"
        });
}]);

app.controller("view_controller",function($scope, $location){
$scope.view = function(){
    $location.path("/view");
}
});

app.controller("update_controller",function($scope, $location){
$scope.update_details = function(){
    $location.path("/update");
}

});
</script>

</body>
</html>


问:
How to parse the next xml using XPath in java?I want to extract the cue and the xscope from a sentence?
This is my java code:

```<code>class SentenceNode {
    Node xscope;
    Node cue;
}

List<SentenceNode> getSentenceNodes(InputSource is) {
    List<SentenceNode> sentenceNodes = new ArrayList<SentenceNode>();
    try {

        Object xscopes = XPathFactory
                .newInstance()
                .newXPath()
                .evaluate("//xscope/cue", is,
                        XPathConstants.NODESET);
        if (xscopes != null) {
            NodeList cuesNodes = (NodeList) xscopes;
            for (int i = 0; i < cuesNodes.getLength(); i++) {
                SentenceNode sentenceNode = new SentenceNode();
                Node cue = cuesNodes.item(i);
                sentenceNode.cue = cue;
                NodeList xscope = cue.getParentNode().getParentNode()
                        .getChildNodes();
                for (int j = 0; j < xscope.getLength(); j++) {
                    Node n = xscope.item(j);
                    if (n.getNodeName().equals("xscope")) {
                        sentenceNode.xscope = n;
                        break;
                    }
                }
                sentenceNodes.add(sentenceNode);

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sentenceNodes;
}

public void displaySentenceNodes() throws ClassNotFoundException, ClassCastException,
        IOException {
    InputSource is = new InputSource(new StringReader("TestBIO.xml"));
    List<SentenceNode> nodes = getSentenceNodes(is);
    for (SentenceNode node : nodes) {

        System.out.println("Xscope: " + node.xscope.getTextContent());
        System.out
                .println("Cue: " + node.cue.getTextContent());

    }
</code>```

I want to extract from this xml the sentence with its cue and xscope.For each sentence I want to obtain the xscope and cue.If the sentence has more xscopes and more cues I want to obtain all.
 Here is my xml:

```<code>   <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Annotation created="22/2/2010" creator="BioscopeWriterCasConsumer">
<DocumentSet>
        <Document type="Biological_abstract">
            <DocID type="PMID">1984449</DocID>
                <DocumentPart type="AbstractText">
                <sentence>When cells were infected with HIV, no induction of NF-KB factor was detected, <xscope>whereas high level of progeny virions was produced, <cue>suggesting</cue> that</xscope>.</sentence>
                <sentence> HIV <xscope><cue>could</cue> mimic some differentiation/activation stimuli allowing nuclear NF-KB expression</xscope>.</sentence>
                </DocumentPart>
        </Document>
</DocumentSet>
</Annotation>
</code>```

An error occured when I am trying to parse the xml file.

```<code>[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(Unknown Source)
</code>```

答:
You are missing ? Character in xml. Should start:</p>

```<code>  <?xml version="
</code>```

Body:
This is my java code:

class SentenceNode {
    Node xscope;
    Node cue;
}

List<SentenceNode> getSentenceNodes(InputSource is) {
    List<SentenceNode> sentenceNodes = new ArrayList<SentenceNode>();
    try {

        Object xscopes = XPathFactory
                .newInstance()
                .newXPath()
                .evaluate("//xscope/cue", is,
                        XPathConstants.NODESET);
        if (xscopes != null) {
            NodeList cuesNodes = (NodeList) xscopes;
            for (int i = 0; i < cuesNodes.getLength(); i++) {
                SentenceNode sentenceNode = new SentenceNode();
                Node cue = cuesNodes.item(i);
                sentenceNode.cue = cue;
                NodeList xscope = cue.getParentNode().getParentNode()
                        .getChildNodes();
                for (int j = 0; j < xscope.getLength(); j++) {
                    Node n = xscope.item(j);
                    if (n.getNodeName().equals("xscope")) {
                        sentenceNode.xscope = n;
                        break;
                    }
                }
                sentenceNodes.add(sentenceNode);

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sentenceNodes;
}

public void displaySentenceNodes() throws ClassNotFoundException, ClassCastException,
        IOException {
    InputSource is = new InputSource(new StringReader("TestBIO.xml"));
    List<SentenceNode> nodes = getSentenceNodes(is);
    for (SentenceNode node : nodes) {

        System.out.println("Xscope: " + node.xscope.getTextContent());
        System.out
                .println("Cue: " + node.cue.getTextContent());

    }

I want to extract from this xml the sentence with its cue and xscope.For each sentence I want to obtain the xscope and cue.If the sentence has more xscopes and more cues I want to obtain all.
 Here is my xml:

   <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Annotation created="22/2/2010" creator="BioscopeWriterCasConsumer">
<DocumentSet>
        <Document type="Biological_abstract">
            <DocID type="PMID">1984449</DocID>
                <DocumentPart type="AbstractText">
                <sentence>When cells were infected with HIV, no induction of NF-KB factor was detected, <xscope>whereas high level of progeny virions was produced, <cue>suggesting</cue> that</xscope>.</sentence>
                <sentence> HIV <xscope><cue>could</cue> mimic some differentiation/activation stimuli allowing nuclear NF-KB expression</xscope>.</sentence>
                </DocumentPart>
        </Document>
</DocumentSet>
</Annotation>

An error occured when I am trying to parse the xml file.

[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(Unknown Source)

Body:
You are missing ? Character in xml. Should start:

  <?xml version="