问:
Delete data from datatable via AJAX call
I have a view where I have AJAX call

Here is code of AJAX request, it's just hit method on back end:

```<code><script>
// deleting
$("#send").click(
    function sender() {
        $.ajax({
            contentType: 'application/json; charset=utf-8',
            type: 'Post',
            dataType: 'json',
            processData: false,
            url: '@Url.Action("DeleteAll", "Questions")',
            success: function(da) {
                if (da.Result === "Success") {

                    alert("Data deleted!");

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function(da) {
                alert('Error');
            }
        });
    });
</code>```

And method on back end

```<code>public ActionResult DeleteAll()
{
    ApplicationDbContext context =  new ApplicationDbContext();
    List<InvitationMail> query = context.InvitationMails.ToList();
    foreach (InvitationMail q in query)
    {
        context.DeleteObject(q);
    }
    context.SaveChanges();
    return Json(new {Result = "Success", Message = "Saved Successfully"});
}
</code>```

But I have this error

I need to delete all data from  InvitationMail table, how I can do this?

答:
The DbContext doesn't include a DeleteObject() method but you can use the Remove() method. Something like this:

```<code>foreach (InvitationMail q in query)
{
    context.InvitationMails.Remove(q);
}

context.SaveChanges();
</code>```

Body:
The DbContext doesn't include a DeleteObject() method but you can use the Remove() method. Something like this:

foreach (InvitationMail q in query)
{
    context.InvitationMails.Remove(q);
}

context.SaveChanges();


来源: stackexchange

问:
Using spinner in android fragment view and button click
I am a newbie programmer in android.I am trying to develop a simple paternity blood test.The logic is like this.I have three spinners and blood group A,B,AB and O will be listed into the spinner.The user have to chose blood type from A,B,AB or O for child,mother and father and then click submit button.The button will do some matching and produce a string result.I have tried several methods whichI found on internet. But still unable to use button click function.
Here is my code.Plz correct my mistake .Thanks.

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn_paternity"
            android:layout_centerHorizontal="true"
            android:gravity="center_horizontal"
            android:layout_marginTop="52dp"
            android:id="@+id/paternity_ans" />

        <TextView
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:id="@+id/textView6"
            android:text="Father"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:layout_width="100dp"
            android:layout_above="@+id/childblds"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_marginTop="53dp"
            android:id="@+id/textView5"
            android:text="Child "
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"

            android:layout_width="100dp"
            android:layout_marginRight="15dp"
            android:layout_marginEnd="15dp"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@+id/btn_paternity"
            android:layout_toStartOf="@+id/btn_paternity" />

        <Spinner
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:spinnerMode="dialog"
            android:id="@+id/dadblds"
            android:dropDownWidth="match_parent"
            android:layout_toLeftOf="@+id/textView4"
            android:layout_toStartOf="@+id/textView4"
            android:layout_alignBottom="@+id/childblds"
            android:layout_alignTop="@+id/childblds" />

        <Spinner
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/childblds"
            android:spinnerMode="dialog"

            android:dropDownWidth="match_parent"
            android:layout_marginTop="13dp"

            android:layout_below="@+id/textView5"
            android:layout_alignLeft="@+id/textView5"
            android:layout_alignStart="@+id/textView5" />

        <Spinner
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/momblds"
            android:spinnerMode="dialog"
            android:entries="@array/paternitybldtype"
            android:dropDownWidth="match_parent"
            android:layout_alignTop="@+id/dadblds"
            android:layout_alignLeft="@+id/textView4"
            android:layout_alignStart="@+id/textView4" />

        <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn_paternity"
            android:layout_below="@+id/dadblds"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="35dp" />

        <TextView
            android:layout_height="wrap_content"
            android:id="@+id/textView4"
            android:gravity="center_horizontal"

            android:text="Mother"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:layout_width="100dp"
            android:layout_marginLeft="9dp"
            android:layout_marginStart="9dp"
            android:layout_above="@+id/childblds"
            android:layout_toRightOf="@+id/textView6"
            android:layout_toEndOf="@+id/textView6" />
    </RelativeLayout>
</LinearLayout>
</code>```

Fragments code:

```<code>public class Paternitytest extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.paternitytestlo, container, false);
        final Button setItem = (Button) view.findViewById(R.id.btn_paternity);
        final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);

        setItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Some if else statement will be applied here by using String c, f and m
            }
        });

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
        Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
        Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);

        // Spinner Drop down elements
        String[] categories = {"A", "B", "O", "AB",};

        // Creating adapter for spinner
        ArrayAdapter adapter = new ArrayAdapter(
                getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);

        // Drop down layout style - list view with radio button
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        childspinner.setAdapter(adapter);
        dadspinner.setAdapter(adapter);
        momspinner.setAdapter(adapter);

        // Spinner click listener
        childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                String c = parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {

                String f = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                String m = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}
</code>```

答:
I have made some changes in your code so try this.</p>

```<code>public class Paternitytest extends Fragment {

    private String childSpinnerString, momSpinnerString, dadspinnerString;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.paternitytestlo,
                container, false);

        final Button setItem = (Button) view.findViewById(R.id.btn_paternity);

        final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);

        setItem.setOnClickListener(new View.OnClickListener()
        {
                @Override
                public void onClick(View view)
                {

                    //Some if else statement will be applied here by using String c, f and m

                    Log.d("Blood groups- ", "Child - " + childSpinnerString + " Mom - " + momSpinnerString + " Dad - " + dadspinnerString);

                }
         });

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
        Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
        Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);

        // Spinner Drop down elements
        String[] categories = {"A", "B", "O", "AB",};

        // Creating adapter for spinner
        ArrayAdapter adapter = new ArrayAdapter(
                    getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);

        // Drop down layout style - list view with radio button
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        childspinner.setAdapter(adapter);
        dadspinner.setAdapter(adapter);
        momspinner.setAdapter(adapter);

        // Spinner click listener
        childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                childSpinnerString = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {

               dadspinnerString = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
              momSpinnerString  = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am a newbie programmer in android.I am trying to develop a simple paternity blood test.The logic is like this.I have three spinners and blood group A,B,AB and O will be listed into the spinner.The user have to chose blood type from A,B,AB or O for child,mother and father and then click submit button.The button will do some matching and produce a string result.I have tried several methods whichI found on internet. But still unable to use button click function.
Here is my code.Plz correct my mistake .Thanks.

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:text="TextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn_paternity"
            android:layout_centerHorizontal="true"
            android:gravity="center_horizontal"
            android:layout_marginTop="52dp"
            android:id="@+id/paternity_ans" />

        <TextView
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:id="@+id/textView6"
            android:text="Father"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:layout_width="100dp"
            android:layout_above="@+id/childblds"
            android:layout_centerHorizontal="true" />

        <TextView
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_marginTop="53dp"
            android:id="@+id/textView5"
            android:text="Child "
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"

            android:layout_width="100dp"
            android:layout_marginRight="15dp"
            android:layout_marginEnd="15dp"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@+id/btn_paternity"
            android:layout_toStartOf="@+id/btn_paternity" />

        <Spinner
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:spinnerMode="dialog"
            android:id="@+id/dadblds"
            android:dropDownWidth="match_parent"
            android:layout_toLeftOf="@+id/textView4"
            android:layout_toStartOf="@+id/textView4"
            android:layout_alignBottom="@+id/childblds"
            android:layout_alignTop="@+id/childblds" />

        <Spinner
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/childblds"
            android:spinnerMode="dialog"

            android:dropDownWidth="match_parent"
            android:layout_marginTop="13dp"

            android:layout_below="@+id/textView5"
            android:layout_alignLeft="@+id/textView5"
            android:layout_alignStart="@+id/textView5" />

        <Spinner
            android:layout_width="100dp"
            android:layout_height="wrap_content"
            android:id="@+id/momblds"
            android:spinnerMode="dialog"
            android:entries="@array/paternitybldtype"
            android:dropDownWidth="match_parent"
            android:layout_alignTop="@+id/dadblds"
            android:layout_alignLeft="@+id/textView4"
            android:layout_alignStart="@+id/textView4" />

        <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn_paternity"
            android:layout_below="@+id/dadblds"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="35dp" />

        <TextView
            android:layout_height="wrap_content"
            android:id="@+id/textView4"
            android:gravity="center_horizontal"

            android:text="Mother"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:layout_width="100dp"
            android:layout_marginLeft="9dp"
            android:layout_marginStart="9dp"
            android:layout_above="@+id/childblds"
            android:layout_toRightOf="@+id/textView6"
            android:layout_toEndOf="@+id/textView6" />
    </RelativeLayout>
</LinearLayout>

Fragments code:

public class Paternitytest extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.paternitytestlo, container, false);
        final Button setItem = (Button) view.findViewById(R.id.btn_paternity);
        final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);

        setItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Some if else statement will be applied here by using String c, f and m
            }
        });

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
        Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
        Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);

        // Spinner Drop down elements
        String[] categories = {"A", "B", "O", "AB",};

        // Creating adapter for spinner
        ArrayAdapter adapter = new ArrayAdapter(
                getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);

        // Drop down layout style - list view with radio button
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        childspinner.setAdapter(adapter);
        dadspinner.setAdapter(adapter);
        momspinner.setAdapter(adapter);

        // Spinner click listener
        childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                String c = parent.getItemAtPosition(position).toString();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {

                String f = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                String m = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}

Body:
I have made some changes in your code so try this.

public class Paternitytest extends Fragment {

    private String childSpinnerString, momSpinnerString, dadspinnerString;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.paternitytestlo,
                container, false);

        final Button setItem = (Button) view.findViewById(R.id.btn_paternity);

        final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);

        setItem.setOnClickListener(new View.OnClickListener()
        {
                @Override
                public void onClick(View view)
                {

                    //Some if else statement will be applied here by using String c, f and m

                    Log.d("Blood groups- ", "Child - " + childSpinnerString + " Mom - " + momSpinnerString + " Dad - " + dadspinnerString);

                }
         });

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
        Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
        Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);

        // Spinner Drop down elements
        String[] categories = {"A", "B", "O", "AB",};

        // Creating adapter for spinner
        ArrayAdapter adapter = new ArrayAdapter(
                    getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);

        // Drop down layout style - list view with radio button
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        childspinner.setAdapter(adapter);
        dadspinner.setAdapter(adapter);
        momspinner.setAdapter(adapter);

        // Spinner click listener
        childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                childSpinnerString = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {

               dadspinnerString = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
              momSpinnerString  = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }
}


问:
Check for errors doing string to float conversion, when 0.00 is an accepted value
I am currently looking for the most elegant way, to do error-checking on a string to float conversion, when 0.00 shall be an accepted value, but non-numeric characters shall lead to a bailout.
Currently I am thinking of testing the string for any other chars than ","/"." or "[0-9]". I`d just like to know, if there is a more elegant/shorter way.
Thanks in advance, Oliver !</p>

答:
PHP has a built in function for this.

is_float()

Examples:

is_float(27.25); // This would be true

is_float('abc'); // This would be false


问:
Could not find module 'tns-core-modules/globals'
I am new to Native Script. Trying to create Hello World application using below link

http://docs.nativescript.org/angular/tutorial/ng-chapter-1

build success but run failed error code below

I have tried in 2-3 system same result, please help

答: Upgrade to latest versions of TNS and Angular to be compatible with the Sample Application.</p>


问:
making exe form HTML and Javascript
I was wondering I have PHP based server side stuff that accepts ajax requests and sends back JSON for JS. And I have HTML and JS based "client" now I would like to create exe(windows aplication) that would look the same as the "client" in browser but without browser. Preferably somehow grab that HTML and JS and "compile it" to regural client that would still send out AJAX calls and procesing JSON data.

Edit:
To clarify things:
Server(on webserver) is PHP procesing incoming AJAX calls and diplaing JSON as result.

Client(what I want to convertt to exe) is HTML and JS(Jquery) page(application).

I want for user to have option two to dowload client for windows so he/she dont have to use browser.

答: With https://electron.atom.io/ from Github you can develop Windows, Mac and Linux applications with Javascript, Html and CSS. You can also build mobile application with your web development skills. https://cordova.apache.org/.</p>

Title: making exe form HTML and Javascript


问:
Is it possible to replace parentheses with $?
I have the following function:

```<code>digits :: Int -> [Int]
digits n = go n []
    where go num acc
            | num < 10 = num : acc
            | otherwise = go (div num 10) (mod num 10 : acc)
</code>```

Is it possible to replace the parentheses in the otherwise expression with $?

答:
In addition to the answers @Centril mentions, you can replace only the second pair:

```<code>go (div num 10) $ mod num 10 : acc
</code>```

or both, but then you need parentheses in a different place:

```<code>(go $ div num 10) $ mod num 10 : acc
</code>```

or declare another operator like $ but left-associative:

```<code>f $$ x = f x
infixl 0 $$

go $$ div num 10 $$ mod num 10 : acc
</code>```

Body:
I have the following function:

digits :: Int -> [Int]
digits n = go n []
    where go num acc
            | num < 10 = num : acc
            | otherwise = go (div num 10) (mod num 10 : acc)

Is it possible to replace the parentheses in the otherwise expression with $?

Body:
In addition to the answers @Centril mentions, you can replace only the second pair:

go (div num 10) $ mod num 10 : acc

or both, but then you need parentheses in a different place:

(go $ div num 10) $ mod num 10 : acc

or declare another operator like $ but left-associative:

f $$ x = f x
infixl 0 $$

go $$ div num 10 $$ mod num 10 : acc


问:
make bigger space for legend in echarts
I'm using echarts

this is my chart

this picture shows I lost some of my legends , so,how do I make bigger space for legends, is it possible to set more space for legends? or if it is possible to make my chart smaller how can I do?

答:
I put

```<code>var option = {
    grid: {
        y: 30,
        y2: 90,
    },
</code>```

y mean space before chart, y2 - after chart

Title: make bigger space for legend in echarts

Body:
I put

var option = {
    grid: {
        y: 30,
        y2: 90,
    },

y mean space before chart, y2 - after chart


问:
Appending more than two child elements to an element gives a strange behaviour
I have a very strange behaviour and I don't know what causes it.

I loop through all of the id's which javascript can find within my html page. Every time when the 'id' startsWith a specific label, it goes into my if statement.

Within this if-statement I am creating several elements such as P,H1 and HR. Within my 'html'-page I've got 3 unique id's which are DIV's and should go into the if statement. This worked well(picture left [ 1]), until...

I tried to append more than two child elements to those DIV elements. The first two DIV elements are extended as expected. The last one has not been extended though. At the moment that there are more than two elements added to the parent, the 3th DIV (standardArticle3) does not pass the if statement. (picture right [2])

Hopefully the code and scenario picture can make this story clearer:

home.component.ts

```<code>var allElements = document.getElementsByTagName("*");
console.log(allElements);
for (var i = 0, n = allElements.length; i < n; ++i) {
  var el = allElements[i];
  var foundElementId = el.id;
  console.log(foundElementId);
  if (foundElementId.startsWith("standardArticle"))
  {
    var standardArticleElement = this.jsonReaderService.getStandardArticleContent(foundElementId.substring(15, foundElementId.length));

    var titleElement = document.createElement("h1");
    var titleText = document.createTextNode(standardArticleElement.title);
    titleElement.appendChild(titleText);

    var contentElement = document.createElement("p");
    contentElement.innerHTML = standardArticleElement.content;

    var thematicBreak = document.createElement("hr");
    thematicBreak.style.borderTopColor = "black";

    var thematicBreakTwo = document.createElement("hr");
    thematicBreakTwo.style.borderTopColor = "black";

    // Child elements are all being appended the right way, but the last DIV will never be extended
    el.appendChild(titleElement);
    el.appendChild(thematicBreak);
    el.appendChild(contentElement);
    el.appendChild(thematicBreakTwo);
  }
}
</code>```

home.component.html

```<code>    // other content
    <div id="standardArticle1" class="col-sm-6">
    </div>
    // other content
    <div id="standardArticle2" class="col-sm-6 pull-right">
    </div>
    // other content
    <div id="standardArticle3" class="col-sm-6">
    </div>
</code>```

Scenario's 1 and 2.

Does anybody have an idea why this is happening?

答:
I think I know what your problem is. Let's see what happens when you loop over all the elements on the page: for (var i = 0, n = allElements.length; i < n; ++i)

If there are 10 elements on the page, then n is set to 10. But then as you reach your if statement and add elements, n is still equal to 10 but you now have additional elements on the page. It looks like Mikael Lennholm said those more concisely and provided a good solution.

Body:
I have a very strange behaviour and I don't know what causes it.

I loop through all of the id's which javascript can find within my html page. Every time when the 'id' startsWith a specific label, it goes into my if statement.

Within this if-statement I am creating several elements such as P,H1 and HR. Within my 'html'-page I've got 3 unique id's which are DIV's and should go into the if statement. This worked well(picture left [ 1]), until...

I tried to append more than two child elements to those DIV elements. The first two DIV elements are extended as expected. The last one has not been extended though. At the moment that there are more than two elements added to the parent, the 3th DIV (standardArticle3) does not pass the if statement. (picture right [2])

Hopefully the code and scenario picture can make this story clearer:

home.component.ts

var allElements = document.getElementsByTagName("*");
console.log(allElements);
for (var i = 0, n = allElements.length; i < n; ++i) {
  var el = allElements[i];
  var foundElementId = el.id;
  console.log(foundElementId);
  if (foundElementId.startsWith("standardArticle"))
  {
    var standardArticleElement = this.jsonReaderService.getStandardArticleContent(foundElementId.substring(15, foundElementId.length));

    var titleElement = document.createElement("h1");
    var titleText = document.createTextNode(standardArticleElement.title);
    titleElement.appendChild(titleText);

    var contentElement = document.createElement("p");
    contentElement.innerHTML = standardArticleElement.content;

    var thematicBreak = document.createElement("hr");
    thematicBreak.style.borderTopColor = "black";

    var thematicBreakTwo = document.createElement("hr");
    thematicBreakTwo.style.borderTopColor = "black";

    // Child elements are all being appended the right way, but the last DIV will never be extended
    el.appendChild(titleElement);
    el.appendChild(thematicBreak);
    el.appendChild(contentElement);
    el.appendChild(thematicBreakTwo);
  }
}

home.component.html

    // other content

    // other content

    // other content

Scenario's 1 and 2.

Does anybody have an idea why this is happening?


答:
I think you're looking for is_numeric()
http://php.net/manual/en/function.is-numeric.php

```<code>$x = 5.345;
$y = '0.00';
$z = 'abc123';

echo is_numeric($x)."1\n";
echo is_numeric($y)."2\n";
echo is_numeric($z)."3\n";
</code>```

See it working here https://3v4l.org/sEvqC

Title: Check for errors doing string to float conversion, when 0.00 is an accepted value

Body:
I am currently looking for the most elegant way, to do error-checking on a string to float conversion, when 0.00 shall be an accepted value, but non-numeric characters shall lead to a bailout.
Currently I am thinking of testing the string for any other chars than ","/"." or "[0-9]". I`d just like to know, if there is a more elegant/shorter way.
Thanks in advance, Oliver !

Body:
I think you're looking for is_numeric()
http://php.net/manual/en/function.is-numeric.php

$x = 5.345;
$y = '0.00';
$z = 'abc123';

echo is_numeric($x)."1\n";
echo is_numeric($y)."2\n";
echo is_numeric($z)."3\n";

See it working here https://3v4l.org/sEvqC


问:
KendoUI grid edit popup, how to hide field
Is there a way to hide a field in edit popup that should still be visible in the grid itself?

I have tried setting it to hidden:true, but kendo seems to ignore it.
When editable is set to false, it hides the textbox but field label is still shown. Is it possible to get rid of both label and textbox?

My datasource:

```<code>schema: {
    total: "Total",
    data: "Data",
    model:{
        id:"Id",
        fields:{
            Id:{ visible: false, editable:false },
            Name:{ editable:true },
            NumberOfUsers:{ hidden:true, editable:false }
        }
    }
}
</code>```

答:
Answer is here:
Kendo-ui MVC PopUp editor: How to hide fields
and here:
http://www.telerik.com/forums/editing-grid-via-popup-mode-hide-fields</p>

Body:
Is there a way to hide a field in edit popup that should still be visible in the grid itself?

I have tried setting it to hidden:true, but kendo seems to ignore it.
When editable is set to false, it hides the textbox but field label is still shown. Is it possible to get rid of both label and textbox?

My datasource:

schema: {
    total: "Total",
    data: "Data",
    model:{
        id:"Id",
        fields:{
            Id:{ visible: false, editable:false },
            Name:{ editable:true },
            NumberOfUsers:{ hidden:true, editable:false }
        }
    }
}


问:
QPX Express API: Why Ryanair is missing?
is there a specific reason why Ryanair is missing from the QPX Express API results while it appears in a normal search on Google Flight?
Thanks

Max

答:
I noticed that the QPX API and Ita Software Matrix (by Google) gives the same results, not including a lot of companies like Ryanair.

I asked Google Support about it.

The answer is:

"QPX Express API and Matrix only include fares that are filed with ATPCO.  There are a number of small carriers and low cost carriers that do not file."

Asking Google if they consider to add these flights to their APIs the answer was:

"Airlines determine which distribution channel they want to participate in.  If any of these airlines were to file with ATPCO, then we would certainly be interested."


问:
C# Service Client - Transfer-Encoding: Chunked
I'm currently trying to fix my SOAP-Client in C#, but got somehow stuck with the Transfer-Encoding. I'm more or less a newbie to C#, so it's completly possible that im just missing something minor here.

I consumed a SOAP service from our local Tomcat Server following this: https://web.archive.org/web/20180506023052/http://www.csharptutorial.in/37/csharp-net-how-to-consume-a-web-service-in-csharp-net-visual-studio-2010

My current code:

```<code>using System;
using ConsoleApp1.Lims;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            LimsZugriffService client = new LimsZugriffService();
           // FunktionsErgebnis response = client.connect();
           // Console.WriteLine("Connect" + response.meldung);
            String[] bond = new String[] { "versuch.auftrag.nr=2014/0031" };
            String[] bondFail = new String[] { "abc" };
            VersuchsschrittErgebnis reponseVersuch = client.ermittleVersuchsschritte(bond);
            Console.WriteLine(reponseVersuch.ermittelteVersuchsschritte.Length);
            Console.WriteLine(reponseVersuch.meldung);

        }
    }
}
</code>```

After some testing I found out, that something does not work as intended. My Response-Array of <ermittelteVersuchsschritte> seems to be empty, while the "control"-Flags are parsed normally.

I captured the traffic between client and server to figure out what was wrong and it was actually completly there. Just chunked into 8192 Byte blocks.

Could it be, that the C# implementation of the WebClient got some problems with Transfer-Encoding: Chunked?

After googling for some hours i could not find a satisfiying solution to this issue. I hope somebody, who knows C# and WebServices better than me has the answer.

For the sake of completeness:

My WSDL

My Traffic - Request->Response

答:
After some researching, trial and error and much time I finally figured out my mistake.

C# seems not to have a problem with the Transfer-Encoding: Chunked

The mistake was on the service side. The consumed wsdl was generated from java code with the help of Axis(the first Axis not Axis2). Axis generated a wsdl 1.0 while C# seems to expect wsdl 2.0. So in the end, the XML-structure described in the wsdl was flawed and could not be automatically consumed.

We fixed this problem by switching from Axis to Apache CXF. The newly generated wsdl was than consumed without a problem at our C# - client side.

ContentLicense: CC BY-SA 4.0

Body:
I'm currently trying to fix my SOAP-Client in C#, but got somehow stuck with the Transfer-Encoding. I'm more or less a newbie to C#, so it's completly possible that im just missing something minor here.

I consumed a SOAP service from our local Tomcat Server following this: https://web.archive.org/web/20180506023052/http://www.csharptutorial.in/37/csharp-net-how-to-consume-a-web-service-in-csharp-net-visual-studio-2010

My current code:

using System;
using ConsoleApp1.Lims;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            LimsZugriffService client = new LimsZugriffService();
           // FunktionsErgebnis response = client.connect();
           // Console.WriteLine("Connect" + response.meldung);
            String[] bond = new String[] { "versuch.auftrag.nr=2014/0031" };
            String[] bondFail = new String[] { "abc" };
            VersuchsschrittErgebnis reponseVersuch = client.ermittleVersuchsschritte(bond);
            Console.WriteLine(reponseVersuch.ermittelteVersuchsschritte.Length);
            Console.WriteLine(reponseVersuch.meldung);

        }
    }
}

After some testing I found out, that something does not work as intended. My Response-Array of <ermittelteVersuchsschritte> seems to be empty, while the "control"-Flags are parsed normally.

I captured the traffic between client and server to figure out what was wrong and it was actually completly there. Just chunked into 8192 Byte blocks.

Could it be, that the C# implementation of the WebClient got some problems with Transfer-Encoding: Chunked?

After googling for some hours i could not find a satisfiying solution to this issue. I hope somebody, who knows C# and WebServices better than me has the answer.

For the sake of completeness:

My WSDL

My Traffic - Request->Response


问:
Node.js and ExpressJS body-parser package retrieve data
OK first time user of Node, and I am trying to send data to backend/index.js

Requirements

Post data to back-end node

Retrieve posted data and store values as variables

Whats the problem

The post is 200 success, that works.

however when I navigate to  :

http://localhost:8080/backend/index

I get :

Cannot GET /backend/index

Where am I going wrong ?

Here is my front end post post

```<code>var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:8080/backend/index.js",
  "method": "POST",
  "headers": {
    "content-type": "application/x-www-form-urlencoded"
  },
  "data": {
    "id": "1223",
    "token": "223",
    "geo": "ee"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
</code>```

I am trying to retrieve this data from and store as variable in the back end node.

backend/index.js

```<code>// grab the packages we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;

// routes will go here

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

// POST http://localhost:8080/api/users
// parameters sent with
app.post('/backend/index', function(req, res) {
    var user_id = req.body.id;
    var token = req.body.token;
    var geo = req.body.geo;

    res.send(user_id + ' ' + token + ' ' + geo);
});
</code>```

UPDATE using screen shots

答:
I think you didn't specify GET method, you can do like this

```<code>app.get('/', function(req, res) {
    res.send('do something 1');
});

app.get('/backend/index', function(req, res) {
    res.send('do something 2');
});
</code>```

Hope this will help!

Body:
OK first time user of Node, and I am trying to send data to backend/index.js

Requirements

Post data to back-end node

Retrieve posted data and store values as variables

Whats the problem

The post is 200 success, that works.

however when I navigate to  :

http://localhost:8080/backend/index

I get :

Cannot GET /backend/index

Where am I going wrong ?

Here is my front end post post

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:8080/backend/index.js",
  "method": "POST",
  "headers": {
    "content-type": "application/x-www-form-urlencoded"
  },
  "data": {
    "id": "1223",
    "token": "223",
    "geo": "ee"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

I am trying to retrieve this data from and store as variable in the back end node.

backend/index.js

// grab the packages we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;

// routes will go here

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

// POST http://localhost:8080/api/users
// parameters sent with
app.post('/backend/index', function(req, res) {
    var user_id = req.body.id;
    var token = req.body.token;
    var geo = req.body.geo;

    res.send(user_id + ' ' + token + ' ' + geo);
});

UPDATE using screen shots

Body:
I think you didn't specify GET method, you can do like this

app.get('/', function(req, res) {
    res.send('do something 1');
});

app.get('/backend/index', function(req, res) {
    res.send('do something 2');
});

Hope this will help!


问:
sql server complex query

1st one is the source table and 2nd one is the destination table, so in 2nd table by using unpivot the the 12 month columns converted into single column and YTD field should be update automatically. If the month name is Jan means the YTD field will Jan data only, if it is Feb means it will add the Jan data with Feb data. same if it is Dec means it will add from Jan to Dec of the same row.

答:
Using cross apply(values ...) to unpivot your data:

```<code>select
    t.[oru code]
  , t.[bg name]
  , t.[bu name]
  , t.[domain]
  , t.KPI
  , t.UoM
  , t.[Year]
  , t.[ACT/TARGET]
  , v.[Month]
  , v.KPI
  , t.[YTD/ITM]
from t
  cross apply (values
    ('Jan',Jan) ,('Feb',Feb) ,('Mar',Mar)
   ,('April',April) ,('May',May) ,('Jun',Jun)
   ,('Jul',Jul) ,('Aug',Aug) ,('Sep',Sep)
   ,('Oct',Oct) ,('Nov',Nov) ,('Dec',Dec)
    ) v ([Month],KPI)
</code>```

Title: sql server complex query

Body:
Using cross apply(values ...) to unpivot your data:

select
    t.[oru code]
  , t.[bg name]
  , t.[bu name]
  , t.[domain]
  , t.KPI
  , t.UoM
  , t.[Year]
  , t.[ACT/TARGET]
  , v.[Month]
  , v.KPI
  , t.[YTD/ITM]
from t
  cross apply (values
    ('Jan',Jan) ,('Feb',Feb) ,('Mar',Mar)
   ,('April',April) ,('May',May) ,('Jun',Jun)
   ,('Jul',Jul) ,('Aug',Aug) ,('Sep',Sep)
   ,('Oct',Oct) ,('Nov',Nov) ,('Dec',Dec)
    ) v ([Month],KPI)


问:
How can I remove my library from Maven JCenter?
I have uploaded my android library on https://bintray.com and linked it with Jcenter repository http://jcenter.bintray.com/.
Now I want to remove this library from JCenter repository. How can I do this?</p>

答:
Unlink a package from JCenter is available only for paying customers, OSS users can't unlink a package from JCenter.

In case you want to remove your package from Jcenter you only need to unlink your package.

Enter your package, click on "Un-Link" button and then choose Jcenter.

However, important information you need to know about deleting content (taken from Bintray User Manual)

An important note about deleting any material::
  Any package, version or file you have published, may now be an integral part of someone else’s project and deleting them may damage their work (deleting unpublished files is not a problem since they are not visible to anyone else)

Note: if your package has been linked to someone else’s repository and then you delete the package, Bintray will automatically create a copy of this package. This means that even though the data was deleted, the data still exists in another version somewhere.

I am with JFrog, the company behind bintray and artifactory.


问:
Retrieving Filter items in P13nFilterPanel
We are using a P13nFilterPanel. When pressing the [+] button, to add a new filter item, we see the added items on the gui, but can not retrieve the values. How do we retrieve the filter items? We are bound to a JSON object for the original items.

答:
Try to use the method getConditions() of your sap.m.P13nFilterPanel object.

Something like

```<code>p13nOk: function(oEvent) { var aConditions = oEvent.getSource().getAggregation("panels")[0].getConditions();
            console.log(aConditions);
    }
</code>```

Body:
Try to use the method getConditions() of your sap.m.P13nFilterPanel object.

Something like

p13nOk: function(oEvent) { var aConditions = oEvent.getSource().getAggregation("panels")[0].getConditions();
            console.log(aConditions);
    }


问:
setOnClickListener() doesn't work
I have my MainActivity and a LoginActivity. I can call each method without any problem, but as soon as I try to click on the button "btnLogin" or "btnLinkToRegister", nothing happens.

LoginActivity

```<code>import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import com.test.music.myapplication.MainActivity;
import com.test.music.myapplication.R;
import com.test.music.myapplication.app.LoginConfig;
import com.test.music.myapplication.app.LoginController;
import com.test.music.myapplication.helper.SQLiteHandler;
import com.test.music.myapplication.helper.SessionManager;

public class LoginActivity extends Activity{
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_fragment);

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        /*btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });*/

    }

    /**
     * function to verify login details in mysql db
     * */
    public void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                LoginConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        LoginController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

    public Button getBtnLogin() {
        return btnLogin;
    }

    public Button getBtnLinkToRegister() {
        return btnLinkToRegister;
    }

    public void setBtnLogin(Button btnLogin) {
        this.btnLogin = btnLogin;
    }

    public void setBtnLinkToRegister(Button btnLinkToRegister) {
        this.btnLinkToRegister = btnLinkToRegister;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
</code>```

LoginFragment

```<code>import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.test.music.myapplication.activity.LoginActivity;
import com.test.music.myapplication.activity.RegisterActivity;
import com.test.music.myapplication.helper.SQLiteHandler;
import com.test.music.myapplication.helper.SessionManager;

public class LoginFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;
    private static final String TAG = RegisterActivity.class.getSimpleName();
    LoginActivity Log = new LoginActivity();

    private OnFragmentInteractionListener mListener;

    public LoginFragment() {
        // Required empty public constructor
    }

    public static LoginFragment newInstance(String param1, String param2) {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public void onCreate() {
        //super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                if (!email.isEmpty() && !password.isEmpty()) {
                    Log.checkLogin(email, password);
                } else {
                    Toast.makeText(Log.getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.login_fragment, container, false);
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
</code>```

login_fragment

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.music.myapplication.LoginFragment"
    android:background="@color/bg_login"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="0dp" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:paddingLeft="0dp"
        android:paddingRight="0dp" >

        <EditText
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/white"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:padding="10dp"
            android:textColor="@color/input_login"
            android:textColorHint="@color/input_login_hint" />

        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/white"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:padding="10dp"
            android:textColor="@color/input_login"
            android:textColorHint="@color/input_login_hint" />

        <!-- Login Button -->

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@color/btn_login_bg"
            android:text="@string/btn_login"
            android:textColor="@color/btn_login" />

        <!-- Link to Login Screen -->

        <Button
            android:id="@+id/btnLinkToRegisterScreen"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@null"
            android:text="@string/btn_link_to_register"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textSize="15dp" />

    </LinearLayout>

</FrameLayout>
</code>```

logcat

```<code>06-08 14:47:56.703 18829-18829/? I/art: Late-enabling -Xcheck:jni
06-08 14:47:56.734 18829-18829/? D/TidaProvider: TidaProvider()
06-08 14:47:56.766 18829-18829/app.myapplication W/ActivityThread: Application app.myapplication is waiting for the debugger on port 8100...
06-08 14:47:56.769 18829-18829/app.myapplication I/System.out: Sending WAIT chunk
06-08 14:47:56.958 18829-18835/app.myapplication I/art: Debugger is active
06-08 14:47:56.971 18829-18829/app.myapplication I/System.out: Debugger has connected
06-08 14:47:56.971 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.171 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.371 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.571 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.772 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.972 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:58.172 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:58.372 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:58.572 18829-18829/app.myapplication I/System.out: debugger has settled (1478)
06-08 14:47:58.585 18829-18829/app.myapplication W/System: ClassLoader referenced unknown path: /data/app/app.myapplication-1/lib/arm64
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mAcquireFunc method = public int com.qualcomm.qti.Performance.perfLockAcquire(int,int[])
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mReleaseFunc method = public int com.qualcomm.qti.Performance.perfLockRelease()
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mAcquireTouchFunc method = public int com.qualcomm.qti.Performance.perfLockAcquireTouch(android.view.MotionEvent,android.util.DisplayMetrics,int,int[])
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mIOPStart method = public int com.qualcomm.qti.Performance.perfIOPrefetchStart(int,java.lang.String)
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mIOPStop method = public int com.qualcomm.qti.Performance.perfIOPrefetchStop()
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@f8b3883
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@1d12a00
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@cdb1239
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@9ea507e
06-08 14:47:58.803 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@11983e3
06-08 14:47:58.803 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@29e81e0
06-08 14:47:58.835 18829-18829/app.myapplication D/SQLiteHandler: Fetching user from Sqlite: {}
06-08 14:47:58.889 18829-18971/app.myapplication D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
06-08 14:47:58.910 18829-18829/app.myapplication D/ActivityThreadInjector: clearCachedDrawables.
06-08 14:47:58.996 18829-18971/app.myapplication I/Adreno: QUALCOMM build                   : a7823f5, I59a6815413
                                                                               Build Date                       : 09/23/16
                                                                               OpenGL ES Shader Compiler Version: XE031.07.00.00
                                                                               Local Branch                     : mybranch22028469
                                                                               Remote Branch                    : quic/LA.BR.1.3.3_rb2.26
                                                                               Remote Branch                    : NONE
                                                                               Reconstruct Branch               : NOTHING
06-08 14:47:59.030 18829-18971/app.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
06-08 14:47:59.072 18829-18971/app.myapplication E/HAL: hw_get_module_by_class: module name gralloc
06-08 14:47:59.072 18829-18971/app.myapplication E/HAL: hw_get_module_by_class: module name gralloc
06-08 14:48:02.796 18829-18829/app.myapplication W/PathParser: Points are too far apart 4.000000596046461
06-08 14:48:03.830 18829-18829/app.myapplication W/PathParser: Points are too far apart 4.000000596046461
</code>```

If you need any more code, just let me know.

答:
First off, never do this... Calling new on an Activity

```<code>LoginActivity Log = new LoginActivity()
</code>```

Secondly, are you sure you're using Fragments?

This is an Activity

```<code>LoginActivity extends Activity
</code>```

And you simply are putting the Fragment layout into the Activity

```<code> setContentView(R.layout.login_fragment);
</code>```

You never seem to actually use LoginFragment class

I think you've loaded the wrong class because if you used startActivity on this activity code, your buttons would work fine

Title: setOnClickListener() doesn't work

Body:
I have my MainActivity and a LoginActivity. I can call each method without any problem, but as soon as I try to click on the button "btnLogin" or "btnLinkToRegister", nothing happens.

LoginActivity

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import com.test.music.myapplication.MainActivity;
import com.test.music.myapplication.R;
import com.test.music.myapplication.app.LoginConfig;
import com.test.music.myapplication.app.LoginController;
import com.test.music.myapplication.helper.SQLiteHandler;
import com.test.music.myapplication.helper.SessionManager;

public class LoginActivity extends Activity{
    private static final String TAG = RegisterActivity.class.getSimpleName();
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_fragment);

        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);

        // Progress dialog
        pDialog = new ProgressDialog(this);
        pDialog.setCancelable(false);

        // SQLite database handler
        db = new SQLiteHandler(getApplicationContext());

        // Session manager
        session = new SessionManager(getApplicationContext());

        // Check if user is already logged in or not
        if (session.isLoggedIn()) {
            // User is already logged in. Take him to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

        // Login button Click Event
        /*btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                // Check for empty data in the form
                if (!email.isEmpty() && !password.isEmpty()) {
                    // login user
                    checkLogin(email, password);
                } else {
                    // Prompt user to enter credentials
                    Toast.makeText(getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });

        // Link to Register Screen
        btnLinkToRegister.setOnClickListener(new OnClickListener() {

            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(i);
                finish();
            }
        });*/

    }

    /**
     * function to verify login details in mysql db
     * */
    public void checkLogin(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_login";

        pDialog.setMessage("Logging in ...");
        showDialog();

        StringRequest strReq = new StringRequest(Method.POST,
                LoginConfig.URL_LOGIN, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite
                        String uid = jObj.getString("uid");

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String email = user.getString("email");
                        String created_at = user
                                .getString("created_at");

                        // Inserting row in users table
                        db.addUser(name, email, uid, created_at);

                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_LONG).show();
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        LoginController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

    public Button getBtnLogin() {
        return btnLogin;
    }

    public Button getBtnLinkToRegister() {
        return btnLinkToRegister;
    }

    public void setBtnLogin(Button btnLogin) {
        this.btnLogin = btnLogin;
    }

    public void setBtnLinkToRegister(Button btnLinkToRegister) {
        this.btnLinkToRegister = btnLinkToRegister;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

LoginFragment

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.test.music.myapplication.activity.LoginActivity;
import com.test.music.myapplication.activity.RegisterActivity;
import com.test.music.myapplication.helper.SQLiteHandler;
import com.test.music.myapplication.helper.SessionManager;

public class LoginFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
    private Button btnLogin;
    private Button btnLinkToRegister;
    private EditText inputEmail;
    private EditText inputPassword;
    private ProgressDialog pDialog;
    private SessionManager session;
    private SQLiteHandler db;
    private static final String TAG = RegisterActivity.class.getSimpleName();
    LoginActivity Log = new LoginActivity();

    private OnFragmentInteractionListener mListener;

    public LoginFragment() {
        // Required empty public constructor
    }

    public static LoginFragment newInstance(String param1, String param2) {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public void onCreate() {
        //super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        // Login button Click Event
        btnLogin.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                String email = inputEmail.getText().toString().trim();
                String password = inputPassword.getText().toString().trim();

                if (!email.isEmpty() && !password.isEmpty()) {
                    Log.checkLogin(email, password);
                } else {
                    Toast.makeText(Log.getApplicationContext(),
                            "Please enter the credentials!", Toast.LENGTH_LONG)
                            .show();
                }
            }

        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.login_fragment, container, false);
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

login_fragment

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.music.myapplication.LoginFragment"
    android:background="@color/bg_login"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="0dp" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:paddingLeft="0dp"
        android:paddingRight="0dp" >

        <EditText
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/white"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:padding="10dp"
            android:textColor="@color/input_login"
            android:textColorHint="@color/input_login_hint" />

        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@color/white"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:padding="10dp"
            android:textColor="@color/input_login"
            android:textColorHint="@color/input_login_hint" />

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@color/btn_login_bg"
            android:text="@string/btn_login"
            android:textColor="@color/btn_login" />

        <Button
            android:id="@+id/btnLinkToRegisterScreen"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@null"
            android:text="@string/btn_link_to_register"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:textSize="15dp" />

    </LinearLayout>

</FrameLayout>

logcat

06-08 14:47:56.703 18829-18829/? I/art: Late-enabling -Xcheck:jni
06-08 14:47:56.734 18829-18829/? D/TidaProvider: TidaProvider()
06-08 14:47:56.766 18829-18829/app.myapplication W/ActivityThread: Application app.myapplication is waiting for the debugger on port 8100...
06-08 14:47:56.769 18829-18829/app.myapplication I/System.out: Sending WAIT chunk
06-08 14:47:56.958 18829-18835/app.myapplication I/art: Debugger is active
06-08 14:47:56.971 18829-18829/app.myapplication I/System.out: Debugger has connected
06-08 14:47:56.971 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.171 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.371 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.571 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.772 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:57.972 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:58.172 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:58.372 18829-18829/app.myapplication I/System.out: waiting for debugger to settle...
06-08 14:47:58.572 18829-18829/app.myapplication I/System.out: debugger has settled (1478)
06-08 14:47:58.585 18829-18829/app.myapplication W/System: ClassLoader referenced unknown path: /data/app/app.myapplication-1/lib/arm64
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mAcquireFunc method = public int com.qualcomm.qti.Performance.perfLockAcquire(int,int[])
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mReleaseFunc method = public int com.qualcomm.qti.Performance.perfLockRelease()
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mAcquireTouchFunc method = public int com.qualcomm.qti.Performance.perfLockAcquireTouch(android.view.MotionEvent,android.util.DisplayMetrics,int,int[])
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mIOPStart method = public int com.qualcomm.qti.Performance.perfIOPrefetchStart(int,java.lang.String)
06-08 14:47:58.700 18829-18829/app.myapplication V/BoostFramework: mIOPStop method = public int com.qualcomm.qti.Performance.perfIOPrefetchStop()
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@f8b3883
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@1d12a00
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@cdb1239
06-08 14:47:58.704 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@9ea507e
06-08 14:47:58.803 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@11983e3
06-08 14:47:58.803 18829-18829/app.myapplication V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@29e81e0
06-08 14:47:58.835 18829-18829/app.myapplication D/SQLiteHandler: Fetching user from Sqlite: {}
06-08 14:47:58.889 18829-18971/app.myapplication D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
06-08 14:47:58.910 18829-18829/app.myapplication D/ActivityThreadInjector: clearCachedDrawables.
06-08 14:47:58.996 18829-18971/app.myapplication I/Adreno: QUALCOMM build                   : a7823f5, I59a6815413
                                                                               Build Date                       : 09/23/16
                                                                               OpenGL ES Shader Compiler Version: XE031.07.00.00
                                                                               Local Branch                     : mybranch22028469
                                                                               Remote Branch                    : quic/LA.BR.1.3.3_rb2.26
                                                                               Remote Branch                    : NONE
                                                                               Reconstruct Branch               : NOTHING
06-08 14:47:59.030 18829-18971/app.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
06-08 14:47:59.072 18829-18971/app.myapplication E/HAL: hw_get_module_by_class: module name gralloc
06-08 14:47:59.072 18829-18971/app.myapplication E/HAL: hw_get_module_by_class: module name gralloc
06-08 14:48:02.796 18829-18829/app.myapplication W/PathParser: Points are too far apart 4.000000596046461
06-08 14:48:03.830 18829-18829/app.myapplication W/PathParser: Points are too far apart 4.000000596046461

If you need any more code, just let me know.

Body:
First off, never do this... Calling new on an Activity

LoginActivity Log = new LoginActivity()

Secondly, are you sure you're using Fragments?

This is an Activity

LoginActivity extends Activity

And you simply are putting the Fragment layout into the Activity

 setContentView(R.layout.login_fragment);

You never seem to actually use LoginFragment class

I think you've loaded the wrong class because if you used startActivity on this activity code, your buttons would work fine


问:
How to access and manipulate structural directives during an e2e test
Background: I want to be able to permutate all possible configurations of an Angular2 screen for a given route and screenshot them using Protractor: http://www.protractortest.org/#/debugging.

Issue: I can't seem to find a way to acces a directive (like ng-if for example) during an e2e Test.

Is it possible to access the ng-if directive inside of an e2e test?

If yes: is there a way to manipulate the directive? By manipulate i mean to influence the evaluation of the directive without changing the input on which the directive depends.

Possible solution path: here is an example on how i acces the router to be able to navigate to a specific route:

```<code>it('should get the router', () => {
browser.executeScript(() => {
  const ng = window['ng'];
  const root = document.getElementsByTagName('app-root')[0];
  const router = ng.probe(root)
    .injector.get(ng.coreTokens.Router);
  const routes = router.config;
  ...
  ...
  return [];
}).then(ret=> console.log(ret));
});
</code>```

Thoughts:

Maybe it is possible to somehow get the ng-if directives using ng.probe

I would apreciate any hints regarding my question.

答:
You can do it as follows:

html

```<code><button id="find">Find ngIf directives and show all</button>
</code>```

script

```<code>var findComments = function(el) {
    var arr = [];
    for(var i = 0; i < el.childNodes.length; i++) {
        var node = el.childNodes[i];
        if(node.nodeType === 8) {
            arr.push(node);
        } else {
            arr.push.apply(arr, findComments(node));
        }
    }
    return arr;
};

function findNgIfDirectives() {
  var commentNodes = findComments(document);
  const ng = window['ng'];
  commentNodes.forEach(function(node) {
    var debugNode = ng.probe(node);
    var ngIf = (debugNode.providerTokens[0]);
    var ngIfInstance = debugNode.injector.get(ngIf);

    ngIfInstance.ngIf = true;
  });

}
document.getElementById('find').addEventListener('click', findNgIfDirectives)
</code>```

Plunker Example

Body:
Background: I want to be able to permutate all possible configurations of an Angular2 screen for a given route and screenshot them using Protractor: http://www.protractortest.org/#/debugging.

Issue: I can't seem to find a way to acces a directive (like ng-if for example) during an e2e Test.

Is it possible to access the ng-if directive inside of an e2e test?

If yes: is there a way to manipulate the directive? By manipulate i mean to influence the evaluation of the directive without changing the input on which the directive depends.

Possible solution path: here is an example on how i acces the router to be able to navigate to a specific route:

it('should get the router', () => {
browser.executeScript(() => {
  const ng = window['ng'];
  const root = document.getElementsByTagName('app-root')[0];
  const router = ng.probe(root)
    .injector.get(ng.coreTokens.Router);
  const routes = router.config;
  ...
  ...
  return [];
}).then(ret=> console.log(ret));
});

Thoughts:

Maybe it is possible to somehow get the ng-if directives using ng.probe

I would apreciate any hints regarding my question.

Body:
You can do it as follows:

html

<button id="find">Find ngIf directives and show all</button>

script

var findComments = function(el) {
    var arr = [];
    for(var i = 0; i < el.childNodes.length; i++) {
        var node = el.childNodes[i];
        if(node.nodeType === 8) {
            arr.push(node);
        } else {
            arr.push.apply(arr, findComments(node));
        }
    }
    return arr;
};

function findNgIfDirectives() {
  var commentNodes = findComments(document);
  const ng = window['ng'];
  commentNodes.forEach(function(node) {
    var debugNode = ng.probe(node);
    var ngIf = (debugNode.providerTokens[0]);
    var ngIfInstance = debugNode.injector.get(ngIf);

    ngIfInstance.ngIf = true;
  });

}
document.getElementById('find').addEventListener('click', findNgIfDirectives)

Plunker Example


问:
Tools used for programming in Linux
I would like to start programming using the Linux operating system and all the free stuff out there.

What is the most common and the best language to use with Linux, C or C++ or C#?

What tools are similar to Turbo C, or Visual Studio in Windows?

答:
For the language it really depends what you want to do :

C is good for low level software, specially if performance is a priority, otherwise syntax can be painful for a first programming experience.

C++ is good for high level software and has a lot of good qualities that C misses (e.g. classes, operator/function overload), but may require some good knowledge of C in case of serious trouble.

if it is really your first programming experience, maybe learning with an interpreted language like Python/Perl could be a good idea to begin with.

For the text editor you have:

the good old classics: emacs/VIM, I don't want to argue about the choice

graphical editors: gedit, gvim, kate. Personally, I really like kate.

IDE: kdevelop, anjuta, eclipse, netbeans. Personally I use netbeans for C/C++ development. Again, if it is a first experience, maybe beginning with an IDE is not a great idea to make things clear.

For the compiler, unless you have special needs, you don't need something else than GCC.

ContentLicense: CC BY-SA 2.5

Title: Tools used for programming in Linux


问:
Angular material Could not find Angular Material core theme
In my Angular2 project I install lastest material plugin from https://material.angular.io/guide/getting-started. Next I add @import '~@angular/material/prebuilt-themes/deeppurple-amber.css'; to my css file for my component. But in my console Angular shows this error:

material.es5.js:148 Could not find Angular Material core theme. Most Material components may not work as expected. For more info refer to the theming guide: https://material.angular.io/guide/theming`

The material components not working.
Whats wrong?

答:
Please insert below code into your styles.css which is located in your src folder.

```<code>@import "../node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css";
</code>```

You can select any css under the prebuilt-themes folder.

Body:
Please insert below code into your styles.css which is located in your src folder.

@import "../node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css";

You can select any css under the prebuilt-themes folder.


问:
Joining two streams
Is it possible to join two separate PubSubIo Unbounded PCollections using a key present in both of them? I try to accomplish the task with something like:

Read(FistStream)&Read(SecondStream) -> Flatten -> Generate key to use in joining -> Use Session Windowing to gather them together -> Group by key then rewindow with fixed size windows -> AvroIOWrite to disk using windowing.

EDIT:

Here is the pipeline code I created. I experience two problems:

Nothing get's written to the disk

Pipeline starts to be really unstable - it randomly slows down processing of certain steps. Especially group by. It's not able to keep up with ingestion speed even when I use 10 dataflow workers.

I need to handle ~ 10 000 sessions a second. Each session comprises of 1 or 2 events, then needs to be closed.

```<code>    PubsubIO.Read<String> auctionFinishedReader = PubsubIO.readStrings().withTimestampAttribute(TIMESTAMP_ATTRIBUTE)
            .fromTopic("projects/authentic-genre-152513/topics/auction_finished");
    PubsubIO.Read<String> auctionAcceptedReader = PubsubIO.readStrings().withTimestampAttribute(TIMESTAMP_ATTRIBUTE)
            .fromTopic("projects/authentic-genre-152513/topics/auction_accepted");

    PCollection<String> auctionFinishedStream = p.apply("ReadAuctionFinished", auctionFinishedReader);
    PCollection<String> auctionAcceptedStream = p.apply("ReadAuctionAccepted", auctionAcceptedReader);

    PCollection<String> combinedEvents = PCollectionList.of(auctionFinishedStream)
            .and(auctionAcceptedStream).apply(Flatten.pCollections());

    PCollection<KV<String, String>> keyedAuctionFinishedStream = combinedEvents
            .apply("AddKeysToAuctionFinished", WithKeys.of(new GenerateKeyForEvent()));

    PCollection<KV<String, Iterable<String>>> sessions = keyedAuctionFinishedStream
            .apply(Window.<KV<String, String>>into(Sessions.withGapDuration(Duration.standardMinutes(1)))
                                            .withTimestampCombiner(TimestampCombiner.END_OF_WINDOW))
            .apply(GroupByKey.create());

    PCollection<SodaSession> values = sessions
            .apply(ParDo.of(new DoFn<KV<String, Iterable<String>>, SodaSession> () {
                @ProcessElement
                public void processElement(ProcessContext c, BoundedWindow window) {
                    c.output(new SodaSession("auctionid", "stattedat"));
                }

    }));

    PCollection<SodaSession> windowedEventStream = values
            .apply("ApplyWindowing", Window.<SodaSession>into(FixedWindows.of(Duration.standardMinutes(2)))
                    .triggering(Repeatedly.forever(
                            AfterProcessingTime.pastFirstElementInPane()
                                    .plusDelayOf(Duration.standardMinutes(1))
                    ))
                    .withAllowedLateness(Duration.ZERO)
                    .discardingFiredPanes()
            );

    AvroIO.Write<SodaSession> avroWriter = AvroIO
            .write(SodaSession.class)
            .to("gs://storage/")
            .withWindowedWrites()
            .withFilenamePolicy(new EventsToGCS.PerWindowFiles("sessionsoda"))
            .withNumShards(3);

    windowedEventStream.apply("WriteToDisk", avroWriter);
</code>```

答:
I've found an efficient solution. As one of my collection was disproportionate in size compared to the other one so I used side input to speed up grouping operation. Here is an overview of my solution:

Read both event streams.

Flatten them into single PCollection.

Use sliding window sized (closable session duration + session max length, every closable session duration).

Partition collections again.

Create PCollectionView from smaller PCollection.

Join both streams using sideInput with the view created in the previous step.

Write sessions to disk.

It handles joining 4000 events/sec stream (larger one) + 60 events/sec stream on 1-2 DataFlow workers versus ~15 workers when used Session windowing along with GroupBy.

Title: Joining two streams

Body:
Is it possible to join two separate PubSubIo Unbounded PCollections using a key present in both of them? I try to accomplish the task with something like:

Read(FistStream)&Read(SecondStream) -> Flatten -> Generate key to use in joining -> Use Session Windowing to gather them together -> Group by key then rewindow with fixed size windows -> AvroIOWrite to disk using windowing.

EDIT:

Here is the pipeline code I created. I experience two problems:

Nothing get's written to the disk

Pipeline starts to be really unstable - it randomly slows down processing of certain steps. Especially group by. It's not able to keep up with ingestion speed even when I use 10 dataflow workers.

I need to handle ~ 10 000 sessions a second. Each session comprises of 1 or 2 events, then needs to be closed.

    PubsubIO.Read<String> auctionFinishedReader = PubsubIO.readStrings().withTimestampAttribute(TIMESTAMP_ATTRIBUTE)
            .fromTopic("projects/authentic-genre-152513/topics/auction_finished");
    PubsubIO.Read<String> auctionAcceptedReader = PubsubIO.readStrings().withTimestampAttribute(TIMESTAMP_ATTRIBUTE)
            .fromTopic("projects/authentic-genre-152513/topics/auction_accepted");

    PCollection<String> auctionFinishedStream = p.apply("ReadAuctionFinished", auctionFinishedReader);
    PCollection<String> auctionAcceptedStream = p.apply("ReadAuctionAccepted", auctionAcceptedReader);

    PCollection<String> combinedEvents = PCollectionList.of(auctionFinishedStream)
            .and(auctionAcceptedStream).apply(Flatten.pCollections());

    PCollection<KV<String, String>> keyedAuctionFinishedStream = combinedEvents
            .apply("AddKeysToAuctionFinished", WithKeys.of(new GenerateKeyForEvent()));

    PCollection<KV<String, Iterable<String>>> sessions = keyedAuctionFinishedStream
            .apply(Window.<KV<String, String>>into(Sessions.withGapDuration(Duration.standardMinutes(1)))
                                            .withTimestampCombiner(TimestampCombiner.END_OF_WINDOW))
            .apply(GroupByKey.create());

    PCollection<SodaSession> values = sessions
            .apply(ParDo.of(new DoFn<KV<String, Iterable<String>>, SodaSession> () {
                @ProcessElement
                public void processElement(ProcessContext c, BoundedWindow window) {
                    c.output(new SodaSession("auctionid", "stattedat"));
                }

    }));

    PCollection<SodaSession> windowedEventStream = values
            .apply("ApplyWindowing", Window.<SodaSession>into(FixedWindows.of(Duration.standardMinutes(2)))
                    .triggering(Repeatedly.forever(
                            AfterProcessingTime.pastFirstElementInPane()
                                    .plusDelayOf(Duration.standardMinutes(1))
                    ))
                    .withAllowedLateness(Duration.ZERO)
                    .discardingFiredPanes()
            );

    AvroIO.Write<SodaSession> avroWriter = AvroIO
            .write(SodaSession.class)
            .to("gs://storage/")
            .withWindowedWrites()
            .withFilenamePolicy(new EventsToGCS.PerWindowFiles("sessionsoda"))
            .withNumShards(3);

    windowedEventStream.apply("WriteToDisk", avroWriter);