问:
Run time of flattening a binary tree
For a simple algorithm that flattens a binary tree given this structure:

```<code>class Tree(object):
   def __init__(self, x):
     self.value = x
     self.left = None
     self.right = None
</code>```

What would the run time be for this algorithm that flattens a binary tree into an array?

```<code>def flatten(root):
    if root == None:
        return []
    return flatten(root.left) + [root.value] + flatten(root.right)
</code>```

I am thinking it's N time, 2N space complexity because the algorithm is going from the root and then out to the left and the right nodes.

I think it's 2N space complexity because you still have the N space the tree is occupying and N space from the resulting array.

Am I thinking about this the right way?

答:
Typically, the running time for an in-order traversal of a binary tree is O(N), because you visit each node in the tree exactly once. However, your code is concatenating arrays which, according to https://stackoverflow.com/a/33191492/56778, is an O(N) operation. If that's true, which it appears to be, then the running time of your code will be O(N^2).

When talking about space complexity, we normally talk about extra space: space that is in addition to the space already taken up by the data structure. Sometimes they don't include the space for the output array.

In your case, it takes O(N) space for the new array, plus O(log N) space for the recursion stack, provided the tree is balanced. If the tree is unbalanced, it could require up to O(N) extra space for the recursion stack.

So the extra space is O(N) + O(N) if the tree is unbalanced, or O(N) + O(log N) if the tree is balanced. Either way, it's considered O(N) extra space.

Title: Run time of flattening a binary tree

Body:
For a simple algorithm that flattens a binary tree given this structure:

class Tree(object):
   def __init__(self, x):
     self.value = x
     self.left = None
     self.right = None

What would the run time be for this algorithm that flattens a binary tree into an array?

def flatten(root):
    if root == None:
        return []
    return flatten(root.left) + [root.value] + flatten(root.right)

I am thinking it's N time, 2N space complexity because the algorithm is going from the root and then out to the left and the right nodes.

I think it's 2N space complexity because you still have the N space the tree is occupying and N space from the resulting array.

Am I thinking about this the right way?


来源: stackexchange

问:
Can SqlBulkCopy affect incremental values when copying indexes?
I have a database whose last index was 419728 and I want to insert data starting from 421662 and ignore the value starting  from 419279 to 421661
is it possible to jump in that values?

答:
DBCC CHECKIDENT can reset the identity value of the table.

If you want next record to have identity as 421662, execute following:

```<code>DBCC CHECKIDENT (table_name, reseed, 421661)
</code>```

HTH!

ContentLicense: CC BY-SA 3.0

Body:
DBCC CHECKIDENT can reset the identity value of the table.

If you want next record to have identity as 421662, execute following:

DBCC CHECKIDENT (table_name, reseed, 421661)

HTH!


问:
Unexpected results in prolog
Why do I get so many true results instead of just one? Here are how I define my rules: </p>

```<code>parent(X,Y):- or(father(X,Y), mother(X,Y)).
sister(X,Y):- female(X), parent(P, X), parent(P,Y).
aunt(X,Y):- female(X), sister(X,P), parent(P,Y).

?- aunt(molly, johnny).
true ;
true ;
true ;
true ;
true ;
true ;
true ;
true ;
true ;
true.
</code>```

答:
As @Steven mentioned in his comment, the result depends on the predicates you have, especially the atom ones. for example the following code will result in a two "true" result because parent(X,Y):- father(X,Y);mother(X,Y).
would match both the father and mother predicates for molly & alex.

```<code>father(dan,molly).
father(dan,alex).
father(alex,johnny).

mother(jess,molly).
mother(jess,alex).

female(molly).

parent(X,Y):- father(X,Y) ; mother(X,Y).

sister(X,Y):- female(X), parent(P, X), parent(P,Y), X \= Y.

aunt(X,Y):- sister(X,P), parent(P,Y).

?- aunt(molly, johnny).
true ;
true .
</code>```

If you need to get a single matching (e.g. a single true result), you could use the cut ! predicate at the end of aunt predicate, such as aunt(X,Y):- female(X), sister(X,P), parent(P,Y),!.

In this case the code will be as follows:

```<code>father(dan,molly).
father(dan,alex).
father(alex,johnny).

mother(jess,molly).
mother(jess,alex).

female(molly).

parent(X,Y):- father(X,Y) ; mother(X,Y).

sister(X,Y):- female(X), parent(P, X), parent(P,Y), X \= Y.

aunt(X,Y):- sister(X,P), parent(P,Y),!.

?- aunt(molly, johnny).
true .
</code>```

Title: Unexpected results in prolog

Body:
Why do I get so many true results instead of just one? Here are how I define my rules:

parent(X,Y):- or(father(X,Y), mother(X,Y)).
sister(X,Y):- female(X), parent(P, X), parent(P,Y).
aunt(X,Y):- female(X), sister(X,P), parent(P,Y).

?- aunt(molly, johnny).
true ;
true ;
true ;
true ;
true ;
true ;
true ;
true ;
true ;
true.

Body:
As @Steven mentioned in his comment, the result depends on the predicates you have, especially the atom ones. for example the following code will result in a two "true" result because parent(X,Y):- father(X,Y);mother(X,Y).
would match both the father and mother predicates for molly & alex.

father(dan,molly).
father(dan,alex).
father(alex,johnny).

mother(jess,molly).
mother(jess,alex).

female(molly).

parent(X,Y):- father(X,Y) ; mother(X,Y).

sister(X,Y):- female(X), parent(P, X), parent(P,Y), X \= Y.

aunt(X,Y):- sister(X,P), parent(P,Y).

?- aunt(molly, johnny).
true ;
true .

If you need to get a single matching (e.g. a single true result), you could use the cut ! predicate at the end of aunt predicate, such as aunt(X,Y):- female(X), sister(X,P), parent(P,Y),!.

In this case the code will be as follows:

father(dan,molly).
father(dan,alex).
father(alex,johnny).

mother(jess,molly).
mother(jess,alex).

female(molly).

parent(X,Y):- father(X,Y) ; mother(X,Y).

sister(X,Y):- female(X), parent(P, X), parent(P,Y), X \= Y.

aunt(X,Y):- sister(X,P), parent(P,Y),!.

?- aunt(molly, johnny).
true .


问:
How to create clickable link with GWT?
I want to make some clickable links with GWT. I'm not sure if this is the best practice for it. Basically I want something that similar like this if I would've written with html

Link

答:
Use a Hyperlink if you want to "link to some place" in your app (meaning it fires a History change event).<br>
Use an Anchor if you want to link to a site ouside of your app. </p>

```<code>Hyperlink link = new Hyperlink("link to foo", "foo"); //text would be "link to foo", would change your url to yourSite.html#foo
Anchor anchor = new Anchor("Link to bar", "www.bar.com"); //text would be "link to bar", would redirect you to "www.bar.com"
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to create clickable link with GWT?

Body:
Use a Hyperlink if you want to "link to some place" in your app (meaning it fires a History change event).

Use an Anchor if you want to link to a site ouside of your app.

Hyperlink link = new Hyperlink("link to foo", "foo"); //text would be "link to foo", would change your url to yourSite.html#foo
Anchor anchor = new Anchor("Link to bar", "www.bar.com"); //text would be "link to bar", would redirect you to "www.bar.com"


问:
this.name is undefined in my Mongoose schema
I'm having a problem. In my kittySchema Mongoose schema. Line 21. I'm trying to get this.name from within the schema object but I'm getting undefined.
I know what the problem is. I'm using an arrow function and It's looking for the this.name property in the arrow function instead of the object that the arrow function is in. Is there a way around this instead of me using a regular vanilla js function?
`

```<code>// Requiring Mongoose
const mongoose = require("mongoose");

const establishConnection = () => {
    // Establishing a connection to Mongoose
    mongoose.connect("mongodb://localhost/kittens");

    // Getting the Mongoose database from the pending connection
    const db = mongoose.connection;

    // Watching for Mongoose errors
    db.on("error", console.error.bind(console, "Connection error:"))
    // A connection was succesfully established
    db.once("open", () => {
        console.log("A connection was established");
        const kittySchema = mongoose.Schema({
            name: String
        });`enter code here`
        mongoose.
        kittySchema.methods.speak = () => {
            console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
        }
        const Kitten = mongoose.model("Kitten", kittySchema);
        const silence = new Kitten({ name: "Silence" });
        console.log(`A new kitty named ${silence.name} was successfully added to your database!`);
        silence.speak();
    })
}

module.exports = {
    establishConnection
}
</code>```

`

答:
Well, as you already know, Arrow function does not have a this itself, so you already got the problem, what you can do, is to wrap your arrow function within a regular function :

```<code>var myKitty = {
  name: "Majid",
  kittyMethod : function() {
    return (() => {
        console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
    })();
}
}
myKitty.kittyMethod ();//Mew, My Name is Majid
</code>```

https://jsfiddle.net/a2ww7tby/

Body:
I'm having a problem. In my kittySchema Mongoose schema. Line 21. I'm trying to get this.name from within the schema object but I'm getting undefined.
I know what the problem is. I'm using an arrow function and It's looking for the this.name property in the arrow function instead of the object that the arrow function is in. Is there a way around this instead of me using a regular vanilla js function?
`

// Requiring Mongoose
const mongoose = require("mongoose");

const establishConnection = () => {
    // Establishing a connection to Mongoose
    mongoose.connect("mongodb://localhost/kittens");

    // Getting the Mongoose database from the pending connection
    const db = mongoose.connection;

    // Watching for Mongoose errors
    db.on("error", console.error.bind(console, "Connection error:"))
    // A connection was succesfully established
    db.once("open", () => {
        console.log("A connection was established");
        const kittySchema = mongoose.Schema({
            name: String
        });`enter code here`
        mongoose.
        kittySchema.methods.speak = () => {
            console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
        }
        const Kitten = mongoose.model("Kitten", kittySchema);
        const silence = new Kitten({ name: "Silence" });
        console.log(`A new kitty named ${silence.name} was successfully added to your database!`);
        silence.speak();
    })
}

module.exports = {
    establishConnection
}

`

Body:
Well, as you already know, Arrow function does not have a this itself, so you already got the problem, what you can do, is to wrap your arrow function within a regular function :

var myKitty = {
  name: "Majid",
  kittyMethod : function() {
    return (() => {
        console.log(this.name ? `Meow, My name is ${this.name}.` : "I don't have a name.");
    })();
}
}
myKitty.kittyMethod ();//Mew, My Name is Majid

https://jsfiddle.net/a2ww7tby/


问:
Call to a member function watermark() in codeigniter
I need to add watermark to the existing image.  Codeigniter provides such functionality under image_lib library. Based on the instruction given here , i have done. Fatal error is displaying instead of the result.

A PHP Error was encountered

Severity: Error

Message: Call to a member function watermark() on null

Filename: controllers/Imageman.php

Line Number: 22

Code is

```<code>        $config['image_library'] = 'gd2';
        $config['source_img']='images/images.jpg';
        $config['wm_text']='Hi welcome..!';
        $config['wm_type']='text';
        $config['wm_font_path']='./system/fonts/texb.ttf';
        $config['wm_font_size']='16';
        $config['wm_font_color']='ffffff';
        $config['wm_vrt_alignment']='bottom';
        $config['wm_hor_alignment']='center';
        $config['wm_padding']='20';

        $this->load->library('Image_lib',$config);
        $this->Image_lib->watermark();
        if($this->Image_lib->watermark())
        {
            echo "Watermark added";
        }
        else
        {
            echo "Failed";
        }
</code>```

答:
After looking at the documentation, it uses:

$config['source_image'] instead of $config['source_img']

Body:
I need to add watermark to the existing image.  Codeigniter provides such functionality under image_lib library. Based on the instruction given here , i have done. Fatal error is displaying instead of the result.

A PHP Error was encountered

Severity: Error

Message: Call to a member function watermark() on null

Filename: controllers/Imageman.php

Line Number: 22

Code is

        $config['image_library'] = 'gd2';
        $config['source_img']='images/images.jpg';
        $config['wm_text']='Hi welcome..!';
        $config['wm_type']='text';
        $config['wm_font_path']='./system/fonts/texb.ttf';
        $config['wm_font_size']='16';
        $config['wm_font_color']='ffffff';
        $config['wm_vrt_alignment']='bottom';
        $config['wm_hor_alignment']='center';
        $config['wm_padding']='20';

        $this->load->library('Image_lib',$config);
        $this->Image_lib->watermark();
        if($this->Image_lib->watermark())
        {
            echo "Watermark added";
        }
        else
        {
            echo "Failed";
        }


问:
RecyclerView addInArray error when adding
When I add in List<OrderList> any item in loadOrdersData(), it throws this:

D/ViewGroup: addInArray been called, this = android.support.v7.widget.RecyclerView {41cab8f0 VFED.... .F....ID 0,0-480,770 #7f0c0073 app:id/rv}call stack = java.lang.Throwable: addInArray at android.view.ViewGroup.addInArray(ViewGroup.java:3786) at android.view.ViewGroup.addViewInner(ViewGroup.java:3740) at android.view.ViewGroup.addView(ViewGroup.java:3564) at android.view.ViewGroup.addView(ViewGroup.java:3509) at android.support.v7.widget.RecyclerView$5.addView(RecyclerView.java:649) at android.support.v7.widget.ChildHelper.addView(ChildHelper.java:107) at android.support.v7.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:7115) at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7073) at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7061) at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1428) at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377) at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3315) at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3124)  at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3568) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1197) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:433) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1888) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1742) at android.widget.LinearLayout.onLayout(LinearLayout.java:1651) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2323) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2029) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1192) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6231) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788) at android.view.Choreographer.doCallbacks(Choreographer.java:591) at android.view.Choreographer.doFrame(Choreographer.java:560) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774) at android.os.Handler.handleCallback(Handler.java:808) at android.os.Handler.dispatchMessage(Handler.java:103) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:5305) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) at dalvik.system.NativeStart.main(Native Method)

I tried adding: adapter.notifyDataSetChanged(); before setAdapter() in loadOrdersData() but it makes no sense. Does anyone see what it is caused by?

Here's the code:

MainActivity:

```<code>public class CourierActivity extends AppCompatActivity {
    private TableLayout orderTable;
    private RecyclerView recyclerView;
    private RecycleAdapter adapter;
    private List<OrderListItem> listItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.courier_main);

        recyclerView = (RecyclerView) findViewById(R.id.rv);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(CourierActivity.this));
        adapter = new RecycleAdapter(listItems, getApplicationContext());
        recyclerView.setAdapter(adapter);
        loadOrdersData();
    }

    private void loadOrdersData() {
        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest sr = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                listItems = new ArrayList<>();

                try {
                    String rsp = new String(response.getBytes("ISO-8859-1"), "UTF-8");
                    JSONArray orders = new JSONArray(rsp);

                    for (int i = 0; i < orders.length(); i++) {
                        OrderListItem listItem = new OrderListItem(
                                // ..
                        );

                        listItems.add(listItem);
                    }

                    adapter = new RecycleAdapter(listItems, getApplicationContext());
                    recyclerView.setAdapter(adapter);
                } catch (JSONException | UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT);
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                return params;
            }
        };

        queue.add(sr);
    }
}
</code>```

OrderListItem:

```<code>public class OrderListItem {
    private String name;
    private String status;
    private String price;
    private String courier;

    public OrderListItem(String name, String status, String price, String courier) {
        this.name = name;
        this.status = status;
        this.price = price;
        this.courier = courier;
    }

    public String getName() { return name; }

    public String getStatus() { return status;}

    public String getPrice() { return price; }

    public String getCourier() { return courier; }
}
</code>```

RecycleAdapter:

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

    private List<OrderListItem> listItems;
    private Context context;

    public RecycleAdapter(List<OrderListItem> listItems, Context context) {
        this.listItems = listItems;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.rv_item, parent, false);

        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        OrderListItem listItem = listItems.get(position);

        holder.TextViewName.setText(listItem.getName());
        holder.TextViewStatus.setText(listItem.getStatus());
        holder.TextViewPrice.setText(listItem.getPrice());
        holder.TextViewCourier.setText(listItem.getCourier());
    }

    @Override
    public int getItemCount() {
        int count = 0;

        if (listItems != null && !listItems.isEmpty()) {
            count = listItems.size();
        }

        return count;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView TextViewName;
        public TextView TextViewStatus;
        public TextView TextViewPrice;
        public TextView TextViewCourier;

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

            TextViewName = (TextView) itemView.findViewById(R.id.orderListName);
            TextViewStatus = (TextView) itemView.findViewById(R.id.orderListStatus);
            TextViewPrice = (TextView) itemView.findViewById(R.id.orderListPrice);
            TextViewCourier = (TextView) itemView.findViewById(R.id.orderListCourier);
        }
    }

}
</code>```

@layout/rv_item.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">

        <LinearLayout
            android:padding="@dimen/activity_horizontal_margin"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/orderListName"
                android:text="Order name"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/orderListStatus"
                android:text="Status"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/orderListPrice"
                android:text="Price"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/orderListCourier"
                android:text="Courier"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>
</code>```

@layout/main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.seether.myapplication.CourierActivity"
    android:background="#fff"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawerLayout">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rv"/>

</android.support.v4.widget.DrawerLayout>
</code>```

EDIT. Works perfect without log's warnings if I enter custom data into listItems.

答:
Instead of create new ArrayList and RecyclerAdapter instance in onResponse(), I prefer,

Clear listItems.

Add all OrderListItem instance to listItems.

Call notifyDataSetChanged() of adapter.

For example:

```<code>@Override
public void onResponse(String response) {
     listItems.clear();

     try {
         //loop and add all items to listItems here
         adapter.notifyDataSetChanged();
     } catch (JSONException | UnsupportedEncodingException e) {
         e.printStackTrace();
     }
}
</code>```

and make sure that you initialize RecyclerAdapter properly because I do not see any code that create listItems in onCreate() method of CourierActivity.

```<code> listItems = new ArrayList<OrderListItem>();
 adapter = new RecycleAdapter(listItems, getApplicationContext());
</code>```

Body:
When I add in List<OrderList> any item in loadOrdersData(), it throws this:

D/ViewGroup: addInArray been called, this = android.support.v7.widget.RecyclerView {41cab8f0 VFED.... .F....ID 0,0-480,770 #7f0c0073 app:id/rv}call stack = java.lang.Throwable: addInArray at android.view.ViewGroup.addInArray(ViewGroup.java:3786) at android.view.ViewGroup.addViewInner(ViewGroup.java:3740) at android.view.ViewGroup.addView(ViewGroup.java:3564) at android.view.ViewGroup.addView(ViewGroup.java:3509) at android.support.v7.widget.RecyclerView$5.addView(RecyclerView.java:649) at android.support.v7.widget.ChildHelper.addView(ChildHelper.java:107) at android.support.v7.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:7115) at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7073) at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:7061) at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1428) at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377) at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3315) at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3124)  at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3568) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1197) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:433) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1888) at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1742) at android.widget.LinearLayout.onLayout(LinearLayout.java:1651) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:515) at android.widget.FrameLayout.onLayout(FrameLayout.java:450) at android.view.View.layout(View.java:15125) at android.view.ViewGroup.layout(ViewGroup.java:4862) at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2323) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2029) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1192) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6231) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788) at android.view.Choreographer.doCallbacks(Choreographer.java:591) at android.view.Choreographer.doFrame(Choreographer.java:560) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774) at android.os.Handler.handleCallback(Handler.java:808) at android.os.Handler.dispatchMessage(Handler.java:103) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:5305) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) at dalvik.system.NativeStart.main(Native Method)

I tried adding: adapter.notifyDataSetChanged(); before setAdapter() in loadOrdersData() but it makes no sense. Does anyone see what it is caused by?

Here's the code:

MainActivity:

public class CourierActivity extends AppCompatActivity {
    private TableLayout orderTable;
    private RecyclerView recyclerView;
    private RecycleAdapter adapter;
    private List<OrderListItem> listItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.courier_main);

        recyclerView = (RecyclerView) findViewById(R.id.rv);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(CourierActivity.this));
        adapter = new RecycleAdapter(listItems, getApplicationContext());
        recyclerView.setAdapter(adapter);
        loadOrdersData();
    }

    private void loadOrdersData() {
        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest sr = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                listItems = new ArrayList<>();

                try {
                    String rsp = new String(response.getBytes("ISO-8859-1"), "UTF-8");
                    JSONArray orders = new JSONArray(rsp);

                    for (int i = 0; i < orders.length(); i++) {
                        OrderListItem listItem = new OrderListItem(
                                // ..
                        );

                        listItems.add(listItem);
                    }

                    adapter = new RecycleAdapter(listItems, getApplicationContext());
                    recyclerView.setAdapter(adapter);
                } catch (JSONException | UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT);
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                return params;
            }
        };

        queue.add(sr);
    }
}

OrderListItem:

public class OrderListItem {
    private String name;
    private String status;
    private String price;
    private String courier;

    public OrderListItem(String name, String status, String price, String courier) {
        this.name = name;
        this.status = status;
        this.price = price;
        this.courier = courier;
    }

    public String getName() { return name; }

    public String getStatus() { return status;}

    public String getPrice() { return price; }

    public String getCourier() { return courier; }
}

RecycleAdapter:

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

    private List<OrderListItem> listItems;
    private Context context;

    public RecycleAdapter(List<OrderListItem> listItems, Context context) {
        this.listItems = listItems;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.rv_item, parent, false);

        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        OrderListItem listItem = listItems.get(position);

        holder.TextViewName.setText(listItem.getName());
        holder.TextViewStatus.setText(listItem.getStatus());
        holder.TextViewPrice.setText(listItem.getPrice());
        holder.TextViewCourier.setText(listItem.getCourier());
    }

    @Override
    public int getItemCount() {
        int count = 0;

        if (listItems != null && !listItems.isEmpty()) {
            count = listItems.size();
        }

        return count;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView TextViewName;
        public TextView TextViewStatus;
        public TextView TextViewPrice;
        public TextView TextViewCourier;

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

            TextViewName = (TextView) itemView.findViewById(R.id.orderListName);
            TextViewStatus = (TextView) itemView.findViewById(R.id.orderListStatus);
            TextViewPrice = (TextView) itemView.findViewById(R.id.orderListPrice);
            TextViewCourier = (TextView) itemView.findViewById(R.id.orderListCourier);
        }
    }

}

@layout/rv_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">

        <LinearLayout
            android:padding="@dimen/activity_horizontal_margin"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/orderListName"
                android:text="Order name"
                android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/orderListStatus"
                android:text="Status"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/orderListPrice"
                android:text="Price"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/orderListCourier"
                android:text="Courier"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

@layout/main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.seether.myapplication.CourierActivity"
    android:background="#fff"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawerLayout">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rv"/>

</android.support.v4.widget.DrawerLayout>

EDIT. Works perfect without log's warnings if I enter custom data into listItems.

Body:
Instead of create new ArrayList and RecyclerAdapter instance in onResponse(), I prefer,

Clear listItems.

Add all OrderListItem instance to listItems.

Call notifyDataSetChanged() of adapter.

For example:

@Override
public void onResponse(String response) {
     listItems.clear();

     try {
         //loop and add all items to listItems here
         adapter.notifyDataSetChanged();
     } catch (JSONException | UnsupportedEncodingException e) {
         e.printStackTrace();
     }
}

and make sure that you initialize RecyclerAdapter properly because I do not see any code that create listItems in onCreate() method of CourierActivity.

 listItems = new ArrayList<OrderListItem>();
 adapter = new RecycleAdapter(listItems, getApplicationContext());


问:
Is it possible to execute a stored procedure over a set without using a cursor?
I would like to execute a stored procedure over each row in a set without using a cursor with something like this:

SELECT EXEC dbo.Sproc @Param1 = Table1.id

FROM Table1

I am using T-SQL in SQL Server 2005. I think this might be possible using a function, but I'd like to use a stored procedure if possible (company standards)

答:
Yes. If you have a column you can use within the table to mark the ones processed, you can use WHILE EXISTS:

```<code>DECLARE @Id int
WHILE EXISTS(SELECT * FROM Table1 WHERE Processed='N')
BEGIN
 SELECT Top 1 @Id = id from Table1 WHERE Procesed='N'
 EXEC dbo.Sproc @Id
 UPDATE Table1 SET Processed = 'Y' WHERE Id = @Id
END
</code>```

Alternately, dump the ids into a temp table or table variable and delete when finished:

```<code>DECLARE @HoldTable table (Id int PRIMARY KEY)
DECLARE @Id int
INSERT INTO @HoldTable SELECT Id FROM Table1
WHILE EXISTS(SELECT * FROM @HoldTable)
BEGIN
 SELECT @Id = id from @HoldTable
 EXEC dbo.Sproc @Id
 DELETE FROM @HoldTable where Id = @Id
END
</code>```

Body:
Yes. If you have a column you can use within the table to mark the ones processed, you can use WHILE EXISTS:

DECLARE @Id int
WHILE EXISTS(SELECT * FROM Table1 WHERE Processed='N')
BEGIN
 SELECT Top 1 @Id = id from Table1 WHERE Procesed='N'
 EXEC dbo.Sproc @Id
 UPDATE Table1 SET Processed = 'Y' WHERE Id = @Id
END

Alternately, dump the ids into a temp table or table variable and delete when finished:

DECLARE @HoldTable table (Id int PRIMARY KEY)
DECLARE @Id int
INSERT INTO @HoldTable SELECT Id FROM Table1
WHILE EXISTS(SELECT * FROM @HoldTable)
BEGIN
 SELECT @Id = id from @HoldTable
 EXEC dbo.Sproc @Id
 DELETE FROM @HoldTable where Id = @Id
END

OwnerDisplayName: Josef


问:
print job accounting using cups+mysql?
I want to set up a server connected to a physical printer.This server hosts a site to allow users to login and send print jobs from their system either remotely or by first uploading it to the server and the server printing it locally , the host is linux machine , uses cups to print. the website needs following features : -

display the printing stats for each user and amount of pages printed(maybe use mysql)

interact with cups for handling print jobs

I have basic knowledge of php,mysql but no idea about cups.

How do i go about it and what are the keywords i should be looking for . Existing solutions like papercut or pykota are either expensive or too complicated for my simple requirements.

答: There is a fully-fledged CUPS job accounting software already: PyKota: written in Python, licensed under GPL, with quite a few supported database apps in its backend (MySQL amongst them, though they recommend to use Postgres).

Title: print job accounting using cups+mysql?


问:
my spring-boot mvc application always shutdown by showing
```<code>   .   ____          _            __ _ _
  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
 ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
   '  |____| .__|_| |_|_| |_\__, | / / / /
  =========|_|==============|___/=/_/_/_/
  :: Spring Boot ::        (v1.5.6.RELEASE)

 2017-09-03 16:43:53.881  INFO 6584 --- [           main] c.n.SpringBootMvcExampleApplication      : Starting SpringBootMvcExampleApplication on lenovo-PC with PID 6584 (C:\Users\lenovo\Documents\workspace-sts-3.8.4.RELEASE\SpringBootMVCExample\target\classes started by lenovo in C:\Users\lenovo\Documents\workspace-sts-3.8.4.RELEASE\SpringBootMVCExample)
 2017-09-03 16:43:53.896  INFO 6584 --- [           main] c.n.SpringBootMvcExampleApplication      : No active profile set, falling back to default profiles: default
 2017-09-03 16:43:54.218  INFO 6584 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6e38921c: startup date [Sun Sep 03 16:43:54 IST 2017]; root of context hierarchy
 2017-09-03 16:43:56.213  INFO 6584 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup 2017-09-03 16:43:56.294  INFO 6584 --- [           main] c.n.SpringBootMvcExampleApplication      : Started SpringBootMvcExampleApplication in 3.284 seconds (JVM running for 3.931)
 2017-09-03 16:43:56.297  INFO 6584 --- [       Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6e38921c: startup date [Sun Sep 03 16:43:54 IST 2017]; root of context hierarchy
 2017-09-03 16:43:56.304  INFO 6584 --- [       Thread-3] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
</code>```

答:
Same issue I was facing and I found that i did't tell the Spring about the server to be used. By adding below maven dependency it worked for me.

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
</code>```

Later I investigate and found that the pom.xml inside the above artifact (spring-boot-starter-data-rest) itself reference the below maven artifacts, which instruct Spring to add the embedded server and use it while running the app which currently own this pom.xml.

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-rest-webmvc</artifactId>
    </dependency>
</code>```

Interestingly when you go further in the POM file of the artifact (spring-boot-starter-web), you will see that it references for other artifact for tomcat server. Below is the maven artifact you will find in the pom.xml (spring-boot-starter-web)

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
</code>```

Note: As my application was using Rest based Controllers so I need Rest with Json support.  So below maven dependency is suitable for me.

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
</code>```

But those only want server integration, can use below dependency and it must work.

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</code>```

Body:
Same issue I was facing and I found that i did't tell the Spring about the server to be used. By adding below maven dependency it worked for me.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>

Later I investigate and found that the pom.xml inside the above artifact (spring-boot-starter-data-rest) itself reference the below maven artifacts, which instruct Spring to add the embedded server and use it while running the app which currently own this pom.xml.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-rest-webmvc</artifactId>
    </dependency>

Interestingly when you go further in the POM file of the artifact (spring-boot-starter-web), you will see that it references for other artifact for tomcat server. Below is the maven artifact you will find in the pom.xml (spring-boot-starter-web)

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>

Note: As my application was using Rest based Controllers so I need Rest with Json support.  So below maven dependency is suitable for me.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>

But those only want server integration, can use below dependency and it must work.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>


问:
My app crashes sometimes (AsyncTask should be static)
I have an android app that shows the rss of my website and shows a notification when there is new content.

The problem:
My app crashes sometimes, and this is what i can see in Google play Console:

```<code>java.lang.RuntimeException:
  at android.os.AsyncTask$3.done (AsyncTask.java:318)
  at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:354)
  at java.util.concurrent.FutureTask.setException (FutureTask.java:223)
  at java.util.concurrent.FutureTask.run (FutureTask.java:242)
  at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:243)
  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1133)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:607)
  at java.lang.Thread.run (Thread.java:761)

Caused by: java.lang.NullPointerException:
  at com.mydomain.rss.notification.RssNotificationService$SearchForUpdates.doInBackground (RssNotificationService.java:100)
  at com.mydomain.rss.notification.RssNotificationService$SearchForUpdates.doInBackground (RssNotificationService.java:92)
  at android.os.AsyncTask$2.call (AsyncTask.java:304)
  at java.util.concurrent.FutureTask.run (FutureTask.java:237)
</code>```

In android studio I see the following  message:

This AsyncTask class should be static or leaks might occur
  (com.mydomain.rss.notification.RssNotificationService.SearchForUpdates)

The following is the java file I need to modify to fix the problem, but I'm not sure what I have to change to fix the problem:

```<code>package com.mydomain.rss.notification;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.mydomain.rss.FeedReaderActivity;
import com.mydomain.rss.R;
import com.mydomain.rss.SettingsActivity;
import com.mydomain.rss.cache.MainActivityContext;
import com.mydomain.rss.cache.RefreshFeed;
import com.mydomain.rss.parser.RSSItem;
import com.mydomain.rss.utility.RSSutility;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.text.Html;

/**
 * RSS Service Executer
 */

public class RssNotificationService extends Service {

    public static final int NOTIFICATION_ID = 1;
    //public static final String TITLE_ERROR = "Notify Error";

    Handler searchHandler = new Handler();
    Timer searchLoader = new Timer();

     @Override
     public void onCreate() {
         super.onCreate();
         boolean is_notification_on = getPrefrenceBoolean(SettingsActivity.NOTIFICATION, false);
         if (is_notification_on){
             new SearchForUpdates().execute();
         }
     }

     @Override
     public IBinder onBind(Intent intent) {
         return null;
     }

     @Override
     public void onRebind(Intent intent) {
     super.onRebind(intent);
     }

     @Override
     public boolean onUnbind(Intent intent) {
     return true;
     }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public boolean getPrefrenceBoolean(String preference, boolean default_value){
        SharedPreferences sp = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE);
        return sp.getBoolean (preference, default_value);
    }

    public void savePrefrenceString(String preference, String value){
        SharedPreferences.Editor editor = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE).edit();
        editor.putString(preference, value);
        editor.apply();
    }
    public String getPrefrenceString(String preference, String default_value){
        SharedPreferences sp = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE);
        return sp.getString(preference, default_value);
    }

    private class SearchForUpdates extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

                String lastest_title = getPrefrenceString ("lastTitle", "No feed");

                List<RSSItem> feeds = RSSutility.getRSSFeed(getString(R.string.rss_url));
                RSSItem feed = feeds.get(0);
                String title = feed.getTitle();

                if (lastest_title.equalsIgnoreCase(title)){
                    //no update
                }else{
                    showNotification(feed);
                    //store last title so next time will not notify for same rss
                    savePrefrenceString("lastTitle", title);
                }

            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {

             boolean is_notification_on = getPrefrenceBoolean(SettingsActivity.NOTIFICATION, false);
             if (is_notification_on){
                //Reload Menu
                long SEARCH_FREQUENCY = Integer.valueOf(getString(R.string.frequency)) * 60 * 1000;

                searchLoader = new Timer();
                searchLoader.schedule(new TimerTask(){
                    public void run() {
                            searchHandler.post(new Runnable(){
                                public void run(){
                                    new SearchForUpdates().execute();
                                    searchLoader.cancel();
                                }
                            });
                }}, SEARCH_FREQUENCY, SEARCH_FREQUENCY);
             }
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

    private void showNotification(RSSItem feed) {

        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification);

        Uri alarmSound = null;
        boolean is_notification_sound_on = getPrefrenceBoolean(SettingsActivity.NOTIFICATION_SOUND, false);
        if (is_notification_sound_on){
            alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        }

        String html = feed.getDescription();
        html = html.replaceAll("<(.*?)\\>", ""); //Removes all items in brackets
        html = html.replaceAll("<(.*?)\\\n", ""); //Must be undeneath
        html = html.replaceFirst("(.*?)\\>", ""); //Removes any connected item to the last bracket
        html = html.replaceAll(" ", "");
        html = html.replaceAll("&", "");
        html = html.replaceAll("%20", " ");
        html = html.replaceAll("%2C", ", ");
        html = html.replaceAll("%0A", "");

        String title = feed.getTitle();
        title = title.replaceAll("<(.*?)\\>", ""); //Removes all items in brackets
        title = title.replaceAll("<(.*?)\\\n", ""); //Must be undeneath
        title = title.replaceFirst("(.*?)\\>", ""); //Removes any connected item to the last bracket
        title = title.replaceAll(" ", "");
        title = title.replaceAll("&", "");
        title = title.replaceAll("%20", " ");
        title = title.replaceAll("%2C", ", ");
        title = title.replaceAll("%0A", "");

        //String description = feed.getDescription();

        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.ic_launcher).setLargeIcon(icon)
                .setContentTitle(feed.getTitle()).setContentText(html)
                .setAutoCancel(true)
                .setSound(alarmSound);

        NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
        bigText.bigText(Html.fromHtml(html));
        bigText.setBigContentTitle(title);
        bigText.setSummaryText(Html.fromHtml(html));
        builder.setStyle(bigText);

        Intent intent = new Intent(this, FeedReaderActivity.class);
        intent.putExtra("NOTIFICATION", true);
        intent.putExtra("title", feed.getTitle());
        intent.putExtra("description", feed.getDescription());
        intent.putExtra("link", feed.getLink());
        intent.putExtra("pubDate", feed.getPubdate());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);

        // Send the notification to the system.
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, builder.build());

        if (MainActivityContext.instance().activity!=null){
            MainActivityContext.instance().activity.runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent broadcast = new Intent();
                            broadcast.setAction("com.rss.RELOAD_URL");
                            sendBroadcast(broadcast);
                            RefreshFeed.instance().refresh = true;
                        }
                    }, 1000);
                }
            });
        }

    }

}
</code>```

So, if you know how to solve my problem, please reply back with the modifications.

答:
To get rid of the "AsyncTask should be static" warning, you can...make your AsyncTask static. See my full answer for how to do that.

As was noted in the comments, you should cancel the updating the UI if the Activity is no longer around when the AsyncTask gets to onPostExecute. This very easily could happen if it takes a long time for your RSS feeds to load. Here is a code snippet showing how to cancel execution if the Activity is null.

```<code>@Override
protected void onPostExecute(String result) {

    // get a reference to the activity if it is still there
    MyActivity activity = activityReference.get();

    // if it is gone, then cancel the UI update
    if (activity == null) return;

    // update the UI ...
}
</code>```

Body:
I have an android app that shows the rss of my website and shows a notification when there is new content.

The problem:
My app crashes sometimes, and this is what i can see in Google play Console:

java.lang.RuntimeException:
  at android.os.AsyncTask$3.done (AsyncTask.java:318)
  at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:354)
  at java.util.concurrent.FutureTask.setException (FutureTask.java:223)
  at java.util.concurrent.FutureTask.run (FutureTask.java:242)
  at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:243)
  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1133)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:607)
  at java.lang.Thread.run (Thread.java:761)

Caused by: java.lang.NullPointerException:
  at com.mydomain.rss.notification.RssNotificationService$SearchForUpdates.doInBackground (RssNotificationService.java:100)
  at com.mydomain.rss.notification.RssNotificationService$SearchForUpdates.doInBackground (RssNotificationService.java:92)
  at android.os.AsyncTask$2.call (AsyncTask.java:304)
  at java.util.concurrent.FutureTask.run (FutureTask.java:237)

In android studio I see the following  message:

This AsyncTask class should be static or leaks might occur
  (com.mydomain.rss.notification.RssNotificationService.SearchForUpdates)

The following is the java file I need to modify to fix the problem, but I'm not sure what I have to change to fix the problem:

package com.mydomain.rss.notification;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.mydomain.rss.FeedReaderActivity;
import com.mydomain.rss.R;
import com.mydomain.rss.SettingsActivity;
import com.mydomain.rss.cache.MainActivityContext;
import com.mydomain.rss.cache.RefreshFeed;
import com.mydomain.rss.parser.RSSItem;
import com.mydomain.rss.utility.RSSutility;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.text.Html;

/**
 * RSS Service Executer
 */

public class RssNotificationService extends Service {

    public static final int NOTIFICATION_ID = 1;
    //public static final String TITLE_ERROR = "Notify Error";

    Handler searchHandler = new Handler();
    Timer searchLoader = new Timer();

     @Override
     public void onCreate() {
         super.onCreate();
         boolean is_notification_on = getPrefrenceBoolean(SettingsActivity.NOTIFICATION, false);
         if (is_notification_on){
             new SearchForUpdates().execute();
         }
     }

     @Override
     public IBinder onBind(Intent intent) {
         return null;
     }

     @Override
     public void onRebind(Intent intent) {
     super.onRebind(intent);
     }

     @Override
     public boolean onUnbind(Intent intent) {
     return true;
     }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public boolean getPrefrenceBoolean(String preference, boolean default_value){
        SharedPreferences sp = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE);
        return sp.getBoolean (preference, default_value);
    }

    public void savePrefrenceString(String preference, String value){
        SharedPreferences.Editor editor = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE).edit();
        editor.putString(preference, value);
        editor.apply();
    }
    public String getPrefrenceString(String preference, String default_value){
        SharedPreferences sp = getSharedPreferences(this.getPackageName(), Context.MODE_PRIVATE);
        return sp.getString(preference, default_value);
    }

    private class SearchForUpdates extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

                String lastest_title = getPrefrenceString ("lastTitle", "No feed");

                List<RSSItem> feeds = RSSutility.getRSSFeed(getString(R.string.rss_url));
                RSSItem feed = feeds.get(0);
                String title = feed.getTitle();

                if (lastest_title.equalsIgnoreCase(title)){
                    //no update
                }else{
                    showNotification(feed);
                    //store last title so next time will not notify for same rss
                    savePrefrenceString("lastTitle", title);
                }

            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {

             boolean is_notification_on = getPrefrenceBoolean(SettingsActivity.NOTIFICATION, false);
             if (is_notification_on){
                //Reload Menu
                long SEARCH_FREQUENCY = Integer.valueOf(getString(R.string.frequency)) * 60 * 1000;

                searchLoader = new Timer();
                searchLoader.schedule(new TimerTask(){
                    public void run() {
                            searchHandler.post(new Runnable(){
                                public void run(){
                                    new SearchForUpdates().execute();
                                    searchLoader.cancel();
                                }
                            });
                }}, SEARCH_FREQUENCY, SEARCH_FREQUENCY);
             }
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

    private void showNotification(RSSItem feed) {

        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification);

        Uri alarmSound = null;
        boolean is_notification_sound_on = getPrefrenceBoolean(SettingsActivity.NOTIFICATION_SOUND, false);
        if (is_notification_sound_on){
            alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        }

        String html = feed.getDescription();
        html = html.replaceAll("<(.*?)\\>", ""); //Removes all items in brackets
        html = html.replaceAll("<(.*?)\\\n", ""); //Must be undeneath
        html = html.replaceFirst("(.*?)\\>", ""); //Removes any connected item to the last bracket
        html = html.replaceAll(" ", "");
        html = html.replaceAll("&", "");
        html = html.replaceAll("%20", " ");
        html = html.replaceAll("%2C", ", ");
        html = html.replaceAll("%0A", "");

        String title = feed.getTitle();
        title = title.replaceAll("<(.*?)\\>", ""); //Removes all items in brackets
        title = title.replaceAll("<(.*?)\\\n", ""); //Must be undeneath
        title = title.replaceFirst("(.*?)\\>", ""); //Removes any connected item to the last bracket
        title = title.replaceAll(" ", "");
        title = title.replaceAll("&", "");
        title = title.replaceAll("%20", " ");
        title = title.replaceAll("%2C", ", ");
        title = title.replaceAll("%0A", "");

        //String description = feed.getDescription();

        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                this).setSmallIcon(R.drawable.ic_launcher).setLargeIcon(icon)
                .setContentTitle(feed.getTitle()).setContentText(html)
                .setAutoCancel(true)
                .setSound(alarmSound);

        NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
        bigText.bigText(Html.fromHtml(html));
        bigText.setBigContentTitle(title);
        bigText.setSummaryText(Html.fromHtml(html));
        builder.setStyle(bigText);

        Intent intent = new Intent(this, FeedReaderActivity.class);
        intent.putExtra("NOTIFICATION", true);
        intent.putExtra("title", feed.getTitle());
        intent.putExtra("description", feed.getDescription());
        intent.putExtra("link", feed.getLink());
        intent.putExtra("pubDate", feed.getPubdate());
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);

        // Send the notification to the system.
        NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, builder.build());

        if (MainActivityContext.instance().activity!=null){
            MainActivityContext.instance().activity.runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent broadcast = new Intent();
                            broadcast.setAction("com.rss.RELOAD_URL");
                            sendBroadcast(broadcast);
                            RefreshFeed.instance().refresh = true;
                        }
                    }, 1000);
                }
            });
        }

    }

}

So, if you know how to solve my problem, please reply back with the modifications.

Body:
To get rid of the "AsyncTask should be static" warning, you can...make your AsyncTask static. See my full answer for how to do that.

As was noted in the comments, you should cancel the updating the UI if the Activity is no longer around when the AsyncTask gets to onPostExecute. This very easily could happen if it takes a long time for your RSS feeds to load. Here is a code snippet showing how to cancel execution if the Activity is null.

@Override
protected void onPostExecute(String result) {

    // get a reference to the activity if it is still there
    MyActivity activity = activityReference.get();

    // if it is gone, then cancel the UI update
    if (activity == null) return;

    // update the UI ...
}


问:
Unable to play a very simple tone
I was following this question, but the tone that I try to play with an AVAudioPCMBuffer does not play. The code is pretty simple:

```<code>class Player: NSObject {
    var engine = AVAudioEngine()
    var player = AVAudioPlayerNode()
    var mixer: AVAudioMixerNode!
    var buffer: AVAudioPCMBuffer!

    override init() {
        mixer = engine.mainMixerNode
        buffer = AVAudioPCMBuffer(pcmFormat: player.outputFormat(forBus: 0), frameCapacity: 100)
        buffer.frameLength = 100

        let sr = mixer.outputFormat(forBus: 0).sampleRate
        let nChannels = mixer.outputFormat(forBus: 0).channelCount

        var i = 0
        while i < Int(buffer.frameLength) {
            let val = sin(441 * Double(i) * Double.pi / sr)
            buffer.floatChannelData?.pointee[i] = Float(val * 0.5)
            i += Int(nChannels)
        }

        engine.attach(player)
        engine.connect(player, to: mixer, format: player.outputFormat(forBus: 0))

        engine.prepare()
    }

    func play() {
        do {
            try engine.start()
        } catch {
            print(error)
        }

        player.scheduleBuffer(buffer, at: nil, options: .loops) {
            print("Played!")
        }

        player.play()
    }
}
</code>```

For some reason, though, the iPhone does not make any sound. In my ViewController, I have this:

```<code>class ViewController: UIViewController {
    var player = Player()

    override func viewDidAppear(_ animated: Bool) {
        player.play()
    }

}
</code>```

As you can see, player is a class variable, so it should not be deallocated from memory.

When I run the app on my physical device (iPhone 6s iOS 11), it does not work, yet it does work on the simulator. Why is this not making any sound, and how can I fix it?

Thanks in advance!

答:
Make sure your device is not on silent mode.

I just created a project that you can download for testing by yourself: https://github.com/mugx/TestSound

Title: Unable to play a very simple tone

Body:
I was following this question, but the tone that I try to play with an AVAudioPCMBuffer does not play. The code is pretty simple:

class Player: NSObject {
    var engine = AVAudioEngine()
    var player = AVAudioPlayerNode()
    var mixer: AVAudioMixerNode!
    var buffer: AVAudioPCMBuffer!

    override init() {
        mixer = engine.mainMixerNode
        buffer = AVAudioPCMBuffer(pcmFormat: player.outputFormat(forBus: 0), frameCapacity: 100)
        buffer.frameLength = 100

        let sr = mixer.outputFormat(forBus: 0).sampleRate
        let nChannels = mixer.outputFormat(forBus: 0).channelCount

        var i = 0
        while i < Int(buffer.frameLength) {
            let val = sin(441 * Double(i) * Double.pi / sr)
            buffer.floatChannelData?.pointee[i] = Float(val * 0.5)
            i += Int(nChannels)
        }

        engine.attach(player)
        engine.connect(player, to: mixer, format: player.outputFormat(forBus: 0))

        engine.prepare()
    }

    func play() {
        do {
            try engine.start()
        } catch {
            print(error)
        }

        player.scheduleBuffer(buffer, at: nil, options: .loops) {
            print("Played!")
        }

        player.play()
    }
}

For some reason, though, the iPhone does not make any sound. In my ViewController, I have this:

class ViewController: UIViewController {
    var player = Player()

    override func viewDidAppear(_ animated: Bool) {
        player.play()
    }

}

As you can see, player is a class variable, so it should not be deallocated from memory.

When I run the app on my physical device (iPhone 6s iOS 11), it does not work, yet it does work on the simulator. Why is this not making any sound, and how can I fix it?

Thanks in advance!


问:
jquery selector doesn't work when html is replaced!
Please, help me with following problem:

```<code><!-- this is the visible code -->
<div id="divid">{some default content}<img class="img" src="GoNextArrow.jpg" alt=""></div>

<!-- this is a hidden list of contents -->
<div style="display: none;">
    <div id="divid1">{some content 1}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid2">{some content 2}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid3">{some content 3}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid4">{some content 4}<img class="img" src="GoNextArrow.jpg" alt=""></div>
    <div id="divid5">{some content 5}<img class="img" src="GoNextArrow.jpg" alt=""></div>
</div>

<!-- this is an jquery script which replace the #divid with any of divid1-divid5 -->
$('#divid').hide().html(elem.html()).fadeIn();
<!-- elem is a variable, divid1 to divid5, e.g. var elem = $j('#divid'+id);  -->

<!-- I need a rollover effect, I made it so: -->
$('img.img').hover(function () {
    $(this).attr('src', 'GoNextArrowHover.jpg');
}, function () {
    $(this).attr('src', 'GoNextArrow.jpg');
});
</code>```

This works well for the first div divid, but doesn't for divid1-divid5 when these are loaded instead of divid.
Where is my mistake??

Thanks!

答: When you use .html() to replace the contents of an element, you are creating new child elements (img in your case), so you need to rebind your hover handler to the new img element after each call to .html().

Body:
Please, help me with following problem:

{some default content}

{some content 1}

{some content 2}

{some content 3}

{some content 4}

{some content 5}

$('#divid').hide().html(elem.html()).fadeIn();

$('img.img').hover(function () {
    $(this).attr('src', 'GoNextArrowHover.jpg');
}, function () {
    $(this).attr('src', 'GoNextArrow.jpg');
});

This works well for the first div divid, but doesn't for divid1-divid5 when these are loaded instead of divid.
Where is my mistake??

Thanks!


问:
Firefox ver 56 Responsive Design Mode failure
I want to use Firefox's responsive design mode to test my website.

At first I didn't get the drop-down list of selectable devices. I tried resolving this issue by following the steps described here. Although I now get the desired drop-down menu, the "box" only shows a blank page for any webpage I visit. Also, the tab becomes entirely unresponsive, i.e. I cannot return to regular viewing mode and/or load another webpage.

Any ideas? Thanks in advance!

FYI, I'm on FF 56.0.1 build 20171002220106, and Multiprocess Windows shows up as "enabled by user".

答:
I've found that tabs that are completely loaded still fail to move from desktop to responsive view.

However, I've found that while a tab is loading, if I move to responsive view, it successfully loads as responsive. And you can switch between views happily.

(It's probably worth noting that I have about 100 tabs open, and they're all grouped.)


问:
'For loop' to arrange Numbers in ascending order. [ERROR] pointer and integer comparision
This is a very simple program, to arrange numbers in ascending order. Now here I don't know how it says there is the comparison between integer and pointer, in all the for loops. I am a noob by the way. </p>

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

int main()
{

    int number[100],total,i,j,temp;;

    printf("Enter the quantity of the numbers you want \n");
    scanf("%d",&total);

    printf("Enter the numbers \n");
    for(i=0; i<total; i++){

        scanf("%d",&number[i]);
    }

    for(i=0; i < (number-1); i++){

        for(j=(i+1); j  < number; j++){

            if(number[i]>number[j]){
                temp = number[i];
                number[i] = number[j];
                number[j] = temp;
           }

        }

    }
    for(i=0; i < number; i++){

        printf("%d \n", number[i]);
    }

    return 0;
}
</code>```

答:
the following proposed code:

properly checks for errors

properly outputs error messages to stderr

properly minimizes the scope of variables

cleanly compiles

incorporates appropriate horizontal spacing after commas, after semicolons, inside parens, around C operators

performs the desired functionality

makes use of a VLA (variable length array) so the number of numbers could be most any positive number

separates code blocks (for, if, else, while, do...while, switch, case, default) via a single blank line

does not contain random blank lines

documents why each header file is included

does not allow the user to enter a negative count for the number of numbers

follows the axiom: only one statement per line and (at most) one variable declaration per statement.

And now, the proposed code:

```<code>#include <stdio.h>   // scanf(), perror(), printf()
#include <stdlib.h>  // exit(), EXIT_FAILURE

int main( void )
{
    int total;

    printf("Enter the quantity of the numbers you want \n");
    if( 1 != scanf( "%d", &total ) )
    {
        perror( "scanf for count of numbers failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    if( !total )
    {  // then 0 entered
        printf( "Exiting, no numbers to enter\n" );
        return 0;
    }

    // implied else, some numbers to enter

    int number[ total ];   // << uses the VLA feature of C

    for( unsigned i = 0; i < total; i++ )
    {
        printf( "Enter number %u: ", i+1 );

        if( 1 != scanf( "%d", &number[i] ) )
        {
            perror( "scanf for a number failed" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf successful
    }

    for( int i = 0; i < (total - 1); i++ )
    {
        for( int j = (i+1); j < total; j++ )
        {
            if( number[i] > number[j] )
            {
                int temp  = number[i];
                number[i] = number[j];
                number[j] = temp;
            }
        }
    }

    for( unsigned i = 0; i < total; i++ )
    {
        printf("%d \n", number[i]);
    }

    return 0;
} // end function: main
</code>```

Body:
This is a very simple program, to arrange numbers in ascending order. Now here I don't know how it says there is the comparison between integer and pointer, in all the for loops. I am a noob by the way.

#include <stdio.h>

int main()
{

    int number[100],total,i,j,temp;;

    printf("Enter the quantity of the numbers you want \n");
    scanf("%d",&total);

    printf("Enter the numbers \n");
    for(i=0; i<total; i++){

        scanf("%d",&number[i]);
    }

    for(i=0; i < (number-1); i++){

        for(j=(i+1); j  < number; j++){

            if(number[i]>number[j]){
                temp = number[i];
                number[i] = number[j];
                number[j] = temp;
           }

        }

    }
    for(i=0; i < number; i++){

        printf("%d \n", number[i]);
    }

    return 0;
}

Body:
the following proposed code:

properly checks for errors

properly outputs error messages to stderr

properly minimizes the scope of variables

cleanly compiles

incorporates appropriate horizontal spacing after commas, after semicolons, inside parens, around C operators

performs the desired functionality

makes use of a VLA (variable length array) so the number of numbers could be most any positive number

separates code blocks (for, if, else, while, do...while, switch, case, default) via a single blank line

does not contain random blank lines

documents why each header file is included

does not allow the user to enter a negative count for the number of numbers

follows the axiom: only one statement per line and (at most) one variable declaration per statement.

And now, the proposed code:

#include <stdio.h>   // scanf(), perror(), printf()
#include <stdlib.h>  // exit(), EXIT_FAILURE

int main( void )
{
    int total;

    printf("Enter the quantity of the numbers you want \n");
    if( 1 != scanf( "%d", &total ) )
    {
        perror( "scanf for count of numbers failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    if( !total )
    {  // then 0 entered
        printf( "Exiting, no numbers to enter\n" );
        return 0;
    }

    // implied else, some numbers to enter

    int number[ total ];   // << uses the VLA feature of C

    for( unsigned i = 0; i < total; i++ )
    {
        printf( "Enter number %u: ", i+1 );

        if( 1 != scanf( "%d", &number[i] ) )
        {
            perror( "scanf for a number failed" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf successful
    }

    for( int i = 0; i < (total - 1); i++ )
    {
        for( int j = (i+1); j < total; j++ )
        {
            if( number[i] > number[j] )
            {
                int temp  = number[i];
                number[i] = number[j];
                number[j] = temp;
            }
        }
    }

    for( unsigned i = 0; i < total; i++ )
    {
        printf("%d \n", number[i]);
    }

    return 0;
} // end function: main


问:
how to get firebase database in android studio
in android studio,
i have trouble retrieving the vehicle class in my firebase database. would like to get the data according to date, then plateno. and store each entry in an array. i have tried most solutions found here but as a noob, i have difficulty in condensing the solutions. thanks for your help:
here's my database structure:

here is my code:

```<code>public void getDatabase() {
     FirebaseDatabase myRef = FirebaseDatabase.getInstance();
     DatabaseReference ref = myRef.getReference();
    ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
               for(DataSnapshot onemarker: dataSnapshot.getChildren())
                    {
                        key =onemarker.getKey();
                        myvehicle = onemarker.child(key).child("OneMarker").getValue(Vehicle.class);
                        String stats = myvehicle.status;
                        vehiclearray.add(myvehicle);

                  new AlertDialog.Builder(MonitorActivity.this)
                            .setTitle("Vehicle Information")
                            .setMessage("  "+stats+" "+key+"  "+vehiclearray.size())
                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                }
                            })
                            .setIcon(R.mipmap.inmissionmarker)
                            .setNegativeButton(android.R.string.cancel,null)
                            .show();

                }
            }
</code>```

when ran, the app stopped and closes.
here's the error code:

```<code>12-11 08:49:27.336 1272-1272/? D/Settings: Mon Dec 11 08:49:27 GMT+08:00 2017 , device_provisioned : 1
                                       java.lang.RuntimeException
                                           at android.provider.Settings$LogMsg.writeCallStackLog(Settings.java:1085)
                                           at android.provider.Settings$NameValueCache.putStringForUser(Settings.java:1206)
                                           at android.provider.Settings$Global.putStringForUser(Settings.java:12282)
                                           at android.provider.Settings$Secure.putStringForUser(Settings.java:7421)
                                           at android.provider.Settings$Secure.putIntForUser(Settings.java:7533)
                                           at android.provider.Settings$Secure.putInt(Settings.java:7527)
                                           at com.android.launcher2.Launcher.onCreate(Launcher.java:529)
                                           at android.app.Activity.performCreate(Activity.java:6609)
                                           at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3104)
                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3261)
                                           at android.app.ActivityThread.access$1000(ActivityThread.java:219)
                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1735)
                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                           at android.os.Looper.loop(Looper.java:145)
                                           at android.app.ActivityThread.main(ActivityThread.java:6939)
                                           at java.lang.reflect.Method.invoke(Native Method)
                                           at java.lang.reflect.Method.invoke(Method.java:372)
                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
</code>```

答:
First thing is, you can actually get rid of onemarker. You don't need another key there. It can be directly parsed with the POJO class.

onemarker.getValue(Vehicle.class); //onemarker is the snapshot

Could you please add logs for crash (i.e., app close)

Body:
in android studio,
i have trouble retrieving the vehicle class in my firebase database. would like to get the data according to date, then plateno. and store each entry in an array. i have tried most solutions found here but as a noob, i have difficulty in condensing the solutions. thanks for your help:
here's my database structure:

here is my code:

public void getDatabase() {
     FirebaseDatabase myRef = FirebaseDatabase.getInstance();
     DatabaseReference ref = myRef.getReference();
    ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
               for(DataSnapshot onemarker: dataSnapshot.getChildren())
                    {
                        key =onemarker.getKey();
                        myvehicle = onemarker.child(key).child("OneMarker").getValue(Vehicle.class);
                        String stats = myvehicle.status;
                        vehiclearray.add(myvehicle);

                  new AlertDialog.Builder(MonitorActivity.this)
                            .setTitle("Vehicle Information")
                            .setMessage("  "+stats+" "+key+"  "+vehiclearray.size())
                            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                }
                            })
                            .setIcon(R.mipmap.inmissionmarker)
                            .setNegativeButton(android.R.string.cancel,null)
                            .show();

                }
            }

when ran, the app stopped and closes.
here's the error code:

12-11 08:49:27.336 1272-1272/? D/Settings: Mon Dec 11 08:49:27 GMT+08:00 2017 , device_provisioned : 1
                                       java.lang.RuntimeException
                                           at android.provider.Settings$LogMsg.writeCallStackLog(Settings.java:1085)
                                           at android.provider.Settings$NameValueCache.putStringForUser(Settings.java:1206)
                                           at android.provider.Settings$Global.putStringForUser(Settings.java:12282)
                                           at android.provider.Settings$Secure.putStringForUser(Settings.java:7421)
                                           at android.provider.Settings$Secure.putIntForUser(Settings.java:7533)
                                           at android.provider.Settings$Secure.putInt(Settings.java:7527)
                                           at com.android.launcher2.Launcher.onCreate(Launcher.java:529)
                                           at android.app.Activity.performCreate(Activity.java:6609)
                                           at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3104)
                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3261)
                                           at android.app.ActivityThread.access$1000(ActivityThread.java:219)
                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1735)
                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                           at android.os.Looper.loop(Looper.java:145)
                                           at android.app.ActivityThread.main(ActivityThread.java:6939)
                                           at java.lang.reflect.Method.invoke(Native Method)
                                           at java.lang.reflect.Method.invoke(Method.java:372)
                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)


问:
Laravel getting id from database to download pdf blade
I am using dompdf currently and I encounter this issue where the id returns me pdf instead of the value I want such as 2 or 1 or 3.

Route:

```<code>Route::get('pdfview/{id}',array('as'=>'pdfview','uses'=>'pdfDownloadController@pdfview'));
</code>```

I get the id pdf when I do something like this:

```<code> public function pdfview($id)
    {
        dd($id); --> return id = pdf
    $object = UserInfo::where('id',$id)->get();
    dd($object); --> return empty collection
}

Collection {#395 ▼
  #items: []
}
</code>```

I get the id as null when I do like this:

```<code>    public function pdfview(Request $request)
    {
         $id = UserInfo::find($request->id);
         dd($id);
}
</code>```

test.blade.php (use this link to download the file)

```<code><a href="{{ route('pdfview',['download'=>'pdf']) }}">Download PDF</a>
</code>```

答:
That is the problem in this  tag you have.

test.blade.php (use this link to download the file) 'pdf']) }}">Download PDF

You are passing the string 'pdf' to the route. thats is the same string it returns back to you. you are suppose to pass the actual ID inside your VIEW file. this way it returns an integer that comes from database.

EX:

```<code> <a href="{{url('/pdfview')}}/{{$post->id}}">Download PDF</a>
</code>```

In that example $post->id is the ID of the $post it coming from database, and thats what you need to pass to that route and to be able to fetch more data from database based on that ID.

Hopefully it make sense now.

Body:
I am using dompdf currently and I encounter this issue where the id returns me pdf instead of the value I want such as 2 or 1 or 3.

Route:

Route::get('pdfview/{id}',array('as'=>'pdfview','uses'=>'pdfDownloadController@pdfview'));

I get the id pdf when I do something like this:

 public function pdfview($id)
    {
        dd($id); --> return id = pdf
    $object = UserInfo::where('id',$id)->get();
    dd($object); --> return empty collection
}

Collection {#395 ▼
  #items: []
}

I get the id as null when I do like this:

    public function pdfview(Request $request)
    {
         $id = UserInfo::find($request->id);
         dd($id);
}

test.blade.php (use this link to download the file)

'pdf']) }}">Download PDF

Body:
That is the problem in this  tag you have.

test.blade.php (use this link to download the file) 'pdf']) }}">Download PDF

You are passing the string 'pdf' to the route. thats is the same string it returns back to you. you are suppose to pass the actual ID inside your VIEW file. this way it returns an integer that comes from database.

EX:

 <a href="{{url('/pdfview')}}/{{$post->id}}">Download PDF</a>

In that example $post->id is the ID of the $post it coming from database, and thats what you need to pass to that route and to be able to fetch more data from database based on that ID.

Hopefully it make sense now.


问:
Which option to choose for designing this API endpoint
Let's imagine we have an API endpoint: /cars/1 and this returns basic information about the car (id, name, description).

But we can also request GET /cars/1?info=extra and this will also return extra information about the car (price, stock). And this extra information is stored in our Database as another table, which has a One To One relationship with the Car.

If it helps, our backend is a Java Spring Boot application.

There are many ways to return the data. Would you return same objects in both requests, with the corresponding extra parameters as null in the ?info=extra request? Or would you return different objects for each one of the requests?

For me returning all the nulls when requesting the "basic" info has the advantage of using the same Class to map both requests, by only changing the @Query in the JPA Repository, making it easier to maintain.

Returning all the nulls also has the disadvantage of returning a lot of useless values that the user didn't even requested. It also makes the API more difficult to read (someone can think that all of those values are actually null and they might not). Speaking of classes, we would have a MappedSuperClass Car and two other classes CarBasic and CarExtra, both extending Car, each one of them with the corresponding getters to create the output JSON.

Option 1:

/cars/1

```<code>{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda"
}
</code>```

/cars/1?info=extra

```<code>{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    extraInfo: {
    {
        price: 25000,
        stock: 24
    }
}
</code>```

Option 2:

/cars/1

```<code>{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    extraInfo: null
}
</code>```

/cars/1?info=extra

```<code>{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    extraInfo: {
    {
        price: 25000,
        stock: 24
    }
}
</code>```

Option 3:

/cars/1

```<code>{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda"
}
</code>```

/cars/1?info=extra

```<code>{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    price: 25000,
    stock: 24
}
</code>```

What do you think?

答:
Just consider the frontend, i think the option 1 is better.

But it also needs to be consider the backend, how do you achieve the basic info and the extraInfo.

In addition, i think you can take a look at graphql and graphql-java.Hope it helps.

Body:
Let's imagine we have an API endpoint: /cars/1 and this returns basic information about the car (id, name, description).

But we can also request GET /cars/1?info=extra and this will also return extra information about the car (price, stock). And this extra information is stored in our Database as another table, which has a One To One relationship with the Car.

If it helps, our backend is a Java Spring Boot application.

There are many ways to return the data. Would you return same objects in both requests, with the corresponding extra parameters as null in the ?info=extra request? Or would you return different objects for each one of the requests?

For me returning all the nulls when requesting the "basic" info has the advantage of using the same Class to map both requests, by only changing the @Query in the JPA Repository, making it easier to maintain.

Returning all the nulls also has the disadvantage of returning a lot of useless values that the user didn't even requested. It also makes the API more difficult to read (someone can think that all of those values are actually null and they might not). Speaking of classes, we would have a MappedSuperClass Car and two other classes CarBasic and CarExtra, both extending Car, each one of them with the corresponding getters to create the output JSON.

Option 1:

/cars/1

{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda"
}

/cars/1?info=extra

{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    extraInfo: {
    {
        price: 25000,
        stock: 24
    }
}

Option 2:

/cars/1

{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    extraInfo: null
}

/cars/1?info=extra

{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    extraInfo: {
    {
        price: 25000,
        stock: 24
    }
}

Option 3:

/cars/1

{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda"
}

/cars/1?info=extra

{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    price: 25000,
    stock: 24
}

What do you think?


问:
Regex to extract 3 digit number in an excel function
I need to extract a 3-digit number from text strings in an excel sheet.
I've written my custom function to return a substring based on a pattern, that's fine, it works. It's the pattern that's beating me.
So, examples could include:

Lorem ipsum dolor cc123 sit amet

Lorem ipsum dolor sit amet cc 123

Lorem ipsum c 123, dolor sit amet

I'm no expert in regex, but usually I'd use (?<=\D)\d{3}\b That works with all the tests I've tried but VBA doesn't seem to support (?<=x). Using just \D\d{3}\b and trimming the leading char works, but offends my senses.

I'm using the standard VBscript Regular Expressions 5.5 library.

The practical background to this is that I have a large worksheet that has a comments field on each line. Policy has been that users include their cost centre somewhere in this field. It can appear anywhere in the field, it's always a three-digit number, it is always followed by a word boundary and it is always preceded by a non-number char.

答:
My best guess is to use : \D(\d{3})\b  like in

```<code>Dim myRegExp, ResultString, myMatches, myMatch As Match
Dim myRegExp As RegExp
Set myRegExp = New RegExp
myRegExp.Pattern = "\D(\d{3})\b"
Set myMatches = myRegExp.Execute(SubjectString)
If myMatches.Count >= 1 Then
    Set myMatch = myMatches(0)
    If myMatch.SubMatches.Count >= 1 Then
        ResultString = myMatch.SubMatches(1-1)
    Else
        ResultString = ""
    End If
Else
    ResultString = ""
End If
</code>```

Body:
My best guess is to use : \D(\d{3})\b  like in

Dim myRegExp, ResultString, myMatches, myMatch As Match
Dim myRegExp As RegExp
Set myRegExp = New RegExp
myRegExp.Pattern = "\D(\d{3})\b"
Set myMatches = myRegExp.Execute(SubjectString)
If myMatches.Count >= 1 Then
    Set myMatch = myMatches(0)
    If myMatch.SubMatches.Count >= 1 Then
        ResultString = myMatch.SubMatches(1-1)
    Else
        ResultString = ""
    End If
Else
    ResultString = ""
End If