问:
Clickable links in a scrolling HTML enabled dynamic textfield in Flash AS2 movie - works in Flash Pro, not in browser
I have developed a rolling credits style movieclip in Flash using Actionscript 2. Text is loaded from an XML file and parsed into a dynamic textfield. This text includes hyperlinks to webpages defined by a url node in the xml so Flash can add the appropriate a href to the dynamic text field and make the link clickable.

In my first attempts to do this the textfield stayed still and all the links worked fine both testing locally and when I run it in a browser on my website.

Then I wanted to make things move ... which I achieved easily enough and tested locally (from within Flash Professional) and the links remained clickable, a browser window opened and the webpage i was expecting to see opened... great

However, when I export the swf, upload it and run it from my website suddenly the links are not working. So I tried to test the movie in a browser from Flash Pro - same problem, it must be something to do with Flash Player and the moving dynamic textfield.

a couple of observations - the cursor will change to a hand icon when over the links as you would expect, and if I right click on the link and click open in a new window the link works ok, just not when I left click. If I stop the scrolling then the links become clickable again, it is only when the textfield is moving... actually its not technically scrolling, im moving the whole textfield.

Any ideas?

答:
Rather than using the href property of the dynamic textField, I would suggest wrapping the textFields as MovieClips and then using the MovieClips onRelease() method.

You could load your text from your xml into the wrapped textFields, and load the associated link urls into an array.  Below presumes you have a linked library symbol that is a movieclip with a dynamic textField in it.  The textField's instance name is tf.  The library link ID is myListItem, the ID of the container to hold the list is myListContainer.  The nextY variable is for placing each link below the last, and the listItemSpacing variable is how many pixels of spacing between each list item.

DISCLAIMER - THIS IS PART PSEUDO CODE - I typed this all out without actually compiling it, so there may be typos or as2/3 syntax goofs, but it should get you going in the right direction

```<code>var listContainer = myListContainer;
var xmlList = theXmlYouHaveParsed;
var urlArray = new Array();
var nextY = 0;
var listItemSpacing = 5;
var thisInstance = this;

for(i=0; i < theXmlYouHaveParsed.length; i++)
{
     var mc = listContainer.attachMovieClip("myListItem", i+1);
     mc._y = nextY;

     mc.tf.htmlText = theXmlYouHaveParsed[i].someText;
     mc.id = String(i);

     urlArray.push(theXmlYouHaveParsed[i].someUrl);

     mc.onRelease = function()
     {
         thisInstance.onLinkClicked(this.id);
     }

     nextY += mc._height + listItemSpacing;
}

function onLinkClicked(id)
{
     getURL(urlArray[id]);
}
</code>```

Body:
Rather than using the href property of the dynamic textField, I would suggest wrapping the textFields as MovieClips and then using the MovieClips onRelease() method.

You could load your text from your xml into the wrapped textFields, and load the associated link urls into an array.  Below presumes you have a linked library symbol that is a movieclip with a dynamic textField in it.  The textField's instance name is tf.  The library link ID is myListItem, the ID of the container to hold the list is myListContainer.  The nextY variable is for placing each link below the last, and the listItemSpacing variable is how many pixels of spacing between each list item.

DISCLAIMER - THIS IS PART PSEUDO CODE - I typed this all out without actually compiling it, so there may be typos or as2/3 syntax goofs, but it should get you going in the right direction

var listContainer = myListContainer;
var xmlList = theXmlYouHaveParsed;
var urlArray = new Array();
var nextY = 0;
var listItemSpacing = 5;
var thisInstance = this;

for(i=0; i < theXmlYouHaveParsed.length; i++)
{
     var mc = listContainer.attachMovieClip("myListItem", i+1);
     mc._y = nextY;

     mc.tf.htmlText = theXmlYouHaveParsed[i].someText;
     mc.id = String(i);

     urlArray.push(theXmlYouHaveParsed[i].someUrl);

     mc.onRelease = function()
     {
         thisInstance.onLinkClicked(this.id);
     }

     nextY += mc._height + listItemSpacing;
}

function onLinkClicked(id)
{
     getURL(urlArray[id]);
}


来源: stackexchange

问:
How can I get my fragment code onClick() get recognized my the main activity?
I am new to android studio. I am sitting for a couple days on my work, but I didn't manage my Button on a Fragment to work as expected.

My structure:

For my fragment, I have a java-class where my method for the Button is defined. (onClick())

I have a main-activity which contains/knows/... the fragment/the java-class of fragment

When I click on my button, the app crashes.
I think it has to do something with binding the fragment to the main activity. I thought i did that already by saying:

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sub_page01, container, false);
return rootView;
}
</code>```

in the main activity.

But it seems I forget something important. I would appreciate it if someone can help me out.

MainActivity.java

```<code>package com.example.yasars.my_fernbedienung;

import android.os.AsyncTask;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.webkit.HttpAuthHandler;
import android.widget.TextView;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.app.Activity;

import android.util.Log;

import org.json.JSONException;
import org.w3c.dom.Text;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private SeekBar mySoundBar;
    private TextView textView;
    private HttpRequest httpRequest;
    private String ipaddress;

    private void initializeVariables() {
        mySoundBar = (SeekBar) findViewById(R.id.mySoundBar); // initiate the Seekbar
        textView = (TextView) findViewById(R.id.volumeView); // initiate volume print
        ipaddress = "192.168.56.1";
        httpRequest = new HttpRequest(ipaddress, 4, true); //4 stands for 4 milliseconds to wait for a response
    }

    public void onClick(View v) {

    }

    private static final String Tag = "myDebugAid";

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    public void addContentView(View view, ViewGroup.LayoutParams params) {
        super.addContentView(view, params);
        Log.i(Tag, "addContentView");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(Tag, "onStop");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i(Tag, "onSaveInstanceState");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(Tag, "onPause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(Tag, "onResume");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initializeVariables();

        mySoundBar.setMax(100); // 100 maximum value for the Seek bar
        mySoundBar.setProgress(10);

        textView.setText(mySoundBar.getProgress() + "/" + mySoundBar.getMax());

        mySoundBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            int progress = 0;

            @Override
            public void onProgressChanged(SeekBar seekBar, int progressValue, boolean fromUser) {
                progress = progressValue;
                textView.setText(progress + "/" + seekBar.getMax());
                try {
                    httpRequest.execute("volume=" + progress);
                } catch (IOException | JSONException | IllegalArgumentException e) {
                }

                //Toast.makeText(getApplicationContext(), "Changing volume", Toast.LENGTH_SHORT).show();
                //we don't need above line. It is irritating for the user
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                textView.setText(progress + "/" + seekBar.getMax());
                try {
                    httpRequest.execute("volume=" + progress);
                } catch (IOException | JSONException | IllegalArgumentException e) {
                }

                //Toast.makeText(getApplicationContext(), "Started tracking volume", Toast.LENGTH_SHORT).show();
                //we don't need above line. It is irritating for the user
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                textView.setText(progress + "/" + seekBar.getMax());
                try {
                    httpRequest.execute("volume=" + progress);
                } catch (IOException | JSONException | IllegalArgumentException e) {
                }
            }
        });

        //HttpRequest httpReq = new HttpRequest(); // an instance of HttpRequest

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        try {
            httpRequest.execute("channelMain=8a");
        } catch (IOException | JSONException | IllegalArgumentException e) {
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        return super.onOptionsItemSelected(item);
    }

//    seekBarInstanceVariable.setOnSeekBarChangeListener(new OnSeekBarChangeListener()) {
//
//    } //This method is used to notify the user changes/actions in the SeekBar.

    public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {

    } //This listener method will be invoked if any change is made in the SeekBar.

    public void onStartTrackingTouch(SeekBar seekBar) {

    } //This listener method will be invoked at the start of user’s touch event. Whenever a user
    // touch the thumb for dragging this method will automatically called.

    public void onStopTrackingTouch(SeekBar seekBar) {

    } //This listener method will be invoked at the end of user touch event. Whenever a user stop
    // dragging the thump this method will be automatically called.

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
                View rootView = inflater.inflate(R.layout.fragment_sub_page01, container, false);
                return rootView;
            } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
                View rootView = inflater.inflate(R.layout.fragment_sub_page02, container, false);
                return rootView;
            } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3) {
                View rootView = inflater.inflate(R.layout.fragment_sub_page03, container, false);
                return rootView;
            } else {
                View rootView = inflater.inflate(R.layout.fragment_main, container, false);
                TextView textView = (TextView) rootView.findViewById(R.id.section_label);
                textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
                return rootView;
            }
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Home";
                case 1:
                    return "Favoriten";
                case 2:
                    return "Sender";
            }
            return null;
        }
    }
}
</code>```

SubPage01.java:

```<code>package layout;

import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SeekBar;

import java.io.IOException;
import java.util.Vector;
import java.util.Map;

import com.example.yasars.my_fernbedienung.HttpRequest;
import com.example.yasars.my_fernbedienung.R;

import org.json.JSONException;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link SubPage01.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SubPage01#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SubPage01 extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private Button button_tri_right;
    private Button button_tri_left;
    private HttpRequest httpRequest;
    private String ipaddress;
    private int onChannel = 1; //it is for the channel recognition.
    private Map<String, String> ChannelMap;

    private void initializeHttpRequest() {
        ipaddress = "192.168.56.1";
        httpRequest = new HttpRequest(ipaddress, 4, true);
    }

    private void fillChannelContainer() {

        ChannelMap.put("1", "8a");
        ChannelMap.put("2", "8b");
        ChannelMap.put("3", "8c");
        ChannelMap.put("4", "22a");
        ChannelMap.put("5", "22b");
        ChannelMap.put("6", "22c");
        ChannelMap.put("7", "22d");
        ChannelMap.put("8", "34a");
        ChannelMap.put("9", "34b");
        ChannelMap.put("10", "34c");
        ChannelMap.put("11", "34d");
        ChannelMap.put("12", "37a");
        ChannelMap.put("13", "37b");
        ChannelMap.put("14", "37c");

/*        ChannelMap.put("Phoenix", "8a");
        ChannelMap.put("BR", "8b");
        ChannelMap.put("SWR", "8c");
        ChannelMap.put("ZDF", "22a");
        ChannelMap.put("3Sat", "22b");
        ChannelMap.put("ZDFinfo" "22c");
        ChannelMap.put("KiKa", "22d");
        ChannelMap.put("RTL", "34a");
        ChannelMap.put("RTL2", "34b");
        ChannelMap.put("Super RTL", "34c");
        ChannelMap.put("Vox", "34d");
        ChannelMap.put("Das Erste", "37a");
        ChannelMap.put("hr", "37b");
        ChannelMap.put("arte", "37c");*/
    }

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SubPage01.
     */
    // TODO: Rename and change types and number of parameters
    public static SubPage01 newInstance(String param1, String param2) {
        SubPage01 fragment = new SubPage01();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        initializeHttpRequest();
        fillChannelContainer();

    }

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

        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.fragment_sub_page01, container, false);
        View v = inflater.inflate(R.layout.fragment_sub_page01, container, false);

        Button b1 = (Button) v.findViewById(R.id.right_triangle_button);
        b1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.right_triangle_button: {
                        if (onChannel == 14) {
                            onChannel = 1;
                        } else {
                            onChannel = onChannel + 1;
                        }
                        String tmpString = String.valueOf(onChannel);
                        try {
                            httpRequest.execute("channelMain=" + ChannelMap.get(tmpString));
                            System.out.println(ChannelMap.get(tmpString));
                        } catch (IOException | JSONException | IllegalArgumentException e) {
                        }
                    }
                }
            }
        });

        Button b2 = (Button) v.findViewById(R.id.left_triangle_button);
        b2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.left_triangle_button: {
                        if (onChannel == 1)

                        {
                            onChannel = 14;
                        } else

                        {
                            onChannel = onChannel - 1;
                        }

                        String tmpString = String.valueOf(onChannel);
                        try

                        {
                            httpRequest.execute("channelMain=" + ChannelMap.get(tmpString));
                            System.out.println(ChannelMap.get(tmpString));
                        } catch (IOException | JSONException |
                                IllegalArgumentException e)

                        {
                        }
                    }
                }
            }
        });

        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        button_tri_right = (Button) getView().findViewById(R.id.right_triangle_button); //this is necessary because you can't
        button_tri_left = (Button) getView().findViewById(R.id.left_triangle_button);   //use findViewById() directly, like in
        //activities.
    }

    /*// TODO: Rename method, update argument and hook method into UI event
    public void onButtonRightPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
        String tmpString = String.valueOf(onChannel);
        try {
            httpRequest.execute("channelMain=" + ChannelMap.get(tmpString));
        } catch (IOException | JSONException | IllegalArgumentException e) {
        }
        onChannel = onChannel + 1;
    }

    public void onButtonLeftPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
        String tmpString = String.valueOf(onChannel);
        try {
            httpRequest.execute("channelMain=" + ChannelMap.get(tmpString));
            System.out.println(ChannelMap.get(tmpString));
        } catch (IOException | JSONException | IllegalArgumentException e) {
        }
        onChannel = onChannel + 1;
    }*/

    @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;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

}
</code>```

fragment_sub_page01.xml

```<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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="layout.SubPage01">

    <Button
        android:id="@+id/left_triangle_button"
        android:layout_width="60dp"
        android:layout_height="80dp"
        android:layout_gravity="center"
        android:layout_marginStart="-100dp"
        android:background="@drawable/triangle_button_left"
        android:clickable="true"
        app:backgroundTint="#076a24" />

    <Button
        android:id="@+id/right_triangle_button"
        android:layout_width="60dp"

        android:layout_height="80dp"
        android:layout_gravity="center"
        android:layout_marginStart="100dp"
        android:background="@drawable/triangle_button_right"
        android:clickable="true"
        android:onClick="onClick"
        app:backgroundTint="#076a24" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Sendung"
        android:layout_gravity="center"
        android:layout_marginTop="-100dp"
        />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Sender"
        android:layout_gravity="center"
        android:layout_marginTop="-150dp" />

    <EditText
        android:id="@+id/editText"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:ems="4"
        android:hint="Nr."
        android:inputType="number"
        android:textAlignment="center" />

</FrameLayout>
</code>```

I tried some possible solutions but didn't manage to resolve my problem.

Thanks in advance.

Edit: the talk is about buttons:

left_triangle_button

right_triangle_button

答:
It is probably because you are trying to execute network request on UI thread (Check you crash log).
Network requests should be done on background thread.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am new to android studio. I am sitting for a couple days on my work, but I didn't manage my Button on a Fragment to work as expected.

My structure:

For my fragment, I have a java-class where my method for the Button is defined. (onClick())

I have a main-activity which contains/knows/... the fragment/the java-class of fragment

When I click on my button, the app crashes.
I think it has to do something with binding the fragment to the main activity. I thought i did that already by saying:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sub_page01, container, false);
return rootView;
}

in the main activity.

But it seems I forget something important. I would appreciate it if someone can help me out.

MainActivity.java

package com.example.yasars.my_fernbedienung;

import android.os.AsyncTask;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.webkit.HttpAuthHandler;
import android.widget.TextView;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.app.Activity;

import android.util.Log;

import org.json.JSONException;
import org.w3c.dom.Text;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private SeekBar mySoundBar;
    private TextView textView;
    private HttpRequest httpRequest;
    private String ipaddress;

    private void initializeVariables() {
        mySoundBar = (SeekBar) findViewById(R.id.mySoundBar); // initiate the Seekbar
        textView = (TextView) findViewById(R.id.volumeView); // initiate volume print
        ipaddress = "192.168.56.1";
        httpRequest = new HttpRequest(ipaddress, 4, true); //4 stands for 4 milliseconds to wait for a response
    }

    public void onClick(View v) {

    }

    private static final String Tag = "myDebugAid";

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    public void addContentView(View view, ViewGroup.LayoutParams params) {
        super.addContentView(view, params);
        Log.i(Tag, "addContentView");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(Tag, "onStop");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i(Tag, "onSaveInstanceState");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(Tag, "onPause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(Tag, "onResume");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initializeVariables();

        mySoundBar.setMax(100); // 100 maximum value for the Seek bar
        mySoundBar.setProgress(10);

        textView.setText(mySoundBar.getProgress() + "/" + mySoundBar.getMax());

        mySoundBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            int progress = 0;

            @Override
            public void onProgressChanged(SeekBar seekBar, int progressValue, boolean fromUser) {
                progress = progressValue;
                textView.setText(progress + "/" + seekBar.getMax());
                try {
                    httpRequest.execute("volume=" + progress);
                } catch (IOException | JSONException | IllegalArgumentException e) {
                }

                //Toast.makeText(getApplicationContext(), "Changing volume", Toast.LENGTH_SHORT).show();
                //we don't need above line. It is irritating for the user
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                textView.setText(progress + "/" + seekBar.getMax());
                try {
                    httpRequest.execute("volume=" + progress);
                } catch (IOException | JSONException | IllegalArgumentException e) {
                }

                //Toast.makeText(getApplicationContext(), "Started tracking volume", Toast.LENGTH_SHORT).show();
                //we don't need above line. It is irritating for the user
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                textView.setText(progress + "/" + seekBar.getMax());
                try {
                    httpRequest.execute("volume=" + progress);
                } catch (IOException | JSONException | IllegalArgumentException e) {
                }
            }
        });

        //HttpRequest httpReq = new HttpRequest(); // an instance of HttpRequest

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        try {
            httpRequest.execute("channelMain=8a");
        } catch (IOException | JSONException | IllegalArgumentException e) {
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        return super.onOptionsItemSelected(item);
    }

//    seekBarInstanceVariable.setOnSeekBarChangeListener(new OnSeekBarChangeListener()) {
//
//    } //This method is used to notify the user changes/actions in the SeekBar.

    public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {

    } //This listener method will be invoked if any change is made in the SeekBar.

    public void onStartTrackingTouch(SeekBar seekBar) {

    } //This listener method will be invoked at the start of user’s touch event. Whenever a user
    // touch the thumb for dragging this method will automatically called.

    public void onStopTrackingTouch(SeekBar seekBar) {

    } //This listener method will be invoked at the end of user touch event. Whenever a user stop
    // dragging the thump this method will be automatically called.

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
                View rootView = inflater.inflate(R.layout.fragment_sub_page01, container, false);
                return rootView;
            } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
                View rootView = inflater.inflate(R.layout.fragment_sub_page02, container, false);
                return rootView;
            } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3) {
                View rootView = inflater.inflate(R.layout.fragment_sub_page03, container, false);
                return rootView;
            } else {
                View rootView = inflater.inflate(R.layout.fragment_main, container, false);
                TextView textView = (TextView) rootView.findViewById(R.id.section_label);
                textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
                return rootView;
            }
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Home";
                case 1:
                    return "Favoriten";
                case 2:
                    return "Sender";
            }
            return null;
        }
    }
}

SubPage01.java:

package layout;

import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.SeekBar;

import java.io.IOException;
import java.util.Vector;
import java.util.Map;

import com.example.yasars.my_fernbedienung.HttpRequest;
import com.example.yasars.my_fernbedienung.R;

import org.json.JSONException;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link SubPage01.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SubPage01#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SubPage01 extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private Button button_tri_right;
    private Button button_tri_left;
    private HttpRequest httpRequest;
    private String ipaddress;
    private int onChannel = 1; //it is for the channel recognition.
    private Map<String, String> ChannelMap;

    private void initializeHttpRequest() {
        ipaddress = "192.168.56.1";
        httpRequest = new HttpRequest(ipaddress, 4, true);
    }

    private void fillChannelContainer() {

        ChannelMap.put("1", "8a");
        ChannelMap.put("2", "8b");
        ChannelMap.put("3", "8c");
        ChannelMap.put("4", "22a");
        ChannelMap.put("5", "22b");
        ChannelMap.put("6", "22c");
        ChannelMap.put("7", "22d");
        ChannelMap.put("8", "34a");
        ChannelMap.put("9", "34b");
        ChannelMap.put("10", "34c");
        ChannelMap.put("11", "34d");
        ChannelMap.put("12", "37a");
        ChannelMap.put("13", "37b");
        ChannelMap.put("14", "37c");

/*        ChannelMap.put("Phoenix", "8a");
        ChannelMap.put("BR", "8b");
        ChannelMap.put("SWR", "8c");
        ChannelMap.put("ZDF", "22a");
        ChannelMap.put("3Sat", "22b");
        ChannelMap.put("ZDFinfo" "22c");
        ChannelMap.put("KiKa", "22d");
        ChannelMap.put("RTL", "34a");
        ChannelMap.put("RTL2", "34b");
        ChannelMap.put("Super RTL", "34c");
        ChannelMap.put("Vox", "34d");
        ChannelMap.put("Das Erste", "37a");
        ChannelMap.put("hr", "37b");
        ChannelMap.put("arte", "37c");*/
    }

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SubPage01.
     */
    // TODO: Rename and change types and number of parameters
    public static SubPage01 newInstance(String param1, String param2) {
        SubPage01 fragment = new SubPage01();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        initializeHttpRequest();
        fillChannelContainer();

    }

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

        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.fragment_sub_page01, container, false);
        View v = inflater.inflate(R.layout.fragment_sub_page01, container, false);

        Button b1 = (Button) v.findViewById(R.id.right_triangle_button);
        b1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.right_triangle_button: {
                        if (onChannel == 14) {
                            onChannel = 1;
                        } else {
                            onChannel = onChannel + 1;
                        }
                        String tmpString = String.valueOf(onChannel);
                        try {
                            httpRequest.execute("channelMain=" + ChannelMap.get(tmpString));
                            System.out.println(ChannelMap.get(tmpString));
                        } catch (IOException | JSONException | IllegalArgumentException e) {
                        }
                    }
                }
            }
        });

        Button b2 = (Button) v.findViewById(R.id.left_triangle_button);
        b2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.left_triangle_button: {
                        if (onChannel == 1)

                        {
                            onChannel = 14;
                        } else

                        {
                            onChannel = onChannel - 1;
                        }

                        String tmpString = String.valueOf(onChannel);
                        try

                        {
                            httpRequest.execute("channelMain=" + ChannelMap.get(tmpString));
                            System.out.println(ChannelMap.get(tmpString));
                        } catch (IOException | JSONException |
                                IllegalArgumentException e)

                        {
                        }
                    }
                }
            }
        });

        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        button_tri_right = (Button) getView().findViewById(R.id.right_triangle_button); //this is necessary because you can't
        button_tri_left = (Button) getView().findViewById(R.id.left_triangle_button);   //use findViewById() directly, like in
        //activities.
    }

    /*// TODO: Rename method, update argument and hook method into UI event
    public void onButtonRightPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
        String tmpString = String.valueOf(onChannel);
        try {
            httpRequest.execute("channelMain=" + ChannelMap.get(tmpString));
        } catch (IOException | JSONException | IllegalArgumentException e) {
        }
        onChannel = onChannel + 1;
    }

    public void onButtonLeftPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
        String tmpString = String.valueOf(onChannel);
        try {
            httpRequest.execute("channelMain=" + ChannelMap.get(tmpString));
            System.out.println(ChannelMap.get(tmpString));
        } catch (IOException | JSONException | IllegalArgumentException e) {
        }
        onChannel = onChannel + 1;
    }*/

    @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;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

}

fragment_sub_page01.xml

<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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="layout.SubPage01">

    <Button
        android:id="@+id/left_triangle_button"
        android:layout_width="60dp"
        android:layout_height="80dp"
        android:layout_gravity="center"
        android:layout_marginStart="-100dp"
        android:background="@drawable/triangle_button_left"
        android:clickable="true"
        app:backgroundTint="#076a24" />

    <Button
        android:id="@+id/right_triangle_button"
        android:layout_width="60dp"

        android:layout_height="80dp"
        android:layout_gravity="center"
        android:layout_marginStart="100dp"
        android:background="@drawable/triangle_button_right"
        android:clickable="true"
        android:onClick="onClick"
        app:backgroundTint="#076a24" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Sendung"
        android:layout_gravity="center"
        android:layout_marginTop="-100dp"
        />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Sender"
        android:layout_gravity="center"
        android:layout_marginTop="-150dp" />

    <EditText
        android:id="@+id/editText"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:ems="4"
        android:hint="Nr."
        android:inputType="number"
        android:textAlignment="center" />

</FrameLayout>

I tried some possible solutions but didn't manage to resolve my problem.

Thanks in advance.

Edit: the talk is about buttons:

left_triangle_button

right_triangle_button


问:
Difference between exit() and sys.exit() in Python
In Python, there are two similarly-named functions, exit() and sys.exit(). What's the difference and when should I use one over the other?

答:
If I use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing.
See here

But sys.exit() is better in this case. It closes the program and doesn't create any dialogue box.


问:
In Angular for which arrtributes we have to use parentheses and for which we have to use bracket
I am a bit confused about using parentheses and brackets on attributes in Angular.</p>

```<code><form [formGroup]="vform" (ngSubmit)="onSubmit(vform.value)">
  <input type="text" name="uname" placeholder="User Name" formControlName="uname">
  <input type="text" name="fname" placeholder="Full Name" formControlName="fname">
  <input type="submit" [disabled]="!vform.valid" value="Submit">
</form>
</code>```

答:
[] is for binding from a value.It allows to pass objects.

```<code><div [allowed]="allowed"></div>
</code>```

() is for binding an event handler to be called when a DOM event is fired

```<code><date-comp [title]="childTitle" (notify)="onNotification($event)"></date-comp>
</code>```

Refer What is the difference between parentheses, brackets and asterisks in Angular2?

Body:
I am a bit confused about using parentheses and brackets on attributes in Angular.

<form [formGroup]="vform" (ngSubmit)="onSubmit(vform.value)">
  <input type="text" name="uname" placeholder="User Name" formControlName="uname">
  <input type="text" name="fname" placeholder="Full Name" formControlName="fname">
  <input type="submit" [disabled]="!vform.valid" value="Submit">
</form>

Body:
[] is for binding from a value.It allows to pass objects.

<div [allowed]="allowed"></div>

() is for binding an event handler to be called when a DOM event is fired

<date-comp [title]="childTitle" (notify)="onNotification($event)"></date-comp>

Refer What is the difference between parentheses, brackets and asterisks in Angular2?


问:
wtfform validation stops working when html form action set to return following page
I've set up DataRequired validation in two wtform components which comprise a SelectField and a StringField.

The information input by the user on the index page is then intended to carry into the following results page.

The validation works when the form action attribute in the index.html file is set to "". However, the inputted form data is not stored in a variable and carried to the results in this scenario (the table field on the results page show "None").

However, when the form action attribute in index.html is set to results the inputed field data Is stored and carried over to the results page, but DataRequired validation no longer takes place, presumably because the html action attribute bypasses the if form.validate_on_submit() in the views.py file.

Here are the index.html,forms.py and views.py files for reference. How can I find a way for the validation to work AND the inputted data to carry over to the results page?

views.py file:

```<code>####Index Page
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
        exception = ""
        try:
            connectToDB()
        except:
            exception = 'Failure to connect to db'
        form = StaffNames()
        if not exception:
                if form.validate_on_submit():
                        return redirect('/results')
        return render_template('index.html',title='Search Page',exception=exception,form=form)

#####Results Page
@app.route('/results', methods=['GET', 'POST'])
def results():
        form =StaffNames()
        return render_template('results.html',
                           title='Results', form=form, staff_name = dict(staff_choices).get(form.staff.data))
</code>```

index.html:

```<code><form action="" method="post" name="index">
        <p> {{ form.hidden_tag() }} </p>
        <p>{{ form.ranumber }} Enter RA Number</p>
        {% for error in form.ranumber.errors %}
         <span style="color: red;">[{{ error }}]</span>
          {% endfor %}<br>
        <p>{{ form.staff }} Select your name</p>
        {% for error in form.staff.errors %}
         <span style="color: red;">[{{ error }}]</span>
          {% endfor %}<br>

        <p><input type="submit" value="Search"></p>
    </form>
</code>```

forms.py:

```<code>from flask_wtf import Form
from wtforms import StringField, SelectField
from wtforms.validators import DataRequired

staff_choices=[("", ""), ('1', 'John Jones'), ('2', 'Chris Hughes'), ('            3', 'Lyn Tony')]
class StaffNames(Form):
        ranumber = StringField('ranumber', validators=[DataRequired()])
        staff = SelectField('staff',choices=staff_choices,validators=[DataRequired()])
</code>```

答:
Have you tried to pass the form data as query string?

```<code>####Index Page
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
        exception = ""
        try:
            connectToDB()
        except:
            exception = 'Failure to connect to db'

        form = StaffNames()
        if not exception:
            if form.validate_on_submit():
                query = {
                    'staff': form.staff.data,
                    'ranumber': form.ranumber.data
                }
                return redirect(url_for('results', **query))

        return render_template(
            'index.html', title='Search Page', exception=exception, form=form
        )

#####Results Page
from flask import request

@app.route('/results')
def results():
    ranumber = request.args.get('ranumber', None)
    staff = request.args.get('staff', None)

    return render_template(
        'results.html', title='Results', staff=staff, ranumber=ranumber
    )
</code>```

This way you can skip form's action attribute altogether

```<code><form method="post" name="index">
...
</form>
</code>```

Body:
I've set up DataRequired validation in two wtform components which comprise a SelectField and a StringField.

The information input by the user on the index page is then intended to carry into the following results page.

The validation works when the form action attribute in the index.html file is set to "". However, the inputted form data is not stored in a variable and carried to the results in this scenario (the table field on the results page show "None").

However, when the form action attribute in index.html is set to results the inputed field data Is stored and carried over to the results page, but DataRequired validation no longer takes place, presumably because the html action attribute bypasses the if form.validate_on_submit() in the views.py file.

Here are the index.html,forms.py and views.py files for reference. How can I find a way for the validation to work AND the inputted data to carry over to the results page?

views.py file:

####Index Page
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
        exception = ""
        try:
            connectToDB()
        except:
            exception = 'Failure to connect to db'
        form = StaffNames()
        if not exception:
                if form.validate_on_submit():
                        return redirect('/results')
        return render_template('index.html',title='Search Page',exception=exception,form=form)

#####Results Page
@app.route('/results', methods=['GET', 'POST'])
def results():
        form =StaffNames()
        return render_template('results.html',
                           title='Results', form=form, staff_name = dict(staff_choices).get(form.staff.data))

index.html:

<form action="" method="post" name="index">

 {{ form.hidden_tag() }}

{{ form.ranumber }} Enter RA Number

        {% for error in form.ranumber.errors %}
         [{{ error }}]
          {% endfor %}

{{ form.staff }} Select your name

        {% for error in form.staff.errors %}
         [{{ error }}]
          {% endfor %}

<input type="submit" value="Search">

    </form>

forms.py:

from flask_wtf import Form
from wtforms import StringField, SelectField
from wtforms.validators import DataRequired

staff_choices=[("", ""), ('1', 'John Jones'), ('2', 'Chris Hughes'), ('            3', 'Lyn Tony')]
class StaffNames(Form):
        ranumber = StringField('ranumber', validators=[DataRequired()])
        staff = SelectField('staff',choices=staff_choices,validators=[DataRequired()])

Body:
Have you tried to pass the form data as query string?

####Index Page
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
        exception = ""
        try:
            connectToDB()
        except:
            exception = 'Failure to connect to db'

        form = StaffNames()
        if not exception:
            if form.validate_on_submit():
                query = {
                    'staff': form.staff.data,
                    'ranumber': form.ranumber.data
                }
                return redirect(url_for('results', **query))

        return render_template(
            'index.html', title='Search Page', exception=exception, form=form
        )

#####Results Page
from flask import request

@app.route('/results')
def results():
    ranumber = request.args.get('ranumber', None)
    staff = request.args.get('staff', None)

    return render_template(
        'results.html', title='Results', staff=staff, ranumber=ranumber
    )

This way you can skip form's action attribute altogether

<form method="post" name="index">
...
</form>


问:
Slow performance of Kendo Grid in IE11
I've been using latest Kendo grid for ASP.NET MVC.

Data table specs are like this,

columns --> 25 to 35.

rows --> anywhere between 1500 to 5000.

client side paging --> 20 rows

Issue is, when I'm doing the scrolling, IE 11 takes upto 1s to display data depending on screen resolution and grid content height. Which causes the UI glitch.

When I ran IE UI Responsiveness from Dev Tools, I got the below results.

I get that whenever user does scrolling, browsers have to render the rows and it takes a bit time. But IE 11 takes it to a whole new level. The moment it has to process 3-4 more rows, it starts acting jumpy and glitchy.

I did the testing in Chrome (& opera), Firefox. In which performace was very decent.

I tried to refractor CSS to reduce styling, but there's very little bit change I could afford.

Please let me know what is the next step? Should I keep calm and blame IE?

答:
The grid works fine on its own in IE11, my team uses it.
It could be you've added some code that's being executed excessively.

The UI responsiveness tool isn't very useful. Try using the profiler in IE's Dev tools. Open the page with the problematic grid in it, hit the green arrow of the profiler to start recording, scroll the grid a bit and then hit stop in the profiler.

Sort the results by Count, Inclusive time and Exclusive time and see what stands out. After each sort look at the top ~50 entries for code you wrote.

When sorting by Count, you might find a piece of code that while is pretty short, it runs hundreds of thousands of times in a loop for no reason because of a simple mistake.

Sorting by time can show you pieces of code that are very demanding and perhaps could be moved to other places.

For instance, it could be you're running some logic on the view like formatting a date. If you see such a function in the profiler, it would be better to move this logic to the data fetching phase before the view is rendered.

Title: Slow performance of Kendo Grid in IE11


问:
Android SDK installation doesn't find JDK
I'm trying to install the Android SDK on my Windows 7 x64 System.

jdk-6u23-windows-x64.exe is installed, but the Android SDK setup refuses to proceed because it doesn't find the JDK installation.

Is this a known issue? And is there a solution?

答: Try downloading and installing the zipped version rather than the .exe installer.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Bulk Insertion in Laravel using eloquent ORM
How can we perform bulk database insertions in Laravel using Eloquent ORM?

I am working with an XML document, looping through its elements. I want to accomplish something like this in Laravel:

$sXML = download_page('http://remotepage.php&function=getItems&count=100&page=1');
$oXML = new SimpleXMLElement($sXML);
$query = "INSERT INTO tbl_item (first_name, last_name, date_added) VALUES";
foreach($oXML->results->item->item as $oEntry){
    $query .=  "('" . $oEntry->firstname . "', '" . $oEntry->lastname . "', '" . date("Y-m-d H:i:s") . "'),";
}
mysql_query($query);
```

but I am getting the following error.

SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters.

答:
This is how you do it in more Eloquent way,</p>
```<code>    $allinterests = [];
    foreach($interests as $item){ // $interests array contains input data
        $interestcat = new User_Category();
        $interestcat->memberid = $item->memberid;
        $interestcat->catid = $item->catid;
        $allinterests[] = $interestcat->attributesToArray();
    }
    User_Category::insert($allinterests);
</code>```

Body:
How can we perform bulk database insertions in Laravel using Eloquent ORM?

I am working with an XML document, looping through its elements. I want to accomplish something like this in Laravel:

$sXML = download_page('http://remotepage.php&function=getItems&count=100&page=1');
$oXML = new SimpleXMLElement($sXML);
$query = "INSERT INTO tbl_item (first_name, last_name, date_added) VALUES";
foreach($oXML->results->item->item as $oEntry){
    $query .=  "('" . $oEntry->firstname . "', '" . $oEntry->lastname . "', '" . date("Y-m-d H:i:s") . "'),";
}
mysql_query($query);

but I am getting the following error.

SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters.

Body:
This is how you do it in more Eloquent way,

    $allinterests = [];
    foreach($interests as $item){ // $interests array contains input data
        $interestcat = new User_Category();
        $interestcat->memberid = $item->memberid;
        $interestcat->catid = $item->catid;
        $allinterests[] = $interestcat->attributesToArray();
    }
    User_Category::insert($allinterests);


问:
Sort Array by highest value google script
I have the following spreadsheet:

```<code>| Name | Rating |
| John | 2000   |
| Jane | 50     |
| Bill | 3000   |
| Sam  | 500    |
</code>```

I get the data for the spreadsheet in the following way:

```<code>mySheet.getDataRange().getValues();
</code>```

My goal is to print the array from highest rating to lowest rating. How can I do that?

EDIT: I probably should mention I am aware of the sort function: However, the issue there is it sorts as a string, not a number. Which means that 60 will show above 2000 because it starts with a 6.

答:
You need to pass a comparator function to the sort() method.

```<code>function sortDescending() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var range = sheet.getRange(2, 1, sheet.getLastRow() - 1, sheet.getLastColumn());
  var values = range.getValues();

  values.sort(function(a, b){

  return b[1] - a[1]; //sorts by the 2nd element in a row

  });

  Logger.log(values);
  }
</code>```

Note that I skipped the header row and didn't include it in the list of values to sort. Hope this helps.

Body:
I have the following spreadsheet:

| Name | Rating |
| John | 2000   |
| Jane | 50     |
| Bill | 3000   |
| Sam  | 500    |

I get the data for the spreadsheet in the following way:

mySheet.getDataRange().getValues();

My goal is to print the array from highest rating to lowest rating. How can I do that?

EDIT: I probably should mention I am aware of the sort function: However, the issue there is it sorts as a string, not a number. Which means that 60 will show above 2000 because it starts with a 6.

Body:
You need to pass a comparator function to the sort() method.

function sortDescending() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var range = sheet.getRange(2, 1, sheet.getLastRow() - 1, sheet.getLastColumn());
  var values = range.getValues();

  values.sort(function(a, b){

  return b[1] - a[1]; //sorts by the 2nd element in a row

  });

  Logger.log(values);
  }

Note that I skipped the header row and didn't include it in the list of values to sort. Hope this helps.


问:
SQL Server: Check Upper Case or Lower Case after certain Character
I have data like 'John is my name; Ram is my name; Adam is my name'.

My rule is such that every first letter that comes after ; should be capital letter.

How do I select all values that satisfy the rule?

答:
you can create a function like this.

```<code>Create FUNCTION SPLITTER (
    @textData NVARCHAR(MAX),
    @Delimeter NVARCHAR(MAX) ) RETURNS @RtnValue TABLE  (
    Data NVARCHAR(MAX) )  AS BEGIN
    DECLARE @index INT  DECLARE @data nvarchar(1000)    DECLARE @firstCharacter char
    SET @index = CHARINDEX(@Delimeter,@textData)

    WHILE (@index>0)
    BEGIN
                set @data = LTRIM(RTRIM(SUBSTRING(@textData, 1, @index - 1)))       set @firstCharacter = SUBSTRING(@data,1,1);
                if UNICODE(@firstCharacter) = UNICODE(upper(@firstCharacter))       begin           INSERT INTO @RtnValue (data) SELECT @data       end;

        SET @textData = SUBSTRING(@textData, @index + DATALENGTH(@Delimeter) / 2, LEN(@textData))

        SET @index = CHARINDEX(@Delimeter, @textData)
    END
        set @data = @textData   set @firstCharacter = SUBSTRING(@data,1,1);
            if UNICODE(@firstCharacter) = UNICODE(upper(@firstCharacter))   begin       INSERT INTO @RtnValue (data) SELECT @data   end;

    RETURN END
</code>```

use it like this

select * from SPLITTER ('John is my name; Ram is my name; Adam is my name', ';')

Body:
you can create a function like this.

Create FUNCTION SPLITTER (
    @textData NVARCHAR(MAX),
    @Delimeter NVARCHAR(MAX) ) RETURNS @RtnValue TABLE  (
    Data NVARCHAR(MAX) )  AS BEGIN
    DECLARE @index INT  DECLARE @data nvarchar(1000)    DECLARE @firstCharacter char
    SET @index = CHARINDEX(@Delimeter,@textData)

    WHILE (@index>0)
    BEGIN
                set @data = LTRIM(RTRIM(SUBSTRING(@textData, 1, @index - 1)))       set @firstCharacter = SUBSTRING(@data,1,1);
                if UNICODE(@firstCharacter) = UNICODE(upper(@firstCharacter))       begin           INSERT INTO @RtnValue (data) SELECT @data       end;

        SET @textData = SUBSTRING(@textData, @index + DATALENGTH(@Delimeter) / 2, LEN(@textData))

        SET @index = CHARINDEX(@Delimeter, @textData)
    END
        set @data = @textData   set @firstCharacter = SUBSTRING(@data,1,1);
            if UNICODE(@firstCharacter) = UNICODE(upper(@firstCharacter))   begin       INSERT INTO @RtnValue (data) SELECT @data   end;

    RETURN END

use it like this

select * from SPLITTER ('John is my name; Ram is my name; Adam is my name', ';')


问:
how to avoid parent view controller rotating
I have parent viewcontroller - in portrait.
I have child viewcontroller - in landscape.
When child viewcontroller is dismissed parent viewcontroller remains in landscape- which it should not do. Please advice :=)
These are the settings:
deployment info

My app delegate

```<code>-(UIInterfaceOrientationMask)application:(UIApplication *)application    supportedInterfaceOrientationsForWindow:(UIWindow *)window {
   UIViewController* topVC = [self getTopController];
     if ([topVC isKindOfClass: [childVideoViewController class]]) {
         return UIInterfaceOrientationMaskLandscape;
     }
     return UIInterfaceOrientationMaskPortrait;
}

-(UIViewController*) getTopController{ UIViewController *topViewController =      [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topViewController.presentedViewController) {
        topViewController = topViewController.presentedViewController;
    }
    return topViewController;
}
</code>```

答:
When You back from child view controller you should call
Create a method in your child view controller and implement this

```<code>- (void)setScreenOrientation:(UIInterfaceOrientation)orientation
{
UIDeviceOrientation deviceOrientation = (UIDeviceOrientation) orientation;
[[UIDevice currentDevice] setValue: [NSNumber numberWithInteger: deviceOrientation] forKey:@"orientation"];
}
</code>```

Call this from child view before dismiss:

```<code>    [self setScreenOrientation:UIInterfaceOrientationPortrait];

    [self dismissViewControllerAnimated:YES completion:nil];
</code>```

Body:
I have parent viewcontroller - in portrait.
I have child viewcontroller - in landscape.
When child viewcontroller is dismissed parent viewcontroller remains in landscape- which it should not do. Please advice :=)
These are the settings:
deployment info

My app delegate

-(UIInterfaceOrientationMask)application:(UIApplication *)application    supportedInterfaceOrientationsForWindow:(UIWindow *)window {
   UIViewController* topVC = [self getTopController];
     if ([topVC isKindOfClass: [childVideoViewController class]]) {
         return UIInterfaceOrientationMaskLandscape;
     }
     return UIInterfaceOrientationMaskPortrait;
}

-(UIViewController*) getTopController{ UIViewController *topViewController =      [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topViewController.presentedViewController) {
        topViewController = topViewController.presentedViewController;
    }
    return topViewController;
}

Body:
When You back from child view controller you should call
Create a method in your child view controller and implement this

- (void)setScreenOrientation:(UIInterfaceOrientation)orientation
{
UIDeviceOrientation deviceOrientation = (UIDeviceOrientation) orientation;
[[UIDevice currentDevice] setValue: [NSNumber numberWithInteger: deviceOrientation] forKey:@"orientation"];
}

Call this from child view before dismiss:

    [self setScreenOrientation:UIInterfaceOrientationPortrait];

    [self dismissViewControllerAnimated:YES completion:nil];


问:
How to insert a firebase server timestamp using the iOS SDK in Swift project
In the "Offline Capabilities" section of the iOS guide it mentions kFirebaseServerValueTimestamp, which doesn't seem to work in a Swift project (auto complete doesn't prompt it).

I tried [".sv": "timestamp"] as the Swift example did. But it complains that this can not be set with other values and has to be the only value for at the given path.

I tried:

```<code>ref.childByAutoId().setValue(["text": "foobar", ".sv": "timestamp"], withCompletionBlock: {...}
</code>```

And it gave me the error that ".sv" can't be saved with other value.

What I wanted to do is to save the createdAt timestamp along with other values for the object. And I'd prefer to use the server time to avoid client clock skew.

How can I do that?

答:
As of Firebase 4.0 you can use ServerValue.timestamp()

for example:

```<code>    let ref = Database.database().reference().child("userExample")
    let values = ["firstName": "Joe", "lastName": "Bloggs", "timestamp": ServerValue.timestamp()] as [String : Any]

    ref.updateChildValues(values) { (err, ref) in

        if let err = err {
            print("failed to upload user data", err)
            return
        }

    }
</code>```

Body:
In the "Offline Capabilities" section of the iOS guide it mentions kFirebaseServerValueTimestamp, which doesn't seem to work in a Swift project (auto complete doesn't prompt it).

I tried [".sv": "timestamp"] as the Swift example did. But it complains that this can not be set with other values and has to be the only value for at the given path.

I tried:

ref.childByAutoId().setValue(["text": "foobar", ".sv": "timestamp"], withCompletionBlock: {...}

And it gave me the error that ".sv" can't be saved with other value.

What I wanted to do is to save the createdAt timestamp along with other values for the object. And I'd prefer to use the server time to avoid client clock skew.

How can I do that?

Body:
As of Firebase 4.0 you can use ServerValue.timestamp()

for example:

    let ref = Database.database().reference().child("userExample")
    let values = ["firstName": "Joe", "lastName": "Bloggs", "timestamp": ServerValue.timestamp()] as [String : Any]

    ref.updateChildValues(values) { (err, ref) in

        if let err = err {
            print("failed to upload user data", err)
            return
        }

    }


问:
Transform a list to a list of average values (by step)
I have a two dimensional list of values:

```<code>[
[[12.2],[5325]],
[[13.4],[235326]],
[[15.9],[235326]],
[[17.7],[53521]],
[[21.3],[42342]],
[[22.6],[6546]],
[[25.9],[34634]],
[[27.2],[523523]],
[[33.4],[235325]],
[[36.2],[235352]]
]
</code>```

I would like to get a list of averages defined by a given step so that for a step=10 it would like like this:

```<code>[
[[10],[average of all 10-19]],
[[20],[average of all 20-29]],
[[30],[average of all 30-39]]
]
</code>```

How can I achieve that? Please note that the number of 10s, 20s, 30s and so on is not always the same.

Body:
I have a two dimensional list of values:

[
[[12.2],[5325]],
[[13.4],[235326]],
[[15.9],[235326]],
[[17.7],[53521]],
[[21.3],[42342]],
[[22.6],[6546]],
[[25.9],[34634]],
[[27.2],[523523]],
[[33.4],[235325]],
[[36.2],[235352]]
]

I would like to get a list of averages defined by a given step so that for a step=10 it would like like this:

[
[[10],[average of all 10-19]],
[[20],[average of all 20-29]],
[[30],[average of all 30-39]]
]

How can I achieve that? Please note that the number of 10s, 20s, 30s and so on is not always the same.

Body:
import pandas as pd

df = pd.DataFrame((q[0][0], q[1][0]) for q in thelist)
df['group'] = (df[0] / 10).astype(int)

Now df is:

      0       1  group
0  12.2    5325      1
1  13.4  235326      1
2  15.9  235326      1
3  17.7   53521      1
4  21.3   42342      2
5  22.6    6546      2
6  25.9   34634      2
7  27.2  523523      2
8  33.4  235325      3
9  36.2  235352      3

Then:

df.groupby('group').mean()

Gives you the answers you seek:

           0       1
group
1      14.80  132374
2      24.25  151761
3      34.80  235338


问:
how to programmatically access the builtin properties of an open xml worddoc file
i would like to access some built in properties(like author,last modified date,etc.) of an open xml word doc file. i would like to use open xml sdk2.0 for this purpose. so i wonder if there is any class or any way i could programmatically access these builtin properties.</p>

答:
An explanation of the following method can be found here, but pretty much you need to pass in the properties that you want to get out of the core.xml file to this method and it will return the value: </p>

```<code>public static string WDRetrieveCoreProperty(string docName, string propertyName)
{
   // Given a document name and a core property, retrieve the value of the property.
   // Note that because this code uses the SelectSingleNode method,
   // the search is case sensitive. That is, looking for "Author" is not
   // the same as looking for "author".

   const string corePropertiesSchema = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
   const string dcPropertiesSchema = "http://purl.org/dc/elements/1.1/";
   const string dcTermsPropertiesSchema = "http://purl.org/dc/terms/";

   string propertyValue = string.Empty;

   using (WordprocessingDocument wdPackage = WordprocessingDocument.Open(docName, true))
   {
      // Get the core properties part (core.xml).
      CoreFilePropertiesPart corePropertiesPart = wdPackage.CoreFilePropertiesPart;

      // Manage namespaces to perform XML XPath queries.
      NameTable nt = new NameTable();
      XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
      nsManager.AddNamespace("cp", corePropertiesSchema);
      nsManager.AddNamespace("dc", dcPropertiesSchema);
      nsManager.AddNamespace("dcterms", dcTermsPropertiesSchema);

      // Get the properties from the package.
      XmlDocument xdoc = new XmlDocument(nt);

      // Load the XML in the part into an XmlDocument instance.
      xdoc.Load(corePropertiesPart.GetStream());

      string searchString = string.Format("//cp:coreProperties/{0}", propertyName);

      XmlNode xNode = xdoc.SelectSingleNode(searchString, nsManager);
      if (!(xNode == null))
      {
         propertyValue = xNode.InnerText;
      }
   }

   return propertyValue;
}
</code>```

Body:
An explanation of the following method can be found here, but pretty much you need to pass in the properties that you want to get out of the core.xml file to this method and it will return the value:

public static string WDRetrieveCoreProperty(string docName, string propertyName)
{
   // Given a document name and a core property, retrieve the value of the property.
   // Note that because this code uses the SelectSingleNode method,
   // the search is case sensitive. That is, looking for "Author" is not
   // the same as looking for "author".

   const string corePropertiesSchema = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
   const string dcPropertiesSchema = "http://purl.org/dc/elements/1.1/";
   const string dcTermsPropertiesSchema = "http://purl.org/dc/terms/";

   string propertyValue = string.Empty;

   using (WordprocessingDocument wdPackage = WordprocessingDocument.Open(docName, true))
   {
      // Get the core properties part (core.xml).
      CoreFilePropertiesPart corePropertiesPart = wdPackage.CoreFilePropertiesPart;

      // Manage namespaces to perform XML XPath queries.
      NameTable nt = new NameTable();
      XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
      nsManager.AddNamespace("cp", corePropertiesSchema);
      nsManager.AddNamespace("dc", dcPropertiesSchema);
      nsManager.AddNamespace("dcterms", dcTermsPropertiesSchema);

      // Get the properties from the package.
      XmlDocument xdoc = new XmlDocument(nt);

      // Load the XML in the part into an XmlDocument instance.
      xdoc.Load(corePropertiesPart.GetStream());

      string searchString = string.Format("//cp:coreProperties/{0}", propertyName);

      XmlNode xNode = xdoc.SelectSingleNode(searchString, nsManager);
      if (!(xNode == null))
      {
         propertyValue = xNode.InnerText;
      }
   }

   return propertyValue;
}


问:
How to stop a stage from closing when user selects close button?
I can add this code to hook into the stage close event:

```<code>stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    public void handle(WindowEvent we) {
        System.out.println("Stage is closing");
        // but wait! I don't want it to close!
    }
});
</code>```

but how do I stop the stage from closing?

答:
I refer to this comment:</p>

```<code>Platform.setImplicitExit(false);

primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent event) {
        event.consume();
    }
});
</code>```

Body:
I can add this code to hook into the stage close event:

stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    public void handle(WindowEvent we) {
        System.out.println("Stage is closing");
        // but wait! I don't want it to close!
    }
});

but how do I stop the stage from closing?

Body:
I refer to this comment:

Platform.setImplicitExit(false);

primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
    @Override
    public void handle(WindowEvent event) {
        event.consume();
    }
});


问:
Error while inserting MySQL with ASP.Net
I'm newbie to MySQL, I'm trying to check if the user exists in the database before inserting a record but I'm getting this error 1064,error in your SQL syntax.
MySQL statement

```<code>IF (SELECT count(*) FROM tvstream.t_users WHERE fb_id=`123456`)=0 THEN
Begin
  INSERT INTO `tvstream`.`t_users` (`fb_id` ,`user_name` ,`email` ,`gender`)
  Values (`123456`,`Daina`,`Daina@gmail.com`,`Female`)
End
</code>```

ASP Code

```<code>        StringBuilder SQL_Add = new StringBuilder("IF (SELECT count(*) FROM tvstream.t_users WHERE fb_id=`" + fb_id +"`)=0 THEN ");
        SQL_Add.Append("Begin ");
        SQL_Add.Append("INSERT INTO  `tvstream`.`t_users` (`fb_id` ,`user_name` ,`email` ,`gender`)");
        SQL_Add.Append(" Values (`" + fb_id + "`,`" + user_name + "`,`" + email + "`,`" + gender + "`)");
        SQL_Add.Append(" End");

        Response.Write(SQL_Add.ToString());
        MySqlConnection m_cnn = new MySqlConnection(myConnection);

        m_cnn.Open();
        MySqlCommand cmd = new MySqlCommand(SQL_Add.ToString());
        cmd.Connection = m_cnn;
        cmd.ExecuteNonQuery();
</code>```

Please advice and thank you

答:
You should make one sql query for checking the user existance, and another one for inserting a new user.

Checking:

```<code>SELECT count(*) FROM tvstream.t_users WHERE fb_id=`123456`
</code>```

Inserting:

```<code>  INSERT INTO `tvstream`.`t_users` (`fb_id` ,`user_name` ,`email` ,`gender`)
  Values (`123456`,`Daina`,`Daina@gmail.com`,`Female`)
</code>```

Basically you should run the first query, check the result, and the execute the insertion.

I you really need to do it completely by SQL-side, then you will need a stored procedure in you DB.

```<code>DELIMITER //

CREATE FUNCTION InsertUnique(fb_id VARCHAR(20), user_name VARCHAR(30), email VARCHAR(40), gender VARCHAR(10))
  RETURNS INT

  BEGIN
    DECLARE s INT;

    IF (SELECT count(*) FROM tvstream.t_users WHERE fb_id=`123456`)=0 THEN SET s = 1;
    ELSE SET s = 0;
    END IF;

    IF s = 0 THEN
        INSERT INTO `tvstream`.`t_users` (`fb_id` ,`user_name` ,`email` ,`gender`)
  Values (fb_id,user_name,email,gender)
    END IF;

    RETURN s;
  END //

DELIMITER ;
</code>```

I didn't check the syntax, it may need to be fixed.

Body:
I'm newbie to MySQL, I'm trying to check if the user exists in the database before inserting a record but I'm getting this error 1064,error in your SQL syntax.
MySQL statement

IF (SELECT count(*) FROM tvstream.t_users WHERE fb_id=`123456`)=0 THEN
Begin
  INSERT INTO `tvstream`.`t_users` (`fb_id` ,`user_name` ,`email` ,`gender`)
  Values (`123456`,`Daina`,`Daina@gmail.com`,`Female`)
End

ASP Code

        StringBuilder SQL_Add = new StringBuilder("IF (SELECT count(*) FROM tvstream.t_users WHERE fb_id=`" + fb_id +"`)=0 THEN ");
        SQL_Add.Append("Begin ");
        SQL_Add.Append("INSERT INTO  `tvstream`.`t_users` (`fb_id` ,`user_name` ,`email` ,`gender`)");
        SQL_Add.Append(" Values (`" + fb_id + "`,`" + user_name + "`,`" + email + "`,`" + gender + "`)");
        SQL_Add.Append(" End");

        Response.Write(SQL_Add.ToString());
        MySqlConnection m_cnn = new MySqlConnection(myConnection);

        m_cnn.Open();
        MySqlCommand cmd = new MySqlCommand(SQL_Add.ToString());
        cmd.Connection = m_cnn;
        cmd.ExecuteNonQuery();

Please advice and thank you

Body:
You should make one sql query for checking the user existance, and another one for inserting a new user.

Checking:

SELECT count(*) FROM tvstream.t_users WHERE fb_id=`123456`

Inserting:

  INSERT INTO `tvstream`.`t_users` (`fb_id` ,`user_name` ,`email` ,`gender`)
  Values (`123456`,`Daina`,`Daina@gmail.com`,`Female`)

Basically you should run the first query, check the result, and the execute the insertion.

I you really need to do it completely by SQL-side, then you will need a stored procedure in you DB.

DELIMITER //

CREATE FUNCTION InsertUnique(fb_id VARCHAR(20), user_name VARCHAR(30), email VARCHAR(40), gender VARCHAR(10))
  RETURNS INT

  BEGIN
    DECLARE s INT;

    IF (SELECT count(*) FROM tvstream.t_users WHERE fb_id=`123456`)=0 THEN SET s = 1;
    ELSE SET s = 0;
    END IF;

    IF s = 0 THEN
        INSERT INTO `tvstream`.`t_users` (`fb_id` ,`user_name` ,`email` ,`gender`)
  Values (fb_id,user_name,email,gender)
    END IF;

    RETURN s;
  END //

DELIMITER ;

I didn't check the syntax, it may need to be fixed.


答:
Use parentheses for binding to events like (click)="clickHandler()"

Use square brackets for binding to properties like [disabled]="true"

Use both (referred to as football in a box) for two-way binding like [(ngModel)]="attr"

Title: In Angular for which arrtributes we have to use parentheses and for which we have to use bracket

Body:
I am a bit confused about using parentheses and brackets on attributes in Angular.

<form [formGroup]="vform" (ngSubmit)="onSubmit(vform.value)">
  <input type="text" name="uname" placeholder="User Name" formControlName="uname">
  <input type="text" name="fname" placeholder="Full Name" formControlName="fname">
  <input type="submit" [disabled]="!vform.valid" value="Submit">
</form>


问:
Align hex number next to them
I need some help for a script. I have hex number like and I need to align next to them, but I have no idea how to solve this with a nice way in c++.

For example I have this array:

```<code>int test[3]={0x12,0x13,0xab};
</code>```

So and I would like to have this Output:

```<code>0x1213ab
</code>```

答:
You can easily do that

```<code>#include <iostream>
#include <iomanip>

int main() {
    int test[3] = {0x12,0x13,0xab};

    std::cout << "0x";
    for(auto x : test) {
        std::cout << std::hex << std::setw(2) << std::setfill('0') << x;
                  // |           |               |
                  // |           |               v
                  // |           |               Prevents filling blanks
                  // |           v
                  // |           Chooses a field output size of 2
                  // v
                  // Provides hex formatting of integers
    }
    std::cout << std::endl;
}
</code>```

See Live Demo

Relevant links from a good c++ reference documentation:

Input/output library

Input/output manipulators

Title: Align hex number next to them

Body:
I need some help for a script. I have hex number like and I need to align next to them, but I have no idea how to solve this with a nice way in c++.

For example I have this array:

int test[3]={0x12,0x13,0xab};

So and I would like to have this Output:

0x1213ab

Body:
You can easily do that

#include <iostream>
#include <iomanip>

int main() {
    int test[3] = {0x12,0x13,0xab};

    std::cout << "0x";
    for(auto x : test) {
        std::cout << std::hex << std::setw(2) << std::setfill('0') << x;
                  // |           |               |
                  // |           |               v
                  // |           |               Prevents filling blanks
                  // |           v
                  // |           Chooses a field output size of 2
                  // v
                  // Provides hex formatting of integers
    }
    std::cout << std::endl;
}

See Live Demo

Relevant links from a good c++ reference documentation:

Input/output library

Input/output manipulators


问:
Looking for Android dashboard-like widget library
I would like to build an Android app showing a dashboard with many different graphical indicators. Have you already used a library containing these items?
Can anyone help me in this?

Thanks in advance and greetings
c.

答:
One approach you could take is to create your gauges and dashboard using CSS, HTML, and JavaScript which would be stored locally in your application's assets folder.  You can then use a WebView to display them.

WebView.addJavaScriptInterface [(link)][1] will allow you to pass data between your Android Java code and the JavaScript dashboard.

The reason I suggest this is that I think you will find more options for the graphical indicators if you look for JavaScript/HTML/CSS based ones.  Here are a couple examples:

http://techoctave.com/c7/posts/17-jquery-dashboard-gauges-using-raphael-xhtml-and-css

http://www.netzgesta.de/gauge/

If this is done well, the user would not be able to tell that your UI is not made with native widgets.  If you decide to go down this path, you may also want to consider using a framework like PhoneGap to help with the Java <-> JavaScript communications.

[1]: http://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String)


问:
Highcharts chart resize on window resize event after setting a specific size
In an app that I work I have this scenario:
In a responsive container I have a chart. This container is resized at a point and I need to change the chart size by calling the setSize method.
But after that I want to make the chart responsive again - to resize on window resize event.

I made a fiddle to demo this:
http://jsfiddle.net/7ka4qaef/
First click on the red button, then try to resize the window.
Is there anyway to 'forget' that I've used setSize method?

答:
i use update function to solve this problem.</p>

```<code>this.$refs.highcharts.chart.update({
  chart: {
    width: undefined,
    height: undefined,
  },
});
</code>```

Body:
i use update function to solve this problem.

this.$refs.highcharts.chart.update({
  chart: {
    width: undefined,
    height: undefined,
  },
});


问:
How to set same height and width of image using css? Not background image
I have to set images with same height and width.I have three images with different height and width. I have to display the same size in the box. Would you help me in this?

ul {
  list-style: none;
}

ul li {
  width: 200px;
  height: 200px;
  display: inline-block;
  border: 1px solid #000;
}

ul li img {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li><img src="http://i.imgur.com/tI5jq2c.jpg"></li>
  <li><img src="http://i.imgur.com/37w80TG.jpg"></li>
  <li><img src="http://i.imgur.com/B1MCOtx.jpg"></li>
</ul></code>```

答:
add constant height to your images

ul {
  list-style: none;
}

ul li {
  width: 200px;
  height: 200px;
  display: inline-block;
  border: 1px solid #000;
}

ul li img {
  width: 100%;
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li><img src="http://i.imgur.com/tI5jq2c.jpg"></li>
  <li><img src="http://i.imgur.com/37w80TG.jpg"></li>
  <li><img src="http://i.imgur.com/B1MCOtx.jpg"></li>
</ul></code>```

Body:
add constant height to your images

ul {
  list-style: none;
}

ul li {
  width: 200px;
  height: 200px;
  display: inline-block;
  border: 1px solid #000;
}

ul li img {
  width: 100%;
  height: 200px;
}

<ul>
  <li><img src="http://i.imgur.com/tI5jq2c.jpg"></li>
  <li><img src="http://i.imgur.com/37w80TG.jpg"></li>
  <li><img src="http://i.imgur.com/B1MCOtx.jpg"></li>
</ul>


问:
PySpark computation of weekly occurrences
I am trying to compute the weekly occurrences of a word. That is, whether each word is more frequent this week than the previous week. For that I am kind of stuck. I did the following:

```<code>m = sc.parallelize(["oded,12-12-2018", "oded,12-03-2018", "oded,12-12-2018", "oded,12-06-2018", "oded2,12-02-2018", "oded2,12-02-2018"])
        m = m.map(lambda line: line.split(','))
        weekly = m.map(lambda line: (line[0], (parse(line[1]).strftime("%V%y"))))
        s = sql.createDataFrame(daily)
        s.groupby("_1", "_2").count().sort("_2")
</code>```

the result is:

```<code>+-----+----+-----+
|   _1|  _2|count|
+-----+----+-----+
|oded2|4818|    2|
| oded|4918|    2|
| oded|5018|    2|
+-----+----+-----+
</code>```

How can I go and get oded: 0  = ( 2 - 2 ) and oded2: 2 = (2 - 0)

答:
Hi you can use lag window function to find value from previous week , after you count words peer week. For weeks that don't have previous value value for count will be zero or you can use na.drop() to remove that lines completely.</p>

```<code>from pyspark.sql.functions import lag, col,coalesce
from pyspark.sql.window import Window
w = Window().partitionBy("_1").orderBy(col("_2"))
s.select("*", lag("count").over(w).alias("prev_week")).na.fill(0).show()
</code>```

Body:
I am trying to compute the weekly occurrences of a word. That is, whether each word is more frequent this week than the previous week. For that I am kind of stuck. I did the following:

m = sc.parallelize(["oded,12-12-2018", "oded,12-03-2018", "oded,12-12-2018", "oded,12-06-2018", "oded2,12-02-2018", "oded2,12-02-2018"])
        m = m.map(lambda line: line.split(','))
        weekly = m.map(lambda line: (line[0], (parse(line[1]).strftime("%V%y"))))
        s = sql.createDataFrame(daily)
        s.groupby("_1", "_2").count().sort("_2")

the result is:

+-----+----+-----+
|   _1|  _2|count|
+-----+----+-----+
|oded2|4818|    2|
| oded|4918|    2|
| oded|5018|    2|
+-----+----+-----+

How can I go and get oded: 0  = ( 2 - 2 ) and oded2: 2 = (2 - 0)

Body:
Hi you can use lag window function to find value from previous week , after you count words peer week. For weeks that don't have previous value value for count will be zero or you can use na.drop() to remove that lines completely.

from pyspark.sql.functions import lag, col,coalesce
from pyspark.sql.window import Window
w = Window().partitionBy("_1").orderBy(col("_2"))
s.select("*", lag("count").over(w).alias("prev_week")).na.fill(0).show()