问:
ORA-28113: policy predicate has error
I need some help with Oracle's VPD feature. I have never used it before but did some research online about it, however I'm running into a problem.

Here are the steps that I have taken:

QuanTriDL:

```<code>create table NhanVien2
</code>```

table NhanVien2

QuanTriVPD:

```<code>CREATE OR REPLACE CONTEXT ThongTinTaiKhoan USING TTTK_PKG;

CREATE OR REPLACE PACKAGE TTTK_PKG IS
PROCEDURE GetTTTK;
END;
/

CREATE OR REPLACE PACKAGE BODY TTTK_PKG IS
PROCEDURE GetTTTK AS
TaiKhoan varchar(30);
tenPhong varchar(30);
tenChucVu varchar(30);
tenMaNV varchar(10);
BEGIN
    TaiKhoan := LOWER(SYS_CONTEXT('USERENV','SESSION_USER'));

    DBMS_SESSION.set_context('ThongTinTaiKhoan','GetTaiKhoan',TaiKhoan);
    if (TaiKhoan = 'nv001') then
        DBMS_SESSION.set_context('ThongTinTaiKhoan','GetChucVu','Giam doc');
    else
    if (TaiKhoan = 'nv002') then
        DBMS_SESSION.set_context('ThongTinTaiKhoan','GetChucVu','Truong phong');
        DBMS_SESSION.set_context('ThongTinTaiKhoan','GetPhong','Kinh doanh');
    else
    if (TaiKhoan = 'nv006') then
        DBMS_SESSION.set_context('ThongTinTaiKhoan','GetChucVu','Truong phong');
        DBMS_SESSION.set_context('ThongTinTaiKhoan','GetPhong','Ky thuat');
    else
        DBMS_SESSION.set_context('ThongTinTaiKhoan','GetChucVu','Nhan vien');
    end if;
    end if;
    end if;
    EXCEPTION
    WHEN NO_DATA_FOUND THEN NULL;
    END GetTTTK;
END;
/

CREATE OR REPLACE TRIGGER RangBuocTTTK AFTER LOGON ON DATABASE
    BEGIN QuanTriVPD.TTTK_PKG.GetTTTK;
        EXCEPTION WHEN NO_DATA_FOUND
        THEN NULL;
    END;
/
</code>```

then:

```<code>CREATE OR REPLACE FUNCTION Select_Nhanvien(
schema_p   IN VARCHAR2,
table_p    IN VARCHAR2)
RETURN VARCHAR2
AS
getChucVu varchar(50);
trave varchar2(1000);
BEGIN
    SELECT SYS_CONTEXT('ThongTinTaiKhoan','GetChucVu') into getChucVu FROM DUAL;
    trave := '1=2';
    if (getChucVu = 'Giam doc')  then
        trave := NULL;
    else
    if (getChucVu = 'Truong phong') then
        trave :='Phong=(SELECT SYS_CONTEXT(''ThongTinTaiKhoan'',''GetPhong'') FROM DUAL)';
    else
        trave :='TenTaiKhoan=(SELECT SYS_CONTEXT(''ThongTinTaiKhoan'',''GetTaiKhoan'') FROM DUAL)';
    end if;
    end if;
    RETURN trave;
END;
/

BEGIN
    DBMS_RLS.ADD_POLICY (
    object_schema    => 'QuanTriDL',
    object_name      => 'NhanVien2',
    policy_name      => 'VPD_Select_Nhanvien',
    function_schema  => 'QuanTriVPD',
    policy_function  => 'Select_Nhanvien',
    statement_types  => 'SELECT');
END;
/
</code>```

When connecting as nv001, nv002, nv006 it's OK. But connecting another user:

ORA-28113: policy predicate has error

Why does it cause that error?

答:
(year old question but since I stumbled across it I'll go ahead and answer it for anyone else...)

ORA-28113 just means that when your policy function returned a where clause, the resulting SQL had some error.  You can get details by looking at the trace file.  Also, try:

```<code>select Select_Nhanvien('myschema','mytable') from dual;
</code>```

And then append the results to a WHERE clause like this:

```<code>SELECT * FROM MYTABLE WHERE <results from above>;
</code>```

And then you should see the root cause.  I'm guessing in the case above the 'other user' didn't have either the sys_context variables required to build the where clause, or access to the login trigger.

As a side note, another problem you can run into here is circular reference when your policy function references its own table - ideally I would expect a policy function to bypass itself within the policy function so you can do NOT EXISTS, etc but it doesn't seem to work that way.

Title: ORA-28113: policy predicate has error

Body:
I need some help with Oracle's VPD feature. I have never used it before but did some research online about it, however I'm running into a problem.

Here are the steps that I have taken:

QuanTriDL:

create table NhanVien2

table NhanVien2

QuanTriVPD:

CREATE OR REPLACE CONTEXT ThongTinTaiKhoan USING TTTK_PKG;

CREATE OR REPLACE PACKAGE TTTK_PKG IS
PROCEDURE GetTTTK;
END;
/

CREATE OR REPLACE PACKAGE BODY TTTK_PKG IS
PROCEDURE GetTTTK AS
TaiKhoan varchar(30);
tenPhong varchar(30);
tenChucVu varchar(30);
tenMaNV varchar(10);
BEGIN
    TaiKhoan := LOWER(SYS_CONTEXT('USERENV','SESSION_USER'));

    DBMS_SESSION.set_context('ThongTinTaiKhoan','GetTaiKhoan',TaiKhoan);
    if (TaiKhoan = 'nv001') then
        DBMS_SESSION.set_context('ThongTinTaiKhoan','GetChucVu','Giam doc');
    else
    if (TaiKhoan = 'nv002') then
        DBMS_SESSION.set_context('ThongTinTaiKhoan','GetChucVu','Truong phong');
        DBMS_SESSION.set_context('ThongTinTaiKhoan','GetPhong','Kinh doanh');
    else
    if (TaiKhoan = 'nv006') then
        DBMS_SESSION.set_context('ThongTinTaiKhoan','GetChucVu','Truong phong');
        DBMS_SESSION.set_context('ThongTinTaiKhoan','GetPhong','Ky thuat');
    else
        DBMS_SESSION.set_context('ThongTinTaiKhoan','GetChucVu','Nhan vien');
    end if;
    end if;
    end if;
    EXCEPTION
    WHEN NO_DATA_FOUND THEN NULL;
    END GetTTTK;
END;
/

CREATE OR REPLACE TRIGGER RangBuocTTTK AFTER LOGON ON DATABASE
    BEGIN QuanTriVPD.TTTK_PKG.GetTTTK;
        EXCEPTION WHEN NO_DATA_FOUND
        THEN NULL;
    END;
/

then:

CREATE OR REPLACE FUNCTION Select_Nhanvien(
schema_p   IN VARCHAR2,
table_p    IN VARCHAR2)
RETURN VARCHAR2
AS
getChucVu varchar(50);
trave varchar2(1000);
BEGIN
    SELECT SYS_CONTEXT('ThongTinTaiKhoan','GetChucVu') into getChucVu FROM DUAL;
    trave := '1=2';
    if (getChucVu = 'Giam doc')  then
        trave := NULL;
    else
    if (getChucVu = 'Truong phong') then
        trave :='Phong=(SELECT SYS_CONTEXT(''ThongTinTaiKhoan'',''GetPhong'') FROM DUAL)';
    else
        trave :='TenTaiKhoan=(SELECT SYS_CONTEXT(''ThongTinTaiKhoan'',''GetTaiKhoan'') FROM DUAL)';
    end if;
    end if;
    RETURN trave;
END;
/

BEGIN
    DBMS_RLS.ADD_POLICY (
    object_schema    => 'QuanTriDL',
    object_name      => 'NhanVien2',
    policy_name      => 'VPD_Select_Nhanvien',
    function_schema  => 'QuanTriVPD',
    policy_function  => 'Select_Nhanvien',
    statement_types  => 'SELECT');
END;
/

When connecting as nv001, nv002, nv006 it's OK. But connecting another user:

ORA-28113: policy predicate has error

Why does it cause that error?

Body:
(year old question but since I stumbled across it I'll go ahead and answer it for anyone else...)

ORA-28113 just means that when your policy function returned a where clause, the resulting SQL had some error.  You can get details by looking at the trace file.  Also, try:

select Select_Nhanvien('myschema','mytable') from dual;

And then append the results to a WHERE clause like this:

SELECT * FROM MYTABLE WHERE <results from above>;

And then you should see the root cause.  I'm guessing in the case above the 'other user' didn't have either the sys_context variables required to build the where clause, or access to the login trigger.

As a side note, another problem you can run into here is circular reference when your policy function references its own table - ideally I would expect a policy function to bypass itself within the policy function so you can do NOT EXISTS, etc but it doesn't seem to work that way.


来源: stackexchange

问:
Error when I use my val in function, but not when I access val on its own in REPL.
I am writing Scala code to search a QuadTree. I'm fairly new to Scala, so this may be a simple question: Why do I get a error: value rec not a member of QuadTree when I try to use tree.rec in a function, BUT if I ask the REPL to evaluate tree.rec, it successfully returns the data?

Anyway, I've got these classes to start with:

```<code>case class Rectangle (minx: Int, maxx: Int, miny: Int, maxy: Int)

abstract class QuadTree
case class Node (value : Int, nw : QuadTree, ne: QuadTree, sw: QuadTree, se: QuadTree, rec: Rectangle) extends QuadTree
case class Leaf (value : Int, rec: Rectangle) extends QuadTree
case class Empty (value: Int, rec: Rectangle) extends QuadTree
</code>```

So I'm defining a Rectangle, and then a QuadTree, which can has a value, and either contains a Node, a Leaf, or Empty.

Next I have a function that checks to see if two rectangles overlap called rectangles_Overlap, which returns True if two input Rectangles overlap, and returns False if there is no overlap.

If I define

```<code>val query = Rectangle(1, 8, 8, 16)
val tree1 = Node(13,Node(12,Leaf(7,Rectangle(1,4,12,16)),Leaf(3,Rectangle(4,8,12,16)),Leaf(2,Rectangle(1,4,8,12)),Empty(0,Rectangle(4,8,8,12)),Rectangle(1,8,8,16)),Empty(0,Rectangle(8,16,8,16)),Empty(0,Rectangle(1,8,1,8)),Leaf(1,Rectangle(8,16,1,8)),Rectangle(1,16,1,16))
</code>```

If I want to get the size of the tree, I can type into the REPL

```<code>scala> tree1.rec
res0: Rectangle = Rectangle(1,16,1,16)
</code>```

I can also use my rectangles_Overlap method to see if the query Rectangle overlaps with the tree Rectangle.

```<code>scala> rectangles_Overlap(query, tree1.rec)
res1: Boolean = true
</code>```

But if I try to use rectangles_Overlap(query, tree1.rec) in another function, its unhappy!

```<code>def queryBoolean(query: Rectangle, tree: QuadTree): Boolean = {
    if(rectangles_Overlap(query, tree.rec)) {
        println("Yay they overlap so I can do other stuff...")
        // I want to add other code here after I get this working
        true
    } else {
        println("Nah, they don't overlap, don't need to do anything")
        false
    }
}
</code>```

And then call the function with queryBoolean(query, tree1), I get this error:

```<code><console>:17: error: value rec is not a member of QuadTree
       if (rectangles_Overlap(query, tree.rec)) {
</code>```

So my question again is: Why can I evaluate tree1.rec in the REPL, but cannot use tree.rec in a function without an error?

My original thought was that perhaps I was overloading something... but rec is always a Rectangle in all of the case clase ... extends QuadTree. So I don't believe I am overloading anything?

答:
This is because rec is not defined for class QuadTree, but only for its subclasses, therefore there is no value to call. The reason that this works properly on REPL is because of the way it is defined. You define it as

```<code>val tree1 = Node(/*some params*/)
</code>```

Which means it has type Node, instead of QuadTree. As Node has a defined rec parameter, everything works out fine. However in the method, you pass in a raw QuadTree, so no rec is defined.

To get it to work, either add rec to the QuadTree class, or pass in a specific subtype, which has the correct parameters defined.

ContentLicense: CC BY-SA 3.0

Body:
I am writing Scala code to search a QuadTree. I'm fairly new to Scala, so this may be a simple question: Why do I get a error: value rec not a member of QuadTree when I try to use tree.rec in a function, BUT if I ask the REPL to evaluate tree.rec, it successfully returns the data?

Anyway, I've got these classes to start with:

case class Rectangle (minx: Int, maxx: Int, miny: Int, maxy: Int)

abstract class QuadTree
case class Node (value : Int, nw : QuadTree, ne: QuadTree, sw: QuadTree, se: QuadTree, rec: Rectangle) extends QuadTree
case class Leaf (value : Int, rec: Rectangle) extends QuadTree
case class Empty (value: Int, rec: Rectangle) extends QuadTree

So I'm defining a Rectangle, and then a QuadTree, which can has a value, and either contains a Node, a Leaf, or Empty.

Next I have a function that checks to see if two rectangles overlap called rectangles_Overlap, which returns True if two input Rectangles overlap, and returns False if there is no overlap.

If I define

val query = Rectangle(1, 8, 8, 16)
val tree1 = Node(13,Node(12,Leaf(7,Rectangle(1,4,12,16)),Leaf(3,Rectangle(4,8,12,16)),Leaf(2,Rectangle(1,4,8,12)),Empty(0,Rectangle(4,8,8,12)),Rectangle(1,8,8,16)),Empty(0,Rectangle(8,16,8,16)),Empty(0,Rectangle(1,8,1,8)),Leaf(1,Rectangle(8,16,1,8)),Rectangle(1,16,1,16))

If I want to get the size of the tree, I can type into the REPL

scala> tree1.rec
res0: Rectangle = Rectangle(1,16,1,16)

I can also use my rectangles_Overlap method to see if the query Rectangle overlaps with the tree Rectangle.

scala> rectangles_Overlap(query, tree1.rec)
res1: Boolean = true

But if I try to use rectangles_Overlap(query, tree1.rec) in another function, its unhappy!

def queryBoolean(query: Rectangle, tree: QuadTree): Boolean = {
    if(rectangles_Overlap(query, tree.rec)) {
        println("Yay they overlap so I can do other stuff...")
        // I want to add other code here after I get this working
        true
    } else {
        println("Nah, they don't overlap, don't need to do anything")
        false
    }
}

And then call the function with queryBoolean(query, tree1), I get this error:

<console>:17: error: value rec is not a member of QuadTree
       if (rectangles_Overlap(query, tree.rec)) {

So my question again is: Why can I evaluate tree1.rec in the REPL, but cannot use tree.rec in a function without an error?

My original thought was that perhaps I was overloading something... but rec is always a Rectangle in all of the case clase ... extends QuadTree. So I don't believe I am overloading anything?

Body:
This is because rec is not defined for class QuadTree, but only for its subclasses, therefore there is no value to call. The reason that this works properly on REPL is because of the way it is defined. You define it as

val tree1 = Node(/*some params*/)

Which means it has type Node, instead of QuadTree. As Node has a defined rec parameter, everything works out fine. However in the method, you pass in a raw QuadTree, so no rec is defined.

To get it to work, either add rec to the QuadTree class, or pass in a specific subtype, which has the correct parameters defined.


问:
Keeping classes loosely coupled and sharing data
I've been working in python on a project where I have a GUI which I split up a bunch of the work between classes. I don't know a lot of the best practices for passing data around between classes, and I've frequently run into the issue, where I have to implement something, or change something for work, and I've resorted to making a lot of the classes objects of another class in order to give it the data I need.

Any ideas or suggests would be greatly appreciated on how to keep my classes independent for later modification and still pass the relevant data around without affecting interfaces too much?

As an example

```<code>class Window():
    def __init__(self, parent=None):
        self.parent = parent
    def doStuff(self):
        #do work here

class ParseMyWork(Window):
    def __init__(self, parent=None):
        self.parent=parent
</code>```

I often find myself doing stuff like the above giving objects to class Window
or simply inheriting everything from them as in ParseMyWork

There must be better and cleaner ways of passing data around without making my classes utterly dependent on eachother, where one little change creates a cascade effect that forces me to make changes in a bunch of other classes.

Any answers to the question don't necessarily have to be in python, but it will be helpful if they are

答:
If I'm understanding your question correctly, I would say that inheritance is not necessary in your case. Why not give ParseMyWork a function for dealing with a specific Window task?

```<code>class Window():
  def __init__(self, parent=None):
    self.parent = parent

  def doStuff(self):
    #do work here

class ParseMyWork():
  def __init__(self, parent=None):
    self.parent=parent`

  def doWindowActivity(self, window):
    window.doStuff
</code>```

Then you can use the function like this

```<code>    work_parser = ParseMyWork()
    window = Window()
    work_parser.doWindowActivity(window);
</code>```

That way you can use your work_parse instance with any window instance.

Apologies in advance for my Python, it's been a while so if you see any rookie mistakes, do point them out.

Body:
I've been working in python on a project where I have a GUI which I split up a bunch of the work between classes. I don't know a lot of the best practices for passing data around between classes, and I've frequently run into the issue, where I have to implement something, or change something for work, and I've resorted to making a lot of the classes objects of another class in order to give it the data I need.

Any ideas or suggests would be greatly appreciated on how to keep my classes independent for later modification and still pass the relevant data around without affecting interfaces too much?

As an example

class Window():
    def __init__(self, parent=None):
        self.parent = parent
    def doStuff(self):
        #do work here

class ParseMyWork(Window):
    def __init__(self, parent=None):
        self.parent=parent

I often find myself doing stuff like the above giving objects to class Window
or simply inheriting everything from them as in ParseMyWork

There must be better and cleaner ways of passing data around without making my classes utterly dependent on eachother, where one little change creates a cascade effect that forces me to make changes in a bunch of other classes.

Any answers to the question don't necessarily have to be in python, but it will be helpful if they are

Body:
If I'm understanding your question correctly, I would say that inheritance is not necessary in your case. Why not give ParseMyWork a function for dealing with a specific Window task?

class Window():
  def __init__(self, parent=None):
    self.parent = parent

  def doStuff(self):
    #do work here

class ParseMyWork():
  def __init__(self, parent=None):
    self.parent=parent`

  def doWindowActivity(self, window):
    window.doStuff

Then you can use the function like this

    work_parser = ParseMyWork()
    window = Window()
    work_parser.doWindowActivity(window);

That way you can use your work_parse instance with any window instance.

Apologies in advance for my Python, it's been a while so if you see any rookie mistakes, do point them out.


问:
Using Picasso to Load Images in List Crashes app on Scroll
I've been using Picasso to populate a listview with URLs that return images. The URLs are returned from a API call.

Adapter

```<code>public class RecipeAdapter extends BaseAdapter implements ListAdapter {

    private final Activity activity;
    private final JSONArray jsonArray;

    public RecipeAdapter (Activity activity, JSONArray jsonArray){
        assert activity !=null;
        assert jsonArray != null;

        this.jsonArray = jsonArray;
        this.activity = activity;

    }

    @Override
    public int getCount(){
        if(null==jsonArray)
            return 0;
        else
            return jsonArray.length();
    }

    @Override
    public JSONObject getItem(int position){
        if(null==jsonArray) return null;
        else
            return jsonArray.optJSONObject(position);
    }

    @Override
    public long getItemId(int position){

        return position;
    }

    @Override
    public View getView (int position, View v, ViewGroup parent){
        if (v == null) {
            v = View.inflate(activity, R.layout.recipe_item, null);
        }

        CircularImageView icon = (CircularImageView)v.findViewById(R.id.recipeIcon);
        TextView title = (TextView) v.findViewById(R.id.recipeTitle);
        TextView supplier = (TextView) v.findViewById(R.id.supplier);

        JSONObject JSdata = getItem(position);
        if(null!=JSdata){
            try {
                if (JSdata.has("title")) {
                    title.setText(JSdata.getString("title"));
                }
                if (JSdata.has("publisher")) {
                    supplier.setText(JSdata.getString("publisher"));
                }
                if (JSdata.has("image_url")) {
                    String image = JSdata.getString("image_url");

                    String[] imagearray = image.split("\\.");
                    String extension = imagearray[imagearray.length - 1];

                    String tag = new String();

                    if (extension.equals("jpg")) {
                        if (URLUtil.isValidUrl(image)) {
                            Picasso.with(activity)
                                    .load(image)
                                    .centerCrop()
                                    .tag(tag)
                                    .error(R.drawable.icon01)
                                    .resize(50, 50)
                                    .into(icon);

                        } else {
                            Picasso.with(activity)
                                    .load(R.drawable.icon01)
                                    .centerCrop()
                                    .resize(50, 50)
                                    .tag(tag)
                                    .into(icon);

                        }

                    }
                }
            } catch (JSONException e) {

                Toast.makeText(activity, "Error finding recipes",
                        Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

        }
       final ImageView fav = (ImageView)v.findViewById(R.id.favbutton);
        fav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fav.setImageResource(R.drawable.ic_favorite_white_24dp);
                Toast.makeText(activity, "Added to favourites",
                        Toast.LENGTH_SHORT).show();
            }
        });

        return v;
    }

}
</code>```

I've done a lot of reading about this, and I've attempted to use the .tag() method and a scroll listener:

```<code>  class Populate extends AsyncTask<String, String, JSONArray> {

    protected void onPreExecute() {
        progress = ProgressDialog.show(RecipeSearch.this, "Finding Recipes", "Searching....", true);
    }

    @Override
    protected JSONArray doInBackground(String... urls) {
        JSONParser recipeParse = new JSONParser();
        String rawJSON = recipeParse.getJSON(urls[0]);

        try {

            if (rawJSON != null) {
                JSONObject object = new JSONObject(rawJSON);
                JSONArray jArray = object.getJSONArray("recipes");
                return jArray;
            } else {
                JSONArray jArray = null;
                return jArray;
            }

        } catch(Exception e) {
            System.out.println(e);
            Toast.makeText(getApplicationContext(), "Error Searching for Recipes",
                    Toast.LENGTH_SHORT).show();

         JSONArray jArray = null;
            return jArray;
        }
        //do http request and add objects to array here.
        //need to do a custom adapter
       // return null;
    }

    @Override
    protected void onPostExecute(JSONArray jArray) {

        if (jArray != null) {
            final ListView recipes = (ListView) findViewById(R.id.recipeView);

            recipes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    JSONObject selected = (JSONObject) (recipes.getItemAtPosition(position));

                    String url = null;
                    try {
                        url = selected.getString("source_url");
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
                    }
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    startActivity(i);

                }
            });
           final String tag ="";
            recipes.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {

                    Picasso picasso = Picasso.with(getApplicationContext());
                    if (scrollState == SCROLL_STATE_IDLE ||
                            scrollState == SCROLL_STATE_TOUCH_SCROLL) {
                        picasso.resumeTag(tag);
                    } else {
                        picasso.pauseTag(tag);
                    }
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                    Picasso picasso = Picasso.with(getApplicationContext());
                    picasso.pauseTag(tag);
                }
            });

            recipeAdapter = new RecipeAdapter(RecipeSearch.this, jArray);//jArray is your json array
            recipes.setAdapter(recipeAdapter);

        } else {
            Toast.makeText(getApplicationContext(), "No Recipes Found", Toast.LENGTH_SHORT).show();
            finish();
        }

        progress.dismiss();
    }
}
</code>```

I though this might solve the problem, but when I scroll on large lists, it causes the app to crash. LogCat:

```<code>   java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
            at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:591)
            at com.pkmmte.view.CircularImageView.refreshBitmapShader(CircularImageView.java:341)
            at com.pkmmte.view.CircularImageView.invalidate(CircularImageView.java:262)
            at android.widget.ImageView.setImageDrawable(ImageView.java:456)
            at com.squareup.picasso.PicassoDrawable.setPlaceholder(PicassoDrawable.java:61)
            at com.squareup.picasso.RequestCreator.into(RequestCreator.java:664)
            at com.squareup.picasso.RequestCreator.into(RequestCreator.java:601)
            at io.moffat.kitchenpal.RecipeAdapter.getView(RecipeAdapter.java:99)
            at android.widget.AbsListView.obtainView(AbsListView.java:2347)
            at android.widget.ListView.makeAndAddView(ListView.java:1864)
            at android.widget.ListView.fillUp(ListView.java:732)
            at android.widget.ListView.fillGap(ListView.java:671)
            at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4991)
            at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3418)
            at android.widget.AbsListView.onTouchMove(AbsListView.java:3801)
            at android.widget.AbsListView.onTouchEvent(AbsListView.java:3632)
            at android.view.View.dispatchTouchEvent(View.java:8471)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2399)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2092)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2369)
            at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1719)
            at android.app.Activity.dispatchTouchEvent(Activity.java:2742)
            at android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:59)
            at android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:59)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2330)
            at android.view.View.dispatchPointerEvent(View.java:8666)
            at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4123)
            at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3989)
            at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
            at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
            at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
            at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3680)
            at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
            at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3737)
            at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
            at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
            at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
            at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
            at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
            at android.view.ViewRootImpl.deliverInputEvent
</code>```

Any help or suggestions would be welcomed

答:
I had the same issue with CircularImageView, image URLs, and Picasso. The
issue lies within CircularImageView being loaded a placeholder image then your requested one. I solved it by using noPlaceholder() in my Picasso query.

You should be able to fix the above code by adding noPlaceholder() like so

```<code>if (URLUtil.isValidUrl(image)) {
    Picasso.with(activity)
        .load(image)
        .centerCrop()
        .tag(tag)
        .error(R.drawable.icon01)
        .resize(50, 50)
        .noPlaceholder()
        .into(icon);

} else {
     Picasso.with(activity)
         .load(R.drawable.icon01)
         .centerCrop()
         .resize(50, 50)
         .tag(tag)
         .noPlaceholder()
         .into(icon);
}
</code>```

The issue is detailed in the Picasso Github https://github.com/square/picasso/issues/931

Body:
I've been using Picasso to populate a listview with URLs that return images. The URLs are returned from a API call.

Adapter

public class RecipeAdapter extends BaseAdapter implements ListAdapter {

    private final Activity activity;
    private final JSONArray jsonArray;

    public RecipeAdapter (Activity activity, JSONArray jsonArray){
        assert activity !=null;
        assert jsonArray != null;

        this.jsonArray = jsonArray;
        this.activity = activity;

    }

    @Override
    public int getCount(){
        if(null==jsonArray)
            return 0;
        else
            return jsonArray.length();
    }

    @Override
    public JSONObject getItem(int position){
        if(null==jsonArray) return null;
        else
            return jsonArray.optJSONObject(position);
    }

    @Override
    public long getItemId(int position){

        return position;
    }

    @Override
    public View getView (int position, View v, ViewGroup parent){
        if (v == null) {
            v = View.inflate(activity, R.layout.recipe_item, null);
        }

        CircularImageView icon = (CircularImageView)v.findViewById(R.id.recipeIcon);
        TextView title = (TextView) v.findViewById(R.id.recipeTitle);
        TextView supplier = (TextView) v.findViewById(R.id.supplier);

        JSONObject JSdata = getItem(position);
        if(null!=JSdata){
            try {
                if (JSdata.has("title")) {
                    title.setText(JSdata.getString("title"));
                }
                if (JSdata.has("publisher")) {
                    supplier.setText(JSdata.getString("publisher"));
                }
                if (JSdata.has("image_url")) {
                    String image = JSdata.getString("image_url");

                    String[] imagearray = image.split("\\.");
                    String extension = imagearray[imagearray.length - 1];

                    String tag = new String();

                    if (extension.equals("jpg")) {
                        if (URLUtil.isValidUrl(image)) {
                            Picasso.with(activity)
                                    .load(image)
                                    .centerCrop()
                                    .tag(tag)
                                    .error(R.drawable.icon01)
                                    .resize(50, 50)
                                    .into(icon);

                        } else {
                            Picasso.with(activity)
                                    .load(R.drawable.icon01)
                                    .centerCrop()
                                    .resize(50, 50)
                                    .tag(tag)
                                    .into(icon);

                        }

                    }
                }
            } catch (JSONException e) {

                Toast.makeText(activity, "Error finding recipes",
                        Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

        }
       final ImageView fav = (ImageView)v.findViewById(R.id.favbutton);
        fav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fav.setImageResource(R.drawable.ic_favorite_white_24dp);
                Toast.makeText(activity, "Added to favourites",
                        Toast.LENGTH_SHORT).show();
            }
        });

        return v;
    }

}

I've done a lot of reading about this, and I've attempted to use the .tag() method and a scroll listener:

  class Populate extends AsyncTask<String, String, JSONArray> {

    protected void onPreExecute() {
        progress = ProgressDialog.show(RecipeSearch.this, "Finding Recipes", "Searching....", true);
    }

    @Override
    protected JSONArray doInBackground(String... urls) {
        JSONParser recipeParse = new JSONParser();
        String rawJSON = recipeParse.getJSON(urls[0]);

        try {

            if (rawJSON != null) {
                JSONObject object = new JSONObject(rawJSON);
                JSONArray jArray = object.getJSONArray("recipes");
                return jArray;
            } else {
                JSONArray jArray = null;
                return jArray;
            }

        } catch(Exception e) {
            System.out.println(e);
            Toast.makeText(getApplicationContext(), "Error Searching for Recipes",
                    Toast.LENGTH_SHORT).show();

         JSONArray jArray = null;
            return jArray;
        }
        //do http request and add objects to array here.
        //need to do a custom adapter
       // return null;
    }

    @Override
    protected void onPostExecute(JSONArray jArray) {

        if (jArray != null) {
            final ListView recipes = (ListView) findViewById(R.id.recipeView);

            recipes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    JSONObject selected = (JSONObject) (recipes.getItemAtPosition(position));

                    String url = null;
                    try {
                        url = selected.getString("source_url");
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
                    }
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    startActivity(i);

                }
            });
           final String tag ="";
            recipes.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {

                    Picasso picasso = Picasso.with(getApplicationContext());
                    if (scrollState == SCROLL_STATE_IDLE ||
                            scrollState == SCROLL_STATE_TOUCH_SCROLL) {
                        picasso.resumeTag(tag);
                    } else {
                        picasso.pauseTag(tag);
                    }
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                    Picasso picasso = Picasso.with(getApplicationContext());
                    picasso.pauseTag(tag);
                }
            });

            recipeAdapter = new RecipeAdapter(RecipeSearch.this, jArray);//jArray is your json array
            recipes.setAdapter(recipeAdapter);

        } else {
            Toast.makeText(getApplicationContext(), "No Recipes Found", Toast.LENGTH_SHORT).show();
            finish();
        }

        progress.dismiss();
    }
}

I though this might solve the problem, but when I scroll on large lists, it causes the app to crash. LogCat:

   java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
            at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:591)
            at com.pkmmte.view.CircularImageView.refreshBitmapShader(CircularImageView.java:341)
            at com.pkmmte.view.CircularImageView.invalidate(CircularImageView.java:262)
            at android.widget.ImageView.setImageDrawable(ImageView.java:456)
            at com.squareup.picasso.PicassoDrawable.setPlaceholder(PicassoDrawable.java:61)
            at com.squareup.picasso.RequestCreator.into(RequestCreator.java:664)
            at com.squareup.picasso.RequestCreator.into(RequestCreator.java:601)
            at io.moffat.kitchenpal.RecipeAdapter.getView(RecipeAdapter.java:99)
            at android.widget.AbsListView.obtainView(AbsListView.java:2347)
            at android.widget.ListView.makeAndAddView(ListView.java:1864)
            at android.widget.ListView.fillUp(ListView.java:732)
            at android.widget.ListView.fillGap(ListView.java:671)
            at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4991)
            at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3418)
            at android.widget.AbsListView.onTouchMove(AbsListView.java:3801)
            at android.widget.AbsListView.onTouchEvent(AbsListView.java:3632)
            at android.view.View.dispatchTouchEvent(View.java:8471)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2399)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2092)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
            at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
            at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2369)
            at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1719)
            at android.app.Activity.dispatchTouchEvent(Activity.java:2742)
            at android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:59)
            at android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:59)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2330)
            at android.view.View.dispatchPointerEvent(View.java:8666)
            at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4123)
            at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3989)
            at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
            at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
            at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
            at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3680)
            at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
            at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3737)
            at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
            at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
            at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
            at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
            at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
            at android.view.ViewRootImpl.deliverInputEvent

Any help or suggestions would be welcomed

Body:
I had the same issue with CircularImageView, image URLs, and Picasso. The
issue lies within CircularImageView being loaded a placeholder image then your requested one. I solved it by using noPlaceholder() in my Picasso query.

You should be able to fix the above code by adding noPlaceholder() like so

if (URLUtil.isValidUrl(image)) {
    Picasso.with(activity)
        .load(image)
        .centerCrop()
        .tag(tag)
        .error(R.drawable.icon01)
        .resize(50, 50)
        .noPlaceholder()
        .into(icon);

} else {
     Picasso.with(activity)
         .load(R.drawable.icon01)
         .centerCrop()
         .resize(50, 50)
         .tag(tag)
         .noPlaceholder()
         .into(icon);
}

The issue is detailed in the Picasso Github https://github.com/square/picasso/issues/931


问:
Getting "PHP Warning: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known"
With a php script like the below, I expected it'd throw an exception and try/catch block will catch it.

```<code><?php
try {
    $dbh = new PDO('mysql:host=does-not-exist;dbname=test;port=3306', 'root', '');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo $e->getMessage(), PHP_EOL;
}
</code>```

But I'm getting a warning error as well. Any workaround?

```<code>PHP Warning:  PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known in /var/www/pdo.php on line 3
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
</code>```

答:
Apparently PHP5.6 throws an exception when instantiating PDO as the document says AND gets a warning error. setAttribute() won't be called anyways.

PHP7.1.5 do not trigger a warning error as expected.

ContentLicense: CC BY-SA 4.0

Body:
With a php script like the below, I expected it'd throw an exception and try/catch block will catch it.

<?php
try {
    $dbh = new PDO('mysql:host=does-not-exist;dbname=test;port=3306', 'root', '');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo $e->getMessage(), PHP_EOL;
}

But I'm getting a warning error as well. Any workaround?

PHP Warning:  PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known in /var/www/pdo.php on line 3
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known


问:
Null Pointer Exception Error message
I cannot seem to find why I am getting this error message. I thought I have already instantiated my array in my main.

Exception in thread "main" java.lang.NullPointerException

```<code>public class A1ArrayList<E> {
    private E[] e;
    private int capacity = 0;

    public A1ArrayList(){
    }

    public int size(){
        return e.length;
    }

    public boolean add(E addElement){
        e[capacity] = addElement;
        capacity = capacity + 1;

        return true;
    }

    public static void main(String[] arg){
        A1ArrayList<Object> e = new A1ArrayList<Object>();
        e.size();

    }
</code>```

答:
You have to initialize your array. Right now you have a field e that has place for an Array of E. But there's no array in that field! So if you try e[capacity] = addElement; you will try to add something to nothing, which is why you'll get a null pointer.

In your constructor you could use this to initialize the array.

```<code>public A1ArrayList(){
    E=new E[5];
}
</code>```

Like that you have an Array where you can store 5 instances of E.

Title: Null Pointer Exception Error message

Body:
I cannot seem to find why I am getting this error message. I thought I have already instantiated my array in my main.

Exception in thread "main" java.lang.NullPointerException

public class A1ArrayList<E> {
    private E[] e;
    private int capacity = 0;

    public A1ArrayList(){
    }

    public int size(){
        return e.length;
    }

    public boolean add(E addElement){
        e[capacity] = addElement;
        capacity = capacity + 1;

        return true;
    }

    public static void main(String[] arg){
        A1ArrayList<Object> e = new A1ArrayList<Object>();
        e.size();

    }

Body:
You have to initialize your array. Right now you have a field e that has place for an Array of E. But there's no array in that field! So if you try e[capacity] = addElement; you will try to add something to nothing, which is why you'll get a null pointer.

In your constructor you could use this to initialize the array.

public A1ArrayList(){
    E=new E[5];
}

Like that you have an Array where you can store 5 instances of E.


问:
hiding elements after a button is clicked - angular2 - ngFor
I am still learning Angular2 and I currently can't find a solution for my problem. I am displaying 1-3 Tiers/Packages using the ngFor, which than looks like this tiers in display mode.
After I click the edit button I only want the clicked element to go into edit mode, currently all of them switch into edit mode, which looks like this tiers in edit mode.

Here is the code, reduced it to the relevant parts.

```<code><h1 class="page-title"><span class="fw-semi-bold">Packages</span></h1>
<div class="row">
  <div class="col-md-4" *ngFor="let tier of tiers; let i=index;">
    <!-- Show Mode -->
    <ul [hidden]="editMode" class="pricing-table">
      <li class="plan-name">
        {{ tier.title }} {{i}}
      </li>
      <li>
        description
      </li>
      <li>
        description
      </li>
      <li>
        description
      </li>
      <li>
        description
      </li>
      <p class="plan-price">{{ tier.price }}</p>
      <li class="plan-action">
        <a class="btn btn-primary" (click)="this.onEdit()">Edit</a>
        <a class="btn btn-success" (click)="this.clickSave()">SaveYes</a>
        <a class="btn btn-warning" >Get</a>
      </li>
    </ul>
    <!-- Edit Mode -->
    <ul [hidden]="!editMode" class="pricing-table-edit">
      <li class="plan-name-edit">
        <input type="text" class="form-control" style=" font-size: 3rem;" placeholder="{{ tier.title }} " formControlName="package_name">

      </li>
      <li >
        <div class="rewards-edit" style="background-color: #3a3d46; ">Feature 1</div>
      </li>
      <li>
        <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
      </li>
      <li>
        <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
      </li>
      <li>
        <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
      </li>
      <div style="align:center; padding-left: 40%; padding-right: 40%;"><input type="text" id="package_price1" class="form-control plan-price" placeholder="4,99" formControlName="package_price"></div>

      <li class="plan-action">
        <a class="btn btn-primary">Edit</a>
        <a class="btn btn-success">Save</a>
        <a class="btn btn-warning">Publish</a>
      </li>
    </ul>
  </div>
</code>```

Components-File:

```<code>export class PackagesComponent {
  editMode = false;

  onEdit () {
    this.editMode = true;
  }
}
</code>```

Is there a way to use the index variable in my method, so that I know which of the 3 tiers is currently clicked? Or are there any other solutions or maybe ideas?

Thanks a lot :)

UPDATED CODE, thanks to Abrar:

```<code>export class PackagesComponent {  //this has to be renamed to TierComponent for less confusion
  public tierToEdit: Tier;
  editMode = false;
  tiers: Tier[] = [
    new Tier(
      10,
      'First Tier',
      [
        {id: 500, title: 'desc', description: 'crazy description'},
        {id: 501, title: 'desc', description: 'crazy description'},
        {id: 502, title: 'desc', description: 'crazy description'},
        {id: 503, title: 'desc', description: 'crazy description'}
      ],
      5.00),
      *[more code..]*
  ]

  constructor (private tierService: TierService) {}

  ngOnInit() {
  }

  onEdit (tier: Tier) {
    this.editMode = true;
    this.tierToEdit = tier;
  }
</code>```

Template-File:

```<code><h1 class="page-title"><span class="fw-semi-bold">Packages</span></h1>
<div class="row">
  <div class="col-md-4" *ngFor="let tier of tiers; let i=index;">
    <!-- Show Mode -->
    <ul *ngIf="!editMode || tierToEdit != tier" class="pricing-table">
      <li class="plan-name">
        {{ tier.title }} {{i}}
      </li>
     <li class="plan-name">
        {{ tier.title }} {{i}}
      </li>
      <li>
        description
      </li>
      <li>
        description
      </li>
      <li>
        description
      </li>
      <li>
        description
      </li>
      <p class="plan-price">{{ tier.price }}</p>
      <li class="plan-action">
        <a class="btn btn-primary" (click)="onEdit(tier)">Edit</a>
        <a class="btn btn-success" (click)="this.clickSave()">SaveYes</a>
        <a class="btn btn-warning" >Get</a>
      </li>
    </ul>
    <!-- Edit Mode -->
    <ul *ngIf="editMode && tierToEdit == tier " class="pricing-table-edit">
      <li class="plan-name-edit">
        <input type="text" class="form-control" style=" font-size: 3rem;" placeholder="{{ tier.title }} " formControlName="package_name">

      </li>
      <li >
        <div class="rewards-edit" style="background-color: #3a3d46; ">Feature 1</div>
      </li>
      <li>
        <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
      </li>
      <li>
        <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
      </li>
      <li>
        <div class="rewards-edit" style="background-color: #3a3d46">Feature 1</div>
      </li>
      <div style="align:center; padding-left: 40%; padding-right: 40%;"><input type="text" id="package_price1" class="form-control plan-price" placeholder="4,99" formControlName="package_price"></div>

      <li class="plan-action">
        <a class="btn btn-primary">Edit</a>
        <a class="btn btn-success">Save</a>
        <a class="btn btn-warning">Publish</a>
      </li>
    </ul>
  </div>
</code>```

答:
What I would do is when you click to edit one of the tiers, pass in the tier into the edit function.

Then set a variable like selectedTier to be set to that tier or id/name of some sort associated with that tier.

Then you can match that selectedTier to the tier in your ngFor.

And then for hiding all but the selected one use [hidden]="selectedTier != tier"

Body:
I am still learning Angular2 and I currently can't find a solution for my problem. I am displaying 1-3 Tiers/Packages using the ngFor, which than looks like this tiers in display mode.
After I click the edit button I only want the clicked element to go into edit mode, currently all of them switch into edit mode, which looks like this tiers in edit mode.

Here is the code, reduced it to the relevant parts.

Packages

        {{ tier.title }} {{i}}

        description

        description

        description

        description

{{ tier.price }}

        Edit
        SaveYes
        Get

        <input type="text" class="form-control" style=" font-size: 3rem;" placeholder="{{ tier.title }} " formControlName="package_name">

Feature 1

Feature 1

Feature 1

Feature 1

<input type="text" id="package_price1" class="form-control plan-price" placeholder="4,99" formControlName="package_price">

        Edit
        Save
        Publish

Components-File:

export class PackagesComponent {
  editMode = false;

  onEdit () {
    this.editMode = true;
  }
}

Is there a way to use the index variable in my method, so that I know which of the 3 tiers is currently clicked? Or are there any other solutions or maybe ideas?

Thanks a lot :)

UPDATED CODE, thanks to Abrar:

export class PackagesComponent {  //this has to be renamed to TierComponent for less confusion
  public tierToEdit: Tier;
  editMode = false;
  tiers: Tier[] = [
    new Tier(
      10,
      'First Tier',
      [
        {id: 500, title: 'desc', description: 'crazy description'},
        {id: 501, title: 'desc', description: 'crazy description'},
        {id: 502, title: 'desc', description: 'crazy description'},
        {id: 503, title: 'desc', description: 'crazy description'}
      ],
      5.00),
      *[more code..]*
  ]

  constructor (private tierService: TierService) {}

  ngOnInit() {
  }

  onEdit (tier: Tier) {
    this.editMode = true;
    this.tierToEdit = tier;
  }

Template-File:

Packages

        {{ tier.title }} {{i}}

        {{ tier.title }} {{i}}

        description

        description

        description

        description

{{ tier.price }}

        Edit
        SaveYes
        Get

        <input type="text" class="form-control" style=" font-size: 3rem;" placeholder="{{ tier.title }} " formControlName="package_name">

Feature 1

Feature 1

Feature 1

Feature 1

<input type="text" id="package_price1" class="form-control plan-price" placeholder="4,99" formControlName="package_price">

        Edit
        Save
        Publish


问:
Rookie Python-questions
Is it possible to make python run on your homepage? I know, this is a really stupid question but please don't pick on me for my stupidity :)

If it is possible, how? Do you have to upload/install the executing part of Python to you website using FTP? or...?

Edit: Just found out my provider does not support python and that shell access is completely restricted. Problem solved :)

答: Python is a scripting language, though it is used gracefully for building back end web applications.</p>

ContentLicense: CC BY-SA 2.5

Title: Rookie Python-questions


问:
Different Android app version in different countries
I have an app that needs to be approved by certain regulatory agencies in different countries before it can be released.  I don't see a way to pick when an update goes live to a particular country on the Play Store.  Is this possible?

So for example, let's say I have Foo 1.0 on the Play Store now.  I want to release Foo 1.1 in the USA, but delay it in Canada for a year because I have to get it approved by their regulatory agency first.  Is there a way to do that without having a "Foo USA" and a "Foo Canada" as separate apps?

答:
You could create multiple google play store entries, restrict them by country. That would require creating different apps that would use the same code and only differ in package name and singing keys that would come from flavours config.

But that would have con of having multiple store entries, which effectively be separate apps.


问:
Parse an XML as fast as possible
I have a VB.Net app that reads a zip file that has an XML file in it.  I need to parse the XML file into row segments, pull one node value out as the application id and send it on it's way to a MS SQL database.  The XML file looks like:

```<code><?xml version="1.0" encoding="UTF-8"?>
<PROJECTS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
<APPLICATION_ID>9243987</APPLICATION_ID>
<ACTIVITY>P30</ACTIVITY>
<ADMINISTERING_IC>AR</ADMINISTERING_IC>
<APPLICATION_TYPE>5</APPLICATION_TYPE>
<ARRA_FUNDED>N</ARRA_FUNDED>
<AWARD_NOTICE_DATE>05/22/2017</AWARD_NOTICE_DATE>
<BUDGET_START>04/01/2017</BUDGET_START>
</row>
<row>
<APPLICATION_ID>9243988</APPLICATION_ID>
<ACTIVITY>P30</ACTIVITY>
<ADMINISTERING_IC>AR</ADMINISTERING_IC>
<APPLICATION_TYPE>5</APPLICATION_TYPE>
<ARRA_FUNDED>N</ARRA_FUNDED>
<AWARD_NOTICE_DATE>05/22/2017</AWARD_NOTICE_DATE>
<BUDGET_START>04/01/2017</BUDGET_START>
</row>
<row>
<APPLICATION_ID>9243989</APPLICATION_ID>
<ACTIVITY>P30</ACTIVITY>
<ADMINISTERING_IC>AR</ADMINISTERING_IC>
<APPLICATION_TYPE>5</APPLICATION_TYPE>
<ARRA_FUNDED>N</ARRA_FUNDED>
<AWARD_NOTICE_DATE>05/22/2017</AWARD_NOTICE_DATE>
<BUDGET_START>04/01/2017</BUDGET_START>
</row>
</PROJECTS>
</code>```

The file could contain a million records and be close to 100mg in size.  My current code isbelow and could take as long as 8 hours to run for a million records.

My VB code that parses the file is:

```<code>            If ofdXML.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
            stopWatch.Start()
            Dim result As String
            Dim fName As String = ofdXML.FileName
            If fName.EndsWith("zip") Then
                Dim ePath As String = "E:\Downloads\WEEKLY"
                fileName = ExtractArchive(fName, ePath)
                fName = Path.Combine(ePath, fileName)
            End If

            result = Path.GetFileNameWithoutExtension(fName)
            Dim rdr As New StreamReader(fName)
            While (rdr.Peek >= 0)
                varLine = rdr.ReadLine
                sTag = varLine.Contains("<row>")
                eTag = varLine.Contains("</row>")
                If sTag And eTag Then
                    appLine = varLine
                    If appLine.Contains("<row><APPLICATION_ID>") Then
                        appID = appLine.Substring(Len("<row><APPLICATION_ID>"), appLine.IndexOf("/APPLICATION_ID") - Len("<row><APPLICATION_ID>") - 1)
                    End If
                ElseIf sTag Then
                    v1 = True
                    appLine = varLine
                    If appLine.Contains("<row><APPLICATION_ID>") Then
                        appID = appLine.Substring(Len("<row><APPLICATION_ID>"), appLine.IndexOf("/APPLICATION_ID") - Len("<row><APPLICATION_ID>") - 1)
                    End If
                ElseIf eTag Then
                    appLine = appLine & varLine
                    v1 = False
                ElseIf v1 Then
                    appLine = appLine & varLine
                    If appLine.Contains("<APPLICATION_ID>") Then
                        Dim xi As Integer = appLine.IndexOf("_ID>") + 4
                        appID = appLine.Substring(xi, appLine.IndexOf("/APPLICATION_ID") - (xi + 1))
                    End If
                End If

                If Trim(Len(varLine)) > 0 And appLine.Contains("<row>") And appLine.Contains("</row") And Not varLine.Contains("</PROJECTS>") Then
                    TextBox2.Text = i.ToString
                    TextBox3.Text = appID
                    sb.Append(appID + ",")
                    Application.DoEvents()
                    i += 1
                    ADMIN_Save_To_Database(appLine, appID, result)
                End If
            End While

        End If
</code>```

Any help is greatly appreciated.

答:
I've change the code to:

```<code>            Dim rdr As New StreamReader(fName)
            Dim xml As New XmlDocument()
            xml.Load(rdr)
            Dim DocumentNodes As XmlNodeList =
            xml.GetElementsByTagName("row")
            For Each xn As XmlNode In DocumentNodes
                Dim example As XmlNode =
             xn.SelectSingleNode("APPLICATION_ID")
                If example IsNot Nothing Then
                    Dim applicationID As String = example.InnerText
                    ADMIN_Save_AuthoringNames(xn.InnerXml, applicationID, result)
                End If
            Next
</code>```

I'll let you know how it runs

Title: Parse an XML as fast as possible

Body:
I have a VB.Net app that reads a zip file that has an XML file in it.  I need to parse the XML file into row segments, pull one node value out as the application id and send it on it's way to a MS SQL database.  The XML file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<PROJECTS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
<APPLICATION_ID>9243987</APPLICATION_ID>
<ACTIVITY>P30</ACTIVITY>
<ADMINISTERING_IC>AR</ADMINISTERING_IC>
<APPLICATION_TYPE>5</APPLICATION_TYPE>
<ARRA_FUNDED>N</ARRA_FUNDED>
<AWARD_NOTICE_DATE>05/22/2017</AWARD_NOTICE_DATE>
<BUDGET_START>04/01/2017</BUDGET_START>
</row>
<row>
<APPLICATION_ID>9243988</APPLICATION_ID>
<ACTIVITY>P30</ACTIVITY>
<ADMINISTERING_IC>AR</ADMINISTERING_IC>
<APPLICATION_TYPE>5</APPLICATION_TYPE>
<ARRA_FUNDED>N</ARRA_FUNDED>
<AWARD_NOTICE_DATE>05/22/2017</AWARD_NOTICE_DATE>
<BUDGET_START>04/01/2017</BUDGET_START>
</row>
<row>
<APPLICATION_ID>9243989</APPLICATION_ID>
<ACTIVITY>P30</ACTIVITY>
<ADMINISTERING_IC>AR</ADMINISTERING_IC>
<APPLICATION_TYPE>5</APPLICATION_TYPE>
<ARRA_FUNDED>N</ARRA_FUNDED>
<AWARD_NOTICE_DATE>05/22/2017</AWARD_NOTICE_DATE>
<BUDGET_START>04/01/2017</BUDGET_START>
</row>
</PROJECTS>

The file could contain a million records and be close to 100mg in size.  My current code isbelow and could take as long as 8 hours to run for a million records.

My VB code that parses the file is:

            If ofdXML.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
            stopWatch.Start()
            Dim result As String
            Dim fName As String = ofdXML.FileName
            If fName.EndsWith("zip") Then
                Dim ePath As String = "E:\Downloads\WEEKLY"
                fileName = ExtractArchive(fName, ePath)
                fName = Path.Combine(ePath, fileName)
            End If

            result = Path.GetFileNameWithoutExtension(fName)
            Dim rdr As New StreamReader(fName)
            While (rdr.Peek >= 0)
                varLine = rdr.ReadLine
                sTag = varLine.Contains("<row>")
                eTag = varLine.Contains("</row>")
                If sTag And eTag Then
                    appLine = varLine
                    If appLine.Contains("<row><APPLICATION_ID>") Then
                        appID = appLine.Substring(Len("<row><APPLICATION_ID>"), appLine.IndexOf("/APPLICATION_ID") - Len("<row><APPLICATION_ID>") - 1)
                    End If
                ElseIf sTag Then
                    v1 = True
                    appLine = varLine
                    If appLine.Contains("<row><APPLICATION_ID>") Then
                        appID = appLine.Substring(Len("<row><APPLICATION_ID>"), appLine.IndexOf("/APPLICATION_ID") - Len("<row><APPLICATION_ID>") - 1)
                    End If
                ElseIf eTag Then
                    appLine = appLine & varLine
                    v1 = False
                ElseIf v1 Then
                    appLine = appLine & varLine
                    If appLine.Contains("<APPLICATION_ID>") Then
                        Dim xi As Integer = appLine.IndexOf("_ID>") + 4
                        appID = appLine.Substring(xi, appLine.IndexOf("/APPLICATION_ID") - (xi + 1))
                    End If
                End If

                If Trim(Len(varLine)) > 0 And appLine.Contains("<row>") And appLine.Contains("</row") And Not varLine.Contains("</PROJECTS>") Then
                    TextBox2.Text = i.ToString
                    TextBox3.Text = appID
                    sb.Append(appID + ",")
                    Application.DoEvents()
                    i += 1
                    ADMIN_Save_To_Database(appLine, appID, result)
                End If
            End While

        End If

Any help is greatly appreciated.

Body:
I've change the code to:

            Dim rdr As New StreamReader(fName)
            Dim xml As New XmlDocument()
            xml.Load(rdr)
            Dim DocumentNodes As XmlNodeList =
            xml.GetElementsByTagName("row")
            For Each xn As XmlNode In DocumentNodes
                Dim example As XmlNode =
             xn.SelectSingleNode("APPLICATION_ID")
                If example IsNot Nothing Then
                    Dim applicationID As String = example.InnerText
                    ADMIN_Save_AuthoringNames(xn.InnerXml, applicationID, result)
                End If
            Next

I'll let you know how it runs


问:
Why does clicking a link rendered by WP PHP with target="_blank" open in new tab and current tab?
So I know this kind of question has been asked in here, but mine appears to be different from others.

The code below shows that if there is a URL populate it and open it in a new tab, however, for some strange reason the link opens in a new tab (YAY!!) AND opens in the current tab (BOO!!). Why is it opening in both the new tab and the current tab?

I just checked in an incognito window and it happens there also so it doesn't appear to be a cookie issue either.

```<code><div class="box span4">
    <?php if( $url1 != '' && $img1 != '' ): ?>
        <a href="<?php echo esc_url( $url1 ); ?>" target="_blank" class="box-link">
            <center><img class="box-image" src="<?php echo esc_url( $img1 ); ?>"/></center>
        </a>
    <?php else: ?>
        <?php if( $img1 != '' ): ?>
            <a class="box-no-url">
                <center><img class="box-image" src="<?php echo esc_url( $img1 ); ?>"/></center>
            </a>
        <?php endif; ?>
    <?php endif; ?>
    <p><?php echo wp_kses( $text1, array( 'br' => array(), 'em' => array(), 'strong' => array() ) ); ?></p>
</div>
</code>```

To see this code in action please visit http://www.tayloredhomeinspection.com/ and scroll down to the image with the InterNACHI seal in the middle gray box and click on it (or the text below it).

答:
The cause

There is a script tag in the header section of the HTML:

```<code><script type="text/javascript" src="http://www.tayloredhomeinspection.com/wp-content/themes/parallax1/elements/lib/js/elements.min.js?ver=4.7.5"></script>
</code>```

Inside that file is the following block (un-minified, thanks to jsbeautifier.org):

```<code>jQuery(".boxes .box").each(function() {
    var e = jQuery(this).children(".box-link").attr("href");
    jQuery(this).hover(function() {
        if (e && e != "") jQuery(this).css("cursor", "pointer")
    }, function() {
        jQuery(this).css("cursor", "default")
    });
    jQuery(this).click(function() {
        if (e && e != "") window.location = e
    })
});
</code>```

That code is looking for elements (child elements of elements with class boxes and box, respectively) with class box-link and when any of those elements is clicked on, it changes the location of the current tab (by assigning a value to window.location) to the value at the href attribute of the element (with class box-link).

That link (that contains the InterNACHI seal) has class box-link and matches those CSS selectors:

```<code><div class="boxes">
        <!-- removed first box -->

        <div class="box span4" style="cursor: default; height: 460px;">
            <a href="http://www.nachi.org/" target="_blank" class="box-link">
                <center><img class="box-image" src="./Taylored Home Inspection 719.602.6287_files/internachi_red_gold.png"></center>
            </a>
</code>```

It appears that this allows the user to click anywhere in the parent container (with class="box"), for instance - on the paragraph below the link, and still have the effect of clicking on the link. See the differences between the link and paragraph illustrated in the screenshot below:

Prevention

One quick solution would be to remove that class name (i.e. box-link) from that element. However that remove desired styling...  Beyond that, one might need to modify the (wordpress) JavaScript to stop changing the location if the anchor tag has a target and it was the target of the event.

Update:

If no help is found from the CyberChimp Parallax Word Press theme documentation and/or support, an alteration script could be run after the page has loaded. The code below could be added to any javascript file run after the other javascript files (including elements.min.js)), or inline in a script tag (i.e. ).

One could argue though that this is just a hack to cover up functionality and might suffer if the implementation in the theme code changes.

```<code>jQuery(".boxes .box").each(function() {
    var e = jQuery(this).children(".box-link").attr("href");
    var target = jQuery(this).children(".box-link").attr('target');
    if (target == '_blank') {
      jQuery(this).off('click');
    }
    jQuery(this).click(function(event) {
      if (e && e != "") {
          if (target == '_blank') {
              window.open( e, '_blank');
          }
          else {
              window.location = e;
          }
      }
    });
  });
</code>```

See a demonstration in this jsbin example

Body:
So I know this kind of question has been asked in here, but mine appears to be different from others.

The code below shows that if there is a URL populate it and open it in a new tab, however, for some strange reason the link opens in a new tab (YAY!!) AND opens in the current tab (BOO!!). Why is it opening in both the new tab and the current tab?

I just checked in an incognito window and it happens there also so it doesn't appear to be a cookie issue either.

    <?php if( $url1 != '' && $img1 != '' ): ?>
        <a href="<?php echo esc_url( $url1 ); ?>" target="_blank" class="box-link">
            <img class="box-image" src="<?php echo esc_url( $img1 ); ?>"/>

    <?php else: ?>
        <?php if( $img1 != '' ): ?>

                <img class="box-image" src="<?php echo esc_url( $img1 ); ?>"/>

        <?php endif; ?>
    <?php endif; ?>

<?php echo wp_kses( $text1, array( 'br' => array(), 'em' => array(), 'strong' => array() ) ); ?>

To see this code in action please visit http://www.tayloredhomeinspection.com/ and scroll down to the image with the InterNACHI seal in the middle gray box and click on it (or the text below it).

Body:
The cause

There is a script tag in the header section of the HTML:

<script type="text/javascript" src="http://www.tayloredhomeinspection.com/wp-content/themes/parallax1/elements/lib/js/elements.min.js?ver=4.7.5"></script>

Inside that file is the following block (un-minified, thanks to jsbeautifier.org):

jQuery(".boxes .box").each(function() {
    var e = jQuery(this).children(".box-link").attr("href");
    jQuery(this).hover(function() {
        if (e && e != "") jQuery(this).css("cursor", "pointer")
    }, function() {
        jQuery(this).css("cursor", "default")
    });
    jQuery(this).click(function() {
        if (e && e != "") window.location = e
    })
});

That code is looking for elements (child elements of elements with class boxes and box, respectively) with class box-link and when any of those elements is clicked on, it changes the location of the current tab (by assigning a value to window.location) to the value at the href attribute of the element (with class box-link).

That link (that contains the InterNACHI seal) has class box-link and matches those CSS selectors:

<div class="boxes">
        <!-- removed first box -->

        <div class="box span4" style="cursor: default; height: 460px;">
            <a href="http://www.nachi.org/" target="_blank" class="box-link">
                <center><img class="box-image" src="./Taylored Home Inspection 719.602.6287_files/internachi_red_gold.png"></center>
            </a>

It appears that this allows the user to click anywhere in the parent container (with class="box"), for instance - on the paragraph below the link, and still have the effect of clicking on the link. See the differences between the link and paragraph illustrated in the screenshot below:

Prevention

One quick solution would be to remove that class name (i.e. box-link) from that element. However that remove desired styling...  Beyond that, one might need to modify the (wordpress) JavaScript to stop changing the location if the anchor tag has a target and it was the target of the event.

Update:

If no help is found from the CyberChimp Parallax Word Press theme documentation and/or support, an alteration script could be run after the page has loaded. The code below could be added to any javascript file run after the other javascript files (including elements.min.js)), or inline in a script tag (i.e. <script type="text/javascript">jQuery(".boxes .box" ...</script>).

One could argue though that this is just a hack to cover up functionality and might suffer if the implementation in the theme code changes.

jQuery(".boxes .box").each(function() {
    var e = jQuery(this).children(".box-link").attr("href");
    var target = jQuery(this).children(".box-link").attr('target');
    if (target == '_blank') {
      jQuery(this).off('click');
    }
    jQuery(this).click(function(event) {
      if (e && e != "") {
          if (target == '_blank') {
              window.open( e, '_blank');
          }
          else {
              window.location = e;
          }
      }
    });
  });

See a demonstration in this jsbin example


问:
Send NEWNYM to TOR with Java?
anyone knows how i can send the NEWNYM signal to TOR through java code?

Say I have this:

```<code>        String adress = "http://some-adress";
        WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52);
        ProxyConfig proxyConfig = new ProxyConfig("127.0.0.1", 9150, true);
        webClient.getOptions().setProxyConfig(proxyConfig);

        webClient.getOptions().setJavaScriptEnabled(false);
        webClient.getOptions().setUseInsecureSSL(true);
        HtmlPage page = (HtmlPage)webClient.getPage(adress);
</code>```

And technically i can do this to restart the application, and get a new identity:

```<code>        Runtime.getRuntime().exec("C:/Users/user/Desktop/Tor Browser/Browser/firefox.exe");

        Runtime.getRuntime().exec("TASKKILL /F /IM firefox.exe");
</code>```

But there must be a way to send the NEWNYM signal, because to get a new identity with TOR this way is quite messy.

Can anyone help me out?

答:
HtmlUnit uses Apache HttpClient to connect to the server.

And according to this answer, you can do it by directly calling:

```<code>public static void torNewIP() throws Exception {
   Socket socket = new Socket();
   socket.connect(new InetSocketAddress(TOR_IP, TOR_CONTROL_PORT));
   socket.getOutputStream().write(new String("SIGNAL NEWNYM\r\n").getBytes());
   socket.close();
}
</code>```

After enabling 'TOR_CONTROL_PORT'

Title: Send NEWNYM to TOR with Java?

Body:
anyone knows how i can send the NEWNYM signal to TOR through java code?

Say I have this:

        String adress = "http://some-adress";
        WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52);
        ProxyConfig proxyConfig = new ProxyConfig("127.0.0.1", 9150, true);
        webClient.getOptions().setProxyConfig(proxyConfig);

        webClient.getOptions().setJavaScriptEnabled(false);
        webClient.getOptions().setUseInsecureSSL(true);
        HtmlPage page = (HtmlPage)webClient.getPage(adress);

And technically i can do this to restart the application, and get a new identity:

        Runtime.getRuntime().exec("C:/Users/user/Desktop/Tor Browser/Browser/firefox.exe");

        Runtime.getRuntime().exec("TASKKILL /F /IM firefox.exe");

But there must be a way to send the NEWNYM signal, because to get a new identity with TOR this way is quite messy.

Can anyone help me out?

Body:
HtmlUnit uses Apache HttpClient to connect to the server.

And according to this answer, you can do it by directly calling:

public static void torNewIP() throws Exception {
   Socket socket = new Socket();
   socket.connect(new InetSocketAddress(TOR_IP, TOR_CONTROL_PORT));
   socket.getOutputStream().write(new String("SIGNAL NEWNYM\r\n").getBytes());
   socket.close();
}

After enabling 'TOR_CONTROL_PORT'


问:
error code : 5007
I followed this tut http://active.tutsplus.com/tutorials/actionscript/as3-101-oop-introduction-basix/ when testing I got

5007: An ActionScript file must have
  at least one externally visible
  definition

WHEREAS I DO HAVE A PUBLIC CLASS

```<code>package {
    import flash.display.MovieClip;
    import flash.text.TextField;
    public class DocumentClass extends MovieClip {
        public function DocumentClass() {
            var tf:TextField = new TextField();
            addChild(tf);
            tf.text = "Hello World";
        }
    }
}
</code>```

答:
Are you saving it as DocumentClass.as? The Class name, Constructor and AS file all need to have exactly the same name.

Other than that, hmm. It's possible that you have another DocumentClass.as somewhere within the same source path of your .fla, and this one is formed incorrectly? Have you created multiple files in the course of your experimentation with this tutorial?

Title: error code : 5007

Body:
I followed this tut http://active.tutsplus.com/tutorials/actionscript/as3-101-oop-introduction-basix/ when testing I got

5007: An ActionScript file must have
  at least one externally visible
  definition

WHEREAS I DO HAVE A PUBLIC CLASS

package {
    import flash.display.MovieClip;
    import flash.text.TextField;
    public class DocumentClass extends MovieClip {
        public function DocumentClass() {
            var tf:TextField = new TextField();
            addChild(tf);
            tf.text = "Hello World";
        }
    }
}


问:
VSCode code autocomplete behavior
I noticed that VSCode uses only the files that are opened in editors (tabs) for looking up names for code auto complete. It is strange for me. To my mind the more usual behavior is to look up all files in opened folder, but not use only the opened files. Is this behavior by design ?</p>

答: Actually, to consider the opened folder as JS project, the "jsconfig.json" is required. Read more here</p>

Title: VSCode code autocomplete behavior


问:
Electron NPM install-app-deps electron-gyp (boilerplate hell)
As there are so many layers involved, I'm a bit lost in how to resolve the following (on linux) ...

Today I started to encounter failures with npm i involving electron apps. The initial error was to the tune of

```<code>"EISDIR: illegal operation on a directory, read" on `~./electron-gyp`.
</code>```

Researching this indicates this is an attempt to read a directory (which it is) as a file. I thought it might be an npm issue as I upgraded it recently and so I reinstalled node/npm and removed all remnants including all electron folders, npm & nodejs. I thought a clean reinstall might be the best approach . . .

Reinstalled and configured all those, including moving global npm node_modules under the user account to remove any permission issues.

So far so good, however, the previous error now changes to

```<code>"ENOENT: no such file or directory, open '/home/joe/.electron-gyp'"
</code>```

which is understandable as I removed this folder. I am unsure as to what electron or npm module should create and populate this folder.

Continued searching seems to be that the issue is associated in some manner with a call to install-app-deps from electron-builder but I can't seem to get that to work. I thought I'd ask for a little guidance here before I start to ask in that repo for assistance as I'm not positive the cause is there.

Creating the directory in advance to see the outcome results in:

```<code>[3] Error: /usr/bin/node exited with code 235
[3] Error output:
[3] npm ERR! addLocal Could not install /home/joe/.electron-gyp
[3] npm ERR! code EISDIR
[3] npm ERR! errno -21
[3] npm ERR! syscall read
[3] npm ERR! eisdir EISDIR: illegal operation on a directory, read
[3] npm ERR! eisdir This is most likely not a problem with npm itself
[3] npm ERR! eisdir and is related to npm not being able to find a package.json in
[3] npm ERR! eisdir a package you are trying to install.
</code>```

... which is sort of back to the start

Any help is greatly appreciated.

UPDATE1: Problem seems to be confirmed as stemming from npm and involving electron-builder. Issue ticket filed.

答: Confirmed as a bug and resolved at source.</p>

Body:
As there are so many layers involved, I'm a bit lost in how to resolve the following (on linux) ...

Today I started to encounter failures with npm i involving electron apps. The initial error was to the tune of

"EISDIR: illegal operation on a directory, read" on `~./electron-gyp`.

Researching this indicates this is an attempt to read a directory (which it is) as a file. I thought it might be an npm issue as I upgraded it recently and so I reinstalled node/npm and removed all remnants including all electron folders, npm & nodejs. I thought a clean reinstall might be the best approach . . .

Reinstalled and configured all those, including moving global npm node_modules under the user account to remove any permission issues.

So far so good, however, the previous error now changes to

"ENOENT: no such file or directory, open '/home/joe/.electron-gyp'"

which is understandable as I removed this folder. I am unsure as to what electron or npm module should create and populate this folder.

Continued searching seems to be that the issue is associated in some manner with a call to install-app-deps from electron-builder but I can't seem to get that to work. I thought I'd ask for a little guidance here before I start to ask in that repo for assistance as I'm not positive the cause is there.

Creating the directory in advance to see the outcome results in:

[3] Error: /usr/bin/node exited with code 235
[3] Error output:
[3] npm ERR! addLocal Could not install /home/joe/.electron-gyp
[3] npm ERR! code EISDIR
[3] npm ERR! errno -21
[3] npm ERR! syscall read
[3] npm ERR! eisdir EISDIR: illegal operation on a directory, read
[3] npm ERR! eisdir This is most likely not a problem with npm itself
[3] npm ERR! eisdir and is related to npm not being able to find a package.json in
[3] npm ERR! eisdir a package you are trying to install.

... which is sort of back to the start

Any help is greatly appreciated.

UPDATE1: Problem seems to be confirmed as stemming from npm and involving electron-builder. Issue ticket filed.


问:
what is Vec4i in opencv
i am learning opencv using c++. i came across Vector in a code for hough line transform . can anyone explain me what does Vec4i store and what does 4i mean.
the code snippet:-</p>

```<code>vector<Vec4i> lines;
  HoughLinesP(dst, lines, 1, CV_PI/180, 50, 50, 10 );
  for( size_t i = 0; i < lines.size(); i++ )
  {
    Vec4i l = lines[i];
    line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);
  }
</code>```

答:
Have a look at the OpenCV Basic Structures.
Vec4i is a structure for representing a vector with 4 dimensions, with each value an int

If you look at the HoughLinesP() documentation you'll see what each dimension in is in this particular case:

lines – Output vector of lines. Each line is represented by a 4-element vector  (x_1, y_1, x_2, y_2) , where  (x_1,y_1) and  (x_2, y_2) are the ending points of each detected line segment.

In short, each line is a Vec4i, the first two elements are the line's start point (x1,y1) and last two are the line's end point(x2,y2)

Title: what is Vec4i in opencv

Body:
i am learning opencv using c++. i came across Vector in a code for hough line transform . can anyone explain me what does Vec4i store and what does 4i mean.
the code snippet:-

vector<Vec4i> lines;
  HoughLinesP(dst, lines, 1, CV_PI/180, 50, 50, 10 );
  for( size_t i = 0; i < lines.size(); i++ )
  {
    Vec4i l = lines[i];
    line( cdst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0,0,255), 3, CV_AA);
  }


问:
Kotlin Renaming Generated Getters and Setters
Is there a way to rename the default getters and setters in Kotlin? I have a property named in snake_case, but I still want the getters and setters to be named in camelCase.

The closest I've gotten is something like

```<code>private var property_name = Color.BLACK
private set
fun setPropertyName(c: Color) { property_name = c }
fun getPropertyName() = property_name
</code>```

Is there a way to do this without hiding the getters and setters and defining new methods?

答:
It is described in the section on handling signature clashes: https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#handling-signature-clashes-with-jvmname

```<code>val x: Int
    @JvmName("getX_prop")
    get() = 15
</code>```

So @JvmName("getPropertyName") get should work.

Body:
Is there a way to rename the default getters and setters in Kotlin? I have a property named in snake_case, but I still want the getters and setters to be named in camelCase.

The closest I've gotten is something like

private var property_name = Color.BLACK
private set
fun setPropertyName(c: Color) { property_name = c }
fun getPropertyName() = property_name

Is there a way to do this without hiding the getters and setters and defining new methods?

Body:
It is described in the section on handling signature clashes: https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#handling-signature-clashes-with-jvmname

val x: Int
    @JvmName("getX_prop")
    get() = 15

So @JvmName("getPropertyName") get should work.


问:
cURL error 7: Failed to connect to api.keen.io port 443: Connection timed out
Our API code recently started failing to push events to one of our two Keen IO projects.

We are using identical code in each case except with different API keys. I even tried to regenerate the keys without any luck.

The error thrown by Guzzle which is called from the PHP keen-io/keen-io libraries is:

There was an error executing the addEvent command: cURL error 7: Failed to connect to api.keen.io port 443: Connection timed out (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

答:
This ended up being a network routing issue. The server that was failing could not make requests to other APIs either, nor could the Linux OS even perform software updates which require a connection to external package repositories. It turns out when we moved to the new building, somehow the same IP address got assigned to two servers, which was somehow creating outbound request issues. Once that was resolved this issue went away.

(The only other reason writes would fail to one Keen IO project but not another is if the project was blocked for some reason. But, in that case, the API would return a 429 or other more descriptive error, not a 443.)


问:
foreach loop on multidimensional array
how could I make a nice search result like google
I cannot wrap my head around this many. thanks for any help you can give.

```<code>Array
(
    [summary] => Array
        (
            [what] => pizza
            [where] => city
        )

    [listings] => Array
        (
            [0] => Array
                (
                    [parent] =>
                    [contents] => Array
                        (
                            [Video] => Array
                                (
                                    [avail] =>
                                )
                        )

                    [id] => 1114638
                    [name] => Sexy house
                    [address] => Array
                        (
                            [street] => 3 King St E
                            [city] => loversLane
                            [prov] => AB
                            [pcode] => L8N1A1
                        )

                    [geoCoded] => Array
                        (
                            [latitude] => 43.256373
                            [longitude] => -79.868167
                        )

                )

        )

)

this works good at printing:

        function recursivePrint($elem) {
   foreach ($elem as $key => $value) {
      if (is_array($value))
         $this->recursivePrint($value);
      else
         print $value.'<br>';
   }
}
</code>```

But I want to be able to place links over the results etc. have the geocode as variables so I can use maps. Just as much control with as little lines as possible.

答:
The HTML you choose to wrap round each one is up to you, but this should make it obvious how you use arrays in PHP:</p>

```<code>echo 'Results for '.$elem['summary']['what'].' '.$elem['summary']['where'].'<br />';

foreach($elem['listings'] as $listing)
{
 echo $listing['name'].'<br />';
 echo $listing['address']['street'].'<br />';
 echo $listing['address']['city'].'<br />';
 echo '<a href="http://maps.google.com/maps?hl=en&tab=wl&q='.$listing['geoCoded']['latitude'].','.$listing['geoCoded']['longitude'].'" title="View location on a map">'.$listing['address']['pcode'].'</a>';
 echo '<br /><br />';
}
</code>```

Title: foreach loop on multidimensional array

Body:
how could I make a nice search result like google
I cannot wrap my head around this many. thanks for any help you can give.

Array
(
    [summary] => Array
        (
            [what] => pizza
            [where] => city
        )

    [listings] => Array
        (
            [0] => Array
                (
                    [parent] =>
                    [contents] => Array
                        (
                            [Video] => Array
                                (
                                    [avail] =>
                                )
                        )

                    [id] => 1114638
                    [name] => Sexy house
                    [address] => Array
                        (
                            [street] => 3 King St E
                            [city] => loversLane
                            [prov] => AB
                            [pcode] => L8N1A1
                        )

                    [geoCoded] => Array
                        (
                            [latitude] => 43.256373
                            [longitude] => -79.868167
                        )

                )

        )

)

this works good at printing:

        function recursivePrint($elem) {
   foreach ($elem as $key => $value) {
      if (is_array($value))
         $this->recursivePrint($value);
      else
         print $value.'
';
   }
}

But I want to be able to place links over the results etc. have the geocode as variables so I can use maps. Just as much control with as little lines as possible.

Body:
The HTML you choose to wrap round each one is up to you, but this should make it obvious how you use arrays in PHP:

echo 'Results for '.$elem['summary']['what'].' '.$elem['summary']['where'].'<br />';

foreach($elem['listings'] as $listing)
{
 echo $listing['name'].'<br />';
 echo $listing['address']['street'].'<br />';
 echo $listing['address']['city'].'<br />';
 echo '<a href="http://maps.google.com/maps?hl=en&tab=wl&q='.$listing['geoCoded']['latitude'].','.$listing['geoCoded']['longitude'].'" title="View location on a map">'.$listing['address']['pcode'].'</a>';
 echo '<br /><br />';
}


问:
Using google Place picker in android project

I am trying to learn Google's place picker

I have used the sample project from here

I have linked playservices library for the sample project

Resolved all the dependencies

Problem:

Some depedencies r not resolved ther are,

```<code>import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
</code>```

Question:

How to solve this

Should I need to add any other project references

答:
Answering because I had te same problem.

I needed to add 'com.google.android.gms:play-services-places to my project.

in the app's build.gradle I added

```<code>dependencies {
    ...
    compile 'com.google.android.gms:play-services-places:10.2.6'
}
</code>```

Body:
I am trying to learn Google's place picker

I have used the sample project from here

I have linked playservices library for the sample project

Resolved all the dependencies

Problem:

Some depedencies r not resolved ther are,

import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;

Question:

How to solve this

Should I need to add any other project references

Body:
Answering because I had te same problem.

I needed to add 'com.google.android.gms:play-services-places to my project.

in the app's build.gradle I added

dependencies {
    ...
    compile 'com.google.android.gms:play-services-places:10.2.6'
}


问:
Confused between Jahia and dotcms as a java CMS
Which is better for web content management purposed only?
The website requirements include a user discussion forum and a poll survey with a good search facility and also needs a good SEO tool. The site should also load faster and should be easy to edit contents.</p>

答: I have not worked with Dotcms, but basic forums, polls, search, and SEO are all freely available as Jahia modules.  The forums are certainly not as good as a standalone like Vanilla, but they are simple to add and administrate.  Search is good and requires little configuration, and anything more than basic SEO is going to be custom work.</p>


问:
Javascript setInterval: first interval is abrupt
When using JavaScript's setInterval method in the example below with jQuery effects, the initial display does not appear to engage the fadeIn method. "text" is displayed suddenly.

Subsequent iterations through the chain of effects starting with fadeIn() execute as expected. It is just the first pass where the "text" is displayed suddenly without the fadeIn effect.

Any ideas as to why this occurs?
Thanks - a JavaScript beginner.

```<code>setInterval(myFunction, 1000);
function myFunction() {
    $('#myId').fadeIn(1500).html("text").delay(2750).fadeOut(1500).delay(1000;
};
</code>```

答:
It could be Fading In without you noticing as the text is added after the fade In. Switch it around, add the text before fading it in.
Make sure it was not displayed beforehand (in CSS or however you need it).</p>

```<code>$('#myId').html("text").fadeIn(1500).delay(2750).fadeOut(1500).delay(1000);
</code>```

Body:
When using JavaScript's setInterval method in the example below with jQuery effects, the initial display does not appear to engage the fadeIn method. "text" is displayed suddenly.

Subsequent iterations through the chain of effects starting with fadeIn() execute as expected. It is just the first pass where the "text" is displayed suddenly without the fadeIn effect.

Any ideas as to why this occurs?
Thanks - a JavaScript beginner.

setInterval(myFunction, 1000);
function myFunction() {
    $('#myId').fadeIn(1500).html("text").delay(2750).fadeOut(1500).delay(1000;
};

Body:
It could be Fading In without you noticing as the text is added after the fade In. Switch it around, add the text before fading it in.
Make sure it was not displayed beforehand (in CSS or however you need it).

$('#myId').html("text").fadeIn(1500).delay(2750).fadeOut(1500).delay(1000);


问:
Automatically subset data frame by factor
Looking for help writing a function to automatically subset data frames based on the value of a column? For example,

df$x contains values a, b, c, d

I want to make separate data frames named a, b, c, d that contain all values x == 'a', or x == 'b', etc. I know several methods to do this manually but am hoping for guidance on how to automate this? Thank you!

答:
maybe not the best way to do it, but will get the job done.</p>

```<code>vars_df = unique(df$x)

for (i in 1:length(vars_df)) {
assign(paste0(vars_df[i]), df %>% filter(x == vars_df[i]), envir = .GlobalEnv)
}
</code>```

Body:
maybe not the best way to do it, but will get the job done.

vars_df = unique(df$x)

for (i in 1:length(vars_df)) {
assign(paste0(vars_df[i]), df %>% filter(x == vars_df[i]), envir = .GlobalEnv)
}


问:
Doing a secure ajax call over proxy creates new Session ID. How can I work around that?
I am working on a Zendesk app. It will allow end-users to integrate my own service in their Zendesk environment.

As they need to authenticate with my service, I decided to allow users to enter a token in the app's settings in Zendesk. This token won't be visible to all their agents using the app as it allows me to use {{setting.token}} in the code.

Now I am doing an ajax call (with secure:true) to authenticate the user and set $_SESSION['userid']. As I do not want to leak the token, the ajax call uses a proxy by Zendesk where the actual token is then added to the call.

So far so good! But since the proxy was used, the SessionID in login.php (url of ajax call) is different to the other pages. Hence $_SESSION['userid'] can not be accessed on the other pages.

My first work-around idea was the following:

I added another custom-header the call, handing over the sessionID to login.php and setting it there before resuming the session.

This somehow works, but only when loading the page twice. When deleting the cookie and loading the page for the first time again, it does not work. Refreshing it then works again.

Can I get my workaround to work properly for the first time someone opens the page too?

Or should I approach this differently?

Thanks guys!

答:
Same issue as me?

Simply refresh the page after the ajax call response. Now the session variables will be available.