问:
android.view.View android.view.View.findViewById(int)' on a null object reference
i have a problem. when i compile always get error like bellow. so i hope there is someone who can help to understand this problem. when i open the activity always stack... please help me.

SettingAct.JAVA

```<code>package com.solusiwebmaster.antrian;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.Toast;
import com.solusiwebmaster.antrian.SettingAct_ViewHelper.SettingActViewInterface;
import tools.AntrianConfig;
import tools.AntrianHelper;
import tools.AntrianHelper.AntrianChanged;

public class SettingAct extends Activity {
    AntrianHelper antrianHelper;
    AntrianConfig antrianconfig;
    EditText et_antrian;
    EditText et_loket;
    LayoutInflater inflater;
    private Boolean settingchanged = Boolean.valueOf(false);
    SettingActViewInterface settingviewInterface = new C06411();
    SharedPreferences sharedpref;
    TableLayout table;
    SettingAct_ViewHelper viewhelpersetting;

    class C06411 implements SettingActViewInterface {
        C06411() {
        }

        public void setServerPort(int port) {
            if (SettingAct.this.antrianconfig.port != port && (port+"").length() >= 4) {
                SettingAct.this.antrianconfig.port = port;
                SettingAct.this.settingchanged = Boolean.valueOf(true);
            }
        }

        public void setServerAddress(String s) {
            if (!SettingAct.this.antrianconfig.serverAddress.equals(s)) {
                SettingAct.this.antrianconfig.serverAddress = s;
                SettingAct.this.settingchanged = Boolean.valueOf(true);
            }
        }

        public void setPlaySoundAt(int i) {
            SettingAct.this.antrianconfig.playSoundAt = i;
            SettingAct.this.settingchanged = Boolean.valueOf(true);
        }

        public void setLoket(int loket) {
            if (SettingAct.this.antrianconfig.loket != loket) {
                SettingAct.this.antrianconfig.loket = loket;
                SettingAct.this.settingchanged = Boolean.valueOf(true);
            }
        }

        public void setAppMode(int i) {
            System.out.println("apasih appmodenya : " + i + "servernya " + AntrianConfig.M_SERVER);
            SettingAct.this.antrianconfig.appMode = i;
            SettingAct.this.settingchanged = Boolean.valueOf(true);
            SettingAct.this.viewhelpersetting.addAllsettingChild();
        }

        public void setAntrian(int _antrian) {
            SettingAct.this.antrianHelper.setAntrian(_antrian);
            SettingAct.this.settingchanged = Boolean.valueOf(true);
        }

        public int getServerPort() {
            return SettingAct.this.antrianconfig.port;
        }

        public String getServerAddress() {
            String add = SettingAct.this.antrianconfig.serverAddress;
            if (add == null) {
                return "";
            }
            return add;
        }

        public int getPlaysoundAt() {
            return SettingAct.this.antrianconfig.playSoundAt;
        }

        public int getLoket() {
            return SettingAct.this.antrianconfig.loket;
        }

        public int getCurrentAntrian() {
            return SettingAct.this.antrianHelper.getAntrian();
        }

        public int getAppMode() {
            return SettingAct.this.antrianconfig.appMode;
        }
    }

    class C06422 implements AntrianChanged {
        C06422() {
        }

        public void warning(String msg) {
            Toast.makeText(SettingAct.this, msg, 0).show();
        }

        public void antrianChanged() {
            if (SettingAct.this.et_antrian != null) {
                SettingAct.this.et_antrian.setText(new StringBuilder(String.valueOf(SettingAct.this.antrianHelper.getAntrian())).toString());
            }
            if (SettingAct.this.et_loket != null) {
                SettingAct.this.et_loket.setText(new StringBuilder(String.valueOf(SettingAct.this.antrianHelper.antrianConfig.loket)).toString());
            }
        }
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        this.table = (TableLayout) findViewById(C0419R.id.as_table);
        this.inflater = getLayoutInflater();
        this.sharedpref = getSharedPreferences(AntrianConfig.SHARED_PREFFILE, 0);
        this.antrianconfig = new AntrianConfig(this.sharedpref);
        this.antrianHelper = new AntrianHelper(this, this.sharedpref);
        this.antrianHelper.setAntrianChangedCallback(new C06422());
        this.antrianHelper.loadCurrentAntrian();
        this.viewhelpersetting = new SettingAct_ViewHelper(this, this.settingviewInterface);
        this.viewhelpersetting.addAllsettingChild();
    }

    protected void onDestroy() {
        if (this.settingchanged.booleanValue()) {
            this.antrianconfig.saveConfig();
            try {
                ActBroadcastReceiver.sendSettingChanged(this);
            } catch (Exception e) {
            }
        }
        super.onDestroy();
    }

    public static void goHere(Activity actIn) {
        actIn.startActivity(new Intent(actIn, SettingAct.class));
    }
}
</code>```

SettingAct_ViewHelper.java

```<code>    package com.solusiwebmaster.antrian;

import android.app.Activity;
import android.graphics.Color;
import android.support.v4.view.ViewCompat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import server.AntrianResponse;
import server.ParamRequest;
import tools.AntrianConfig;
import tools.MyClient;
import tools.MyClient.MyClientCallback;
import tools.NetWorkTools;
import tools.ResourceTools;
import uihelper.SmallTombolBulat;
import uihelper.TombolSwitch;

public class SettingAct_ViewHelper {
    Activity act;
    EditText et_antrian;
    EditText et_loket;
    SettingActViewInterface ifc;
    MyClient oldclient;

    LayoutInflater inflater = this.act.getLayoutInflater();
    TableLayout table = ((TableLayout) this.act.findViewById(R.id.as_table));

    TombolSwitch tombolstatus;
    public SettingAct activity;

    class C04201 implements OnKeyListener {
        C04201() {
        }

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == 1) {
                try {
                    SettingAct_ViewHelper.this.ifc.setLoket(Integer.parseInt(((EditText) v).getText().toString()));
                } catch (Exception e) {
                }
            }
            return false;
        }
    }

    class C04212 implements OnKeyListener {
        C04212() {
        }

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == 1) {
                try {
                    SettingAct_ViewHelper.this.ifc.setAntrian(Integer.parseInt(((EditText) v).getText().toString()));
                } catch (Exception e) {
                }
            }
            return false;
        }
    }

    class C04223 implements OnItemSelectedListener {
        C04223() {
        }

        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            if (position != SettingAct_ViewHelper.this.ifc.getAppMode()) {
                SettingAct_ViewHelper.this.ifc.setAppMode(position);
            }
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    }

    class C04234 implements OnKeyListener {
        C04234() {
        }

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            try {
                if (event.getAction() == 1) {
                    EditText et = (EditText) v;
                    String text = et.getText().toString();
                    if (!text.startsWith("http://")) {
                        text = "http://" + text;
                        et.setText(text);
                        et.setSelection(text.length());
                    }
                    SettingAct_ViewHelper.this.ifc.setServerAddress(text);
                }
            } catch (Exception e) {
            }
            return false;
        }
    }

    class C04245 implements OnItemSelectedListener {
        C04245() {
        }

        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            int psoundat = position == 0 ? AntrianConfig.M_CLIENT : AntrianConfig.M_SERVER;
            if (psoundat != SettingAct_ViewHelper.this.ifc.getPlaysoundAt()) {
                SettingAct_ViewHelper.this.ifc.setPlaySoundAt(psoundat);
                SettingAct_ViewHelper.this.addAllsettingChild();
            }
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    }

    class C04256 implements OnKeyListener {
        C04256() {
        }

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            try {
                if (event.getAction() == 1) {
                    EditText et = (EditText) v;
                    if (et.getText().toString().length() >= 4) {
                        SettingAct_ViewHelper.this.ifc.setServerPort(Integer.parseInt(et.getText().toString()));
                    }
                }
            } catch (Exception e) {
            }
            return false;
        }
    }

    class C04267 implements OnClickListener {
        C04267() {
        }

        public void onClick(View v) {
            Toast.makeText(SettingAct_ViewHelper.this.act, "Tutup dan buka aplikasi untuk menyalakan server", 0).show();
        }
    }

    public interface SettingActViewInterface {
        int getAppMode();

        int getCurrentAntrian();

        int getLoket();

        int getPlaysoundAt();

        String getServerAddress();

        int getServerPort();

        void setAntrian(int i);

        void setAppMode(int i);

        void setLoket(int i);

        void setPlaySoundAt(int i);

        void setServerAddress(String str);

        void setServerPort(int i);
    }

    class C06438 implements MyClientCallback {
        C06438() {
        }

        public void result(int i) {
            if (i == 200) {
                SettingAct_ViewHelper.this.tombolstatus.setOn(Boolean.valueOf(true));
            } else {
                SettingAct_ViewHelper.this.tombolstatus.setOn(Boolean.valueOf(false));
            }
        }

        public void error(String msg) {
        }
    }

    public SettingAct_ViewHelper(Activity actIn, SettingActViewInterface ifcIn) {
        this.act = actIn;
        this.ifc = ifcIn;
        ((TextView) this.act.findViewById(R.id.as_title)).setText(new StringBuilder(String.valueOf(this.act.getResources().getString(R.string.app_name))).append(" v").append(ResourceTools.getVersionname(this.act)).toString());
    }

    public void addAllsettingChild() {
        this.table.removeAllViews();
        addSettingChild();
        addClientMenu();
        addServerMenu();
    }

    class ChildView {
        public View rootview=SettingAct_ViewHelper.this.inflater.inflate(R.layout.activity_setting_child, SettingAct_ViewHelper.this.table, false);
        public LinearLayout childlinear = ((LinearLayout) this.rootview.findViewById(R.id.asc_childLinear));
        public TextView textview = ((TextView) this.rootview.findViewById(R.id.asc_text));
        public SmallTombolBulat tombol = ((SmallTombolBulat) this.rootview.findViewById(R.id.asc_tombol));

        public ChildView(int iconcode, String textlabel, int circleColor) {
            this.rootview = SettingAct_ViewHelper.this.inflater.inflate(R.layout.activity_setting_child, SettingAct_ViewHelper.this.table, false);
            try {
                this.tombol.setIconCode(SettingAct_ViewHelper.this.act.getResources().getString(iconcode));
            } catch (Exception e) {
            }
            this.textview.setText(textlabel);
            this.tombol.setCircleColor(circleColor);
        }
    }

    private void addSettingChild() {
        addEditextChild(R.string.im_laptop, "Loket", this.ifc.getLoket()+"", Color.parseColor("#e63e6f"), new C04201());
        addEditextChild(R.string.im_user, "Antrian", this.ifc.getCurrentAntrian()+"", Color.parseColor("#730679"), new C04212());
        ChildView modechild = new ChildView(R.string.im_tree, "Mode", Color.parseColor("#99c210"));
        String[] modeopt = new String[]{"Standalone", "Client", "Server"};
        Spinner spinner = new Spinner(this.act);
        spinner.setAdapter(new ArrayAdapter(this.act, 17367048, modeopt));
        spinner.setSelection(this.ifc.getAppMode());
        spinner.setOnItemSelectedListener(new C04223());
        modechild.childlinear.addView(spinner);
        this.table.addView(modechild.rootview);
    }

    private void addClientMenu() {
        int psound = 0;
        if (this.ifc.getAppMode() == AntrianConfig.M_CLIENT) {
            String serveradd = this.ifc.getServerAddress();
            if (serveradd == null) {
                serveradd = "";
            }
            addEditextChild(R.string.im_podcast, "Server", serveradd, Color.parseColor("#ffab31"), 1, new C04234());
            ChildView modechild = new ChildView(R.string.im_megaphone, "Speakers", Color.parseColor("#99c210"));
            String[] modeopt = new String[]{"Client", "Server"};
            Spinner spinner = new Spinner(this.act);
            spinner.setAdapter(new ArrayAdapter(this.act, 17367048, modeopt));
            if (this.ifc.getPlaysoundAt() != 1) {
                psound = 1;
            }
            spinner.setSelection(psound);
            spinner.setOnItemSelectedListener(new C04245());
            modechild.childlinear.addView(spinner);
            this.table.addView(modechild.rootview);
        }
    }

    private void addServerMenu() {
        if (Integer.valueOf(this.ifc.getAppMode()).equals(Integer.valueOf(AntrianConfig.M_SERVER))) {
            addEditextChild(R.string.im_podcast, "Port", new StringBuilder(String.valueOf(this.ifc.getServerPort())).toString(), Color.parseColor("#730679"), new C04256());
            String devip = NetWorkTools.getIpAddress(this.act);
            if (devip == null) {
                devip = "";
            }
            devip = "http://" + devip + ":" + this.ifc.getServerPort() + "/";
            ChildView ipcv = new ChildView(R.string.im_podcast, "Server URL", Color.parseColor("#99c210"));
            TextView tv = new TextView(this.act);
            tv.setTextSize(2, 16.0f);
            tv.setTextColor(ViewCompat.MEASURED_STATE_MASK);
            tv.setGravity(16);
            tv.setText(devip);
            ipcv.childlinear.addView(tv);
            this.table.addView(ipcv.rootview);
            ChildView cv = new ChildView(R.string.im_podcast, "Server Status", Color.parseColor("#99c210"));
            this.tombolstatus = new TombolSwitch(this.act);
            this.tombolstatus.setOn(Boolean.valueOf(false));
            cv.childlinear.addView(this.tombolstatus);
            this.table.addView(cv.rootview);
            this.tombolstatus.setOnClickListener(new C04267());
            getStatusServer();
        }
    }

    private void addEditextChild(int icon, String textlabel, String valtext, int circleColor, OnKeyListener keylistener) {
        addEditextChild(icon, textlabel, valtext, circleColor, 2, keylistener);
    }

    private void addEditextChild(int icon, String textlabel, String valtext, int circleColor, int editortype, OnKeyListener keylistener) {
        ChildView cvLoket = new ChildView(icon, textlabel, circleColor);
        EditText loketeditext = new EditText(this.act);
        loketeditext.setText(valtext);
        loketeditext.setInputType(editortype);
        loketeditext.setOnKeyListener(keylistener);
        cvLoket.childlinear.addView(loketeditext);
        if (textlabel.equals("Loket")) {
            this.et_loket = loketeditext;
        }
        if (textlabel.equals("Antrian")) {
            this.et_antrian = loketeditext;
        }
        this.table.addView(cvLoket.rootview);
    }

    private void getStatusServer() {
        try {
            this.oldclient.disconnect();
        } catch (Exception e) {
        }
        if (this.tombolstatus != null) {
            ParamRequest param = new ParamRequest();
            param.allowresponse = Boolean.valueOf(true);
            param.reqmode = AntrianResponse.REQMODE_TEST;
            this.oldclient = MyClient.getAntrian(this.act, new C06438(), "http://127.0.0.1:" + this.ifc.getServerPort(), param);
        }
    }
}
</code>```

FATAL

```<code>FATAL EXCEPTION: main
Process: com.solusiwebmaster.antrian, PID: 22033
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.solusiwebmaster.antrian/com.solusiwebmaster.antrian.SettingAct}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.LayoutInflater android.app.Activity.getLayoutInflater()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.LayoutInflater android.app.Activity.getLayoutInflater()' on a null object reference
at com.solusiwebmaster.antrian.SettingAct_ViewHelper.<init>(SettingAct_ViewHelper.java:37)
at com.solusiwebmaster.antrian.SettingAct.onCreate(SettingAct.java:128)
at android.app.Activity.performCreate(Activity.java:6955)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
</code>```

when i run the application always show FATAL EXCEPTION: main. please help

答:
initialize rootview first</p>

```<code>class ChildView {
    public View rootview=SettingAct_ViewHelper.this.inflater.inflate(R.layout.activity_setting_child, SettingAct_ViewHelper.this.table, false);
    public LinearLayout childlinear = ((LinearLayout) this.rootview.findViewById(R.id.asc_childLinear));
    public TextView textview = ((TextView) this.rootview.findViewById(R.id.asc_text));
    public SmallTombolBulat tombol = ((SmallTombolBulat) this.rootview.findViewById(R.id.asc_tombol));
</code>```

Body:
i have a problem. when i compile always get error like bellow. so i hope there is someone who can help to understand this problem. when i open the activity always stack... please help me.

SettingAct.JAVA

package com.solusiwebmaster.antrian;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.Toast;
import com.solusiwebmaster.antrian.SettingAct_ViewHelper.SettingActViewInterface;
import tools.AntrianConfig;
import tools.AntrianHelper;
import tools.AntrianHelper.AntrianChanged;

public class SettingAct extends Activity {
    AntrianHelper antrianHelper;
    AntrianConfig antrianconfig;
    EditText et_antrian;
    EditText et_loket;
    LayoutInflater inflater;
    private Boolean settingchanged = Boolean.valueOf(false);
    SettingActViewInterface settingviewInterface = new C06411();
    SharedPreferences sharedpref;
    TableLayout table;
    SettingAct_ViewHelper viewhelpersetting;

    class C06411 implements SettingActViewInterface {
        C06411() {
        }

        public void setServerPort(int port) {
            if (SettingAct.this.antrianconfig.port != port && (port+"").length() >= 4) {
                SettingAct.this.antrianconfig.port = port;
                SettingAct.this.settingchanged = Boolean.valueOf(true);
            }
        }

        public void setServerAddress(String s) {
            if (!SettingAct.this.antrianconfig.serverAddress.equals(s)) {
                SettingAct.this.antrianconfig.serverAddress = s;
                SettingAct.this.settingchanged = Boolean.valueOf(true);
            }
        }

        public void setPlaySoundAt(int i) {
            SettingAct.this.antrianconfig.playSoundAt = i;
            SettingAct.this.settingchanged = Boolean.valueOf(true);
        }

        public void setLoket(int loket) {
            if (SettingAct.this.antrianconfig.loket != loket) {
                SettingAct.this.antrianconfig.loket = loket;
                SettingAct.this.settingchanged = Boolean.valueOf(true);
            }
        }

        public void setAppMode(int i) {
            System.out.println("apasih appmodenya : " + i + "servernya " + AntrianConfig.M_SERVER);
            SettingAct.this.antrianconfig.appMode = i;
            SettingAct.this.settingchanged = Boolean.valueOf(true);
            SettingAct.this.viewhelpersetting.addAllsettingChild();
        }

        public void setAntrian(int _antrian) {
            SettingAct.this.antrianHelper.setAntrian(_antrian);
            SettingAct.this.settingchanged = Boolean.valueOf(true);
        }

        public int getServerPort() {
            return SettingAct.this.antrianconfig.port;
        }

        public String getServerAddress() {
            String add = SettingAct.this.antrianconfig.serverAddress;
            if (add == null) {
                return "";
            }
            return add;
        }

        public int getPlaysoundAt() {
            return SettingAct.this.antrianconfig.playSoundAt;
        }

        public int getLoket() {
            return SettingAct.this.antrianconfig.loket;
        }

        public int getCurrentAntrian() {
            return SettingAct.this.antrianHelper.getAntrian();
        }

        public int getAppMode() {
            return SettingAct.this.antrianconfig.appMode;
        }
    }

    class C06422 implements AntrianChanged {
        C06422() {
        }

        public void warning(String msg) {
            Toast.makeText(SettingAct.this, msg, 0).show();
        }

        public void antrianChanged() {
            if (SettingAct.this.et_antrian != null) {
                SettingAct.this.et_antrian.setText(new StringBuilder(String.valueOf(SettingAct.this.antrianHelper.getAntrian())).toString());
            }
            if (SettingAct.this.et_loket != null) {
                SettingAct.this.et_loket.setText(new StringBuilder(String.valueOf(SettingAct.this.antrianHelper.antrianConfig.loket)).toString());
            }
        }
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        this.table = (TableLayout) findViewById(C0419R.id.as_table);
        this.inflater = getLayoutInflater();
        this.sharedpref = getSharedPreferences(AntrianConfig.SHARED_PREFFILE, 0);
        this.antrianconfig = new AntrianConfig(this.sharedpref);
        this.antrianHelper = new AntrianHelper(this, this.sharedpref);
        this.antrianHelper.setAntrianChangedCallback(new C06422());
        this.antrianHelper.loadCurrentAntrian();
        this.viewhelpersetting = new SettingAct_ViewHelper(this, this.settingviewInterface);
        this.viewhelpersetting.addAllsettingChild();
    }

    protected void onDestroy() {
        if (this.settingchanged.booleanValue()) {
            this.antrianconfig.saveConfig();
            try {
                ActBroadcastReceiver.sendSettingChanged(this);
            } catch (Exception e) {
            }
        }
        super.onDestroy();
    }

    public static void goHere(Activity actIn) {
        actIn.startActivity(new Intent(actIn, SettingAct.class));
    }
}

SettingAct_ViewHelper.java

    package com.solusiwebmaster.antrian;

import android.app.Activity;
import android.graphics.Color;
import android.support.v4.view.ViewCompat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import server.AntrianResponse;
import server.ParamRequest;
import tools.AntrianConfig;
import tools.MyClient;
import tools.MyClient.MyClientCallback;
import tools.NetWorkTools;
import tools.ResourceTools;
import uihelper.SmallTombolBulat;
import uihelper.TombolSwitch;

public class SettingAct_ViewHelper {
    Activity act;
    EditText et_antrian;
    EditText et_loket;
    SettingActViewInterface ifc;
    MyClient oldclient;

    LayoutInflater inflater = this.act.getLayoutInflater();
    TableLayout table = ((TableLayout) this.act.findViewById(R.id.as_table));

    TombolSwitch tombolstatus;
    public SettingAct activity;

    class C04201 implements OnKeyListener {
        C04201() {
        }

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == 1) {
                try {
                    SettingAct_ViewHelper.this.ifc.setLoket(Integer.parseInt(((EditText) v).getText().toString()));
                } catch (Exception e) {
                }
            }
            return false;
        }
    }

    class C04212 implements OnKeyListener {
        C04212() {
        }

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == 1) {
                try {
                    SettingAct_ViewHelper.this.ifc.setAntrian(Integer.parseInt(((EditText) v).getText().toString()));
                } catch (Exception e) {
                }
            }
            return false;
        }
    }

    class C04223 implements OnItemSelectedListener {
        C04223() {
        }

        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            if (position != SettingAct_ViewHelper.this.ifc.getAppMode()) {
                SettingAct_ViewHelper.this.ifc.setAppMode(position);
            }
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    }

    class C04234 implements OnKeyListener {
        C04234() {
        }

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            try {
                if (event.getAction() == 1) {
                    EditText et = (EditText) v;
                    String text = et.getText().toString();
                    if (!text.startsWith("http://")) {
                        text = "http://" + text;
                        et.setText(text);
                        et.setSelection(text.length());
                    }
                    SettingAct_ViewHelper.this.ifc.setServerAddress(text);
                }
            } catch (Exception e) {
            }
            return false;
        }
    }

    class C04245 implements OnItemSelectedListener {
        C04245() {
        }

        public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
            int psoundat = position == 0 ? AntrianConfig.M_CLIENT : AntrianConfig.M_SERVER;
            if (psoundat != SettingAct_ViewHelper.this.ifc.getPlaysoundAt()) {
                SettingAct_ViewHelper.this.ifc.setPlaySoundAt(psoundat);
                SettingAct_ViewHelper.this.addAllsettingChild();
            }
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    }

    class C04256 implements OnKeyListener {
        C04256() {
        }

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            try {
                if (event.getAction() == 1) {
                    EditText et = (EditText) v;
                    if (et.getText().toString().length() >= 4) {
                        SettingAct_ViewHelper.this.ifc.setServerPort(Integer.parseInt(et.getText().toString()));
                    }
                }
            } catch (Exception e) {
            }
            return false;
        }
    }

    class C04267 implements OnClickListener {
        C04267() {
        }

        public void onClick(View v) {
            Toast.makeText(SettingAct_ViewHelper.this.act, "Tutup dan buka aplikasi untuk menyalakan server", 0).show();
        }
    }

    public interface SettingActViewInterface {
        int getAppMode();

        int getCurrentAntrian();

        int getLoket();

        int getPlaysoundAt();

        String getServerAddress();

        int getServerPort();

        void setAntrian(int i);

        void setAppMode(int i);

        void setLoket(int i);

        void setPlaySoundAt(int i);

        void setServerAddress(String str);

        void setServerPort(int i);
    }

    class C06438 implements MyClientCallback {
        C06438() {
        }

        public void result(int i) {
            if (i == 200) {
                SettingAct_ViewHelper.this.tombolstatus.setOn(Boolean.valueOf(true));
            } else {
                SettingAct_ViewHelper.this.tombolstatus.setOn(Boolean.valueOf(false));
            }
        }

        public void error(String msg) {
        }
    }

    public SettingAct_ViewHelper(Activity actIn, SettingActViewInterface ifcIn) {
        this.act = actIn;
        this.ifc = ifcIn;
        ((TextView) this.act.findViewById(R.id.as_title)).setText(new StringBuilder(String.valueOf(this.act.getResources().getString(R.string.app_name))).append(" v").append(ResourceTools.getVersionname(this.act)).toString());
    }

    public void addAllsettingChild() {
        this.table.removeAllViews();
        addSettingChild();
        addClientMenu();
        addServerMenu();
    }

    class ChildView {
        public View rootview=SettingAct_ViewHelper.this.inflater.inflate(R.layout.activity_setting_child, SettingAct_ViewHelper.this.table, false);
        public LinearLayout childlinear = ((LinearLayout) this.rootview.findViewById(R.id.asc_childLinear));
        public TextView textview = ((TextView) this.rootview.findViewById(R.id.asc_text));
        public SmallTombolBulat tombol = ((SmallTombolBulat) this.rootview.findViewById(R.id.asc_tombol));

        public ChildView(int iconcode, String textlabel, int circleColor) {
            this.rootview = SettingAct_ViewHelper.this.inflater.inflate(R.layout.activity_setting_child, SettingAct_ViewHelper.this.table, false);
            try {
                this.tombol.setIconCode(SettingAct_ViewHelper.this.act.getResources().getString(iconcode));
            } catch (Exception e) {
            }
            this.textview.setText(textlabel);
            this.tombol.setCircleColor(circleColor);
        }
    }

    private void addSettingChild() {
        addEditextChild(R.string.im_laptop, "Loket", this.ifc.getLoket()+"", Color.parseColor("#e63e6f"), new C04201());
        addEditextChild(R.string.im_user, "Antrian", this.ifc.getCurrentAntrian()+"", Color.parseColor("#730679"), new C04212());
        ChildView modechild = new ChildView(R.string.im_tree, "Mode", Color.parseColor("#99c210"));
        String[] modeopt = new String[]{"Standalone", "Client", "Server"};
        Spinner spinner = new Spinner(this.act);
        spinner.setAdapter(new ArrayAdapter(this.act, 17367048, modeopt));
        spinner.setSelection(this.ifc.getAppMode());
        spinner.setOnItemSelectedListener(new C04223());
        modechild.childlinear.addView(spinner);
        this.table.addView(modechild.rootview);
    }

    private void addClientMenu() {
        int psound = 0;
        if (this.ifc.getAppMode() == AntrianConfig.M_CLIENT) {
            String serveradd = this.ifc.getServerAddress();
            if (serveradd == null) {
                serveradd = "";
            }
            addEditextChild(R.string.im_podcast, "Server", serveradd, Color.parseColor("#ffab31"), 1, new C04234());
            ChildView modechild = new ChildView(R.string.im_megaphone, "Speakers", Color.parseColor("#99c210"));
            String[] modeopt = new String[]{"Client", "Server"};
            Spinner spinner = new Spinner(this.act);
            spinner.setAdapter(new ArrayAdapter(this.act, 17367048, modeopt));
            if (this.ifc.getPlaysoundAt() != 1) {
                psound = 1;
            }
            spinner.setSelection(psound);
            spinner.setOnItemSelectedListener(new C04245());
            modechild.childlinear.addView(spinner);
            this.table.addView(modechild.rootview);
        }
    }

    private void addServerMenu() {
        if (Integer.valueOf(this.ifc.getAppMode()).equals(Integer.valueOf(AntrianConfig.M_SERVER))) {
            addEditextChild(R.string.im_podcast, "Port", new StringBuilder(String.valueOf(this.ifc.getServerPort())).toString(), Color.parseColor("#730679"), new C04256());
            String devip = NetWorkTools.getIpAddress(this.act);
            if (devip == null) {
                devip = "";
            }
            devip = "http://" + devip + ":" + this.ifc.getServerPort() + "/";
            ChildView ipcv = new ChildView(R.string.im_podcast, "Server URL", Color.parseColor("#99c210"));
            TextView tv = new TextView(this.act);
            tv.setTextSize(2, 16.0f);
            tv.setTextColor(ViewCompat.MEASURED_STATE_MASK);
            tv.setGravity(16);
            tv.setText(devip);
            ipcv.childlinear.addView(tv);
            this.table.addView(ipcv.rootview);
            ChildView cv = new ChildView(R.string.im_podcast, "Server Status", Color.parseColor("#99c210"));
            this.tombolstatus = new TombolSwitch(this.act);
            this.tombolstatus.setOn(Boolean.valueOf(false));
            cv.childlinear.addView(this.tombolstatus);
            this.table.addView(cv.rootview);
            this.tombolstatus.setOnClickListener(new C04267());
            getStatusServer();
        }
    }

    private void addEditextChild(int icon, String textlabel, String valtext, int circleColor, OnKeyListener keylistener) {
        addEditextChild(icon, textlabel, valtext, circleColor, 2, keylistener);
    }

    private void addEditextChild(int icon, String textlabel, String valtext, int circleColor, int editortype, OnKeyListener keylistener) {
        ChildView cvLoket = new ChildView(icon, textlabel, circleColor);
        EditText loketeditext = new EditText(this.act);
        loketeditext.setText(valtext);
        loketeditext.setInputType(editortype);
        loketeditext.setOnKeyListener(keylistener);
        cvLoket.childlinear.addView(loketeditext);
        if (textlabel.equals("Loket")) {
            this.et_loket = loketeditext;
        }
        if (textlabel.equals("Antrian")) {
            this.et_antrian = loketeditext;
        }
        this.table.addView(cvLoket.rootview);
    }

    private void getStatusServer() {
        try {
            this.oldclient.disconnect();
        } catch (Exception e) {
        }
        if (this.tombolstatus != null) {
            ParamRequest param = new ParamRequest();
            param.allowresponse = Boolean.valueOf(true);
            param.reqmode = AntrianResponse.REQMODE_TEST;
            this.oldclient = MyClient.getAntrian(this.act, new C06438(), "http://127.0.0.1:" + this.ifc.getServerPort(), param);
        }
    }
}

FATAL

FATAL EXCEPTION: main
Process: com.solusiwebmaster.antrian, PID: 22033
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.solusiwebmaster.antrian/com.solusiwebmaster.antrian.SettingAct}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.LayoutInflater android.app.Activity.getLayoutInflater()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.LayoutInflater android.app.Activity.getLayoutInflater()' on a null object reference
at com.solusiwebmaster.antrian.SettingAct_ViewHelper.<init>(SettingAct_ViewHelper.java:37)
at com.solusiwebmaster.antrian.SettingAct.onCreate(SettingAct.java:128)
at android.app.Activity.performCreate(Activity.java:6955)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)

when i run the application always show FATAL EXCEPTION: main. please help

Body:
initialize rootview first

class ChildView {
    public View rootview=SettingAct_ViewHelper.this.inflater.inflate(R.layout.activity_setting_child, SettingAct_ViewHelper.this.table, false);
    public LinearLayout childlinear = ((LinearLayout) this.rootview.findViewById(R.id.asc_childLinear));
    public TextView textview = ((TextView) this.rootview.findViewById(R.id.asc_text));
    public SmallTombolBulat tombol = ((SmallTombolBulat) this.rootview.findViewById(R.id.asc_tombol));


来源: stackexchange

问:
How to access UI from thread in C++ UWP App?
I have a native C++ multi-threaded console application.
I ported this application into UWP app with minimal change/
now I want to print out text into textbox in UI as there is no console app available in UWP app.

For this, I required access to a text box from a thread.

答: This is about asynchronous programming in C++.You can refer to this article.It describes the recommended way to consume asynchronous methods in Visual C++ and managing the thread context.You can populate text box within task::then method.On other hand, you can also use DispatchedHandler to access UI,please see this sample.

ContentLicense: CC BY-SA 3.0


问:
jquery passing string reference to object as parameter to function
I'm not sure wether to pass an $(object) or a string referencing the name of an object to a function:

```<code>function makeObject(div){
    var newDiv = $(div);
    $(div).html("newDiv: " + newDiv);
    }
</code>```

and caller:

```<code><div id="myDiv">
<a href="#" onclick="makeObject($(this).parent().attr('id'));">makeObject(this</a>
</div>
</code>```

I hope this is clear. It's a test function to get the principle in my head. Thanks in advance.

答:
Alternatively you can also add event handler on click.

```<code>// $(".myA").click(function (e) {
$("#myDiv").on("click", "a", function(e) {
</code>```

// $(".myA").click(function (e) {
$("#myDiv").on("click", "a", function(e) {
  console.log(this); // `this` is anchor element

  var parentId = $(this).parent().attr("id");
  console.log(parentId);

  e.preventDefault();
});

function makeObject(div) {
  var newDiv = $(div);
  $(div).html("newDiv: " + newDiv);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="myDiv">

makeObject(this);

</div></code>```

Body:
I'm not sure wether to pass an $(object) or a string referencing the name of an object to a function:

function makeObject(div){
    var newDiv = $(div);
    $(div).html("newDiv: " + newDiv);
    }

and caller:

makeObject(this

I hope this is clear. It's a test function to get the principle in my head. Thanks in advance.

Body:
Alternatively you can also add event handler on click.

// $(".myA").click(function (e) {
$("#myDiv").on("click", "a", function(e) {

// $(".myA").click(function (e) {
$("#myDiv").on("click", "a", function(e) {
  console.log(this); // `this` is anchor element

  var parentId = $(this).parent().attr("id");
  console.log(parentId);

  e.preventDefault();
});

function makeObject(div) {
  var newDiv = $(div);
  $(div).html("newDiv: " + newDiv);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="myDiv">
  <a href="#" class="myA">
makeObject(this);
  </a>
</div>


问:
validating a model when using a custom model binder in webapi2
I am executing a custom WebApi2 model binder as follows:
This is creating the model successfully. I am suppressing the JSON serializer errors as they don't correspond to the same errors that are normally provided by the default model binder.

Regardless or 'required' and other attributes on the model, the ModelState is empty.

How do I either

Invoke the default model binder to obtain the PartyModel with all the relevant model state errors?

Execute the default model validator to fill the Model State with the relevant errors after serializing what properties I can?

.

```<code>    public bool BindModel(
       HttpActionContext actionContext,
       System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(PartyModel))
            return false;

        var json = actionContext.Request.Content.ReadAsStringAsync().Result;
        var settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                // ignore json serializer errors, as they don't
                // seem to mimic the webapi2 default validator names/descriptions.
                Error = (s, e) => e.ErrorContext.Handled = true
            };
        var model = JsonConvert.DeserializeObject<PartyModel>(json, settings);

        // at this point the model needs to be validated.

        bindingContext.Model = model;
        return true;
    }
</code>```

答:
```<code>    public bool BindModel(
         HttpActionContext actionContext,
         System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(PartyModel))
            return false;
        ...

        // following lines invoke default validation on model
        bindingContext.ValidationNode.ValidateAllProperties = true;
        bindingContext.ValidationNode.Validate(actionContext);
        return true;
    }
</code>```

Body:
I am executing a custom WebApi2 model binder as follows:
This is creating the model successfully. I am suppressing the JSON serializer errors as they don't correspond to the same errors that are normally provided by the default model binder.

Regardless or 'required' and other attributes on the model, the ModelState is empty.

How do I either

Invoke the default model binder to obtain the PartyModel with all the relevant model state errors?

Execute the default model validator to fill the Model State with the relevant errors after serializing what properties I can?

.

    public bool BindModel(
       HttpActionContext actionContext,
       System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType != typeof(PartyModel))
            return false;

        var json = actionContext.Request.Content.ReadAsStringAsync().Result;
        var settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                // ignore json serializer errors, as they don't
                // seem to mimic the webapi2 default validator names/descriptions.
                Error = (s, e) => e.ErrorContext.Handled = true
            };
        var model = JsonConvert.DeserializeObject<PartyModel>(json, settings);

        // at this point the model needs to be validated.

        bindingContext.Model = model;
        return true;
    }


问:
How to create dynamic variables in JS?
This is my Code:

```<code>function NewPerson() {
    var count = parseInt($('#HiddenField').html());
    count++;
    $('#HiddenField').html(count);
    Var dynamicVariable = 'Person'+'Count'
}
</code>```

I want to define variable on this line Var **dynamicVariable** = 'Person'+'Count'

Now I need to create variable with count number

答:
You could also try this.

```<code>  var count = 1; //Let this be your count variable.
  var PersonString = "Person" + count; //Building a dynamic name for your variable
  alert(PersonString); //Person1 will be alerted
  window[PersonString] = "One";
  alert(Person1); //One will be alerted.
</code>```

Click here for the fiddle.

P.S : Here variables created dynamically will have a global scope.

Title: How to create dynamic variables in JS?

Body:
This is my Code:

function NewPerson() {
    var count = parseInt($('#HiddenField').html());
    count++;
    $('#HiddenField').html(count);
    Var dynamicVariable = 'Person'+'Count'
}

I want to define variable on this line Var **dynamicVariable** = 'Person'+'Count'

Now I need to create variable with count number

Body:
You could also try this.

  var count = 1; //Let this be your count variable.
  var PersonString = "Person" + count; //Building a dynamic name for your variable
  alert(PersonString); //Person1 will be alerted
  window[PersonString] = "One";
  alert(Person1); //One will be alerted.

Click here for the fiddle.

P.S : Here variables created dynamically will have a global scope.


问:
How to increase Image Memory using Bitmap Factory option
I want to use Big Size Image In Back Ground so How Can I do And i want to It's Working For All Device </p>

答:
As per your requirement, I guess that you are getting image from server end. Some time big size Bitmap throw OutOfMemoryException. So do one thing. Use this library to compress image and then show it to ImageView.

https://github.com/zetbaitsu/Compressor

You can also use Library. It provide you facility to fix image size and quality. so it won't be problem for you.

Nostra Image Loader


问:
Tokenize a String and Keep Delimiters Using Regular Expression in C++
I would like to modify the given regular expression to produce the following list of matches. I am having a hard time describing the problem in words.

I want to use a regular expression to match a set of 'tokens'. Specifically I want &&,||,;,(,) to be matched, and any string that does not contain those characters should be a match.
The problem I am having is distinguishing between one pipe and two pipes. How can i produce the desired matches? Thank you a lot for your help!

Link to this example

The expression:

```<code>((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+)
</code>```

Test String

```<code>a < b | c | d > e >> f && ((g) || h) ; i
</code>```

Expected Matches

```<code>a < b | c | d > e >> f
&&

(
(
g
)

||
 h
)

;
 i
</code>```

Actual Matches

```<code>a < b
|
 c
|
 d > e >> f
&&

(
(
g
)

||
 h
)

;
 i
</code>```

I am trying to implement a custom tokenizer for a program in C++.

Example Code

```<code>std::vector<std::string> Parser::tokenizeInput(std::string s) {
    std::vector<std::string> returnTokens;

    //tokenize correctly using this regex
    std::regex rgx(R"S(((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+))S");

    std::regex_iterator<std::string::iterator> rit ( s.begin(), s.end(), rgx );
    std::regex_iterator<std::string::iterator> rend;

    while (rit!=rend) {

        std::string tokenStr = rit->str();

        if(tokenStr.size() > 0 && tokenStr != " "){
            //assure the token is not blank
            //and push the token
            boost::algorithm::trim(tokenStr);
            returnTokens.push_back(tokenStr);
        }

        ++rit;
    }

    return returnTokens;
}
</code>```

Example Driver Code

```<code>//in main
std::vector<std::string> testVec = Parser::tokenizeInput(inputWithNoComments);
std::cout << "input string: " << inputWithNoComments << std::endl;
std::cout << "tokenized string[";
for(unsigned int i = 0; i < testVec.size(); i++){
    std::cout << testVec[i];
    if ( i + 1 < testVec.size() ) { std::cout << ", "; }
}
std::cout << "]" << std::endl;
</code>```

Produced Output

```<code>input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l, grep -i, )]

input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f, g]

input string: foo | bar || foo || bar | foo | bar
tokenized string[foo, bar, ||, foo, ||, bar, foo, bar]
</code>```

What I Want the Output to be

```<code>input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l | grep -i, )]

input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f | g]

input string: foo | bar || foo || bar | foo | bar
tokenized string[foo | bar, ||, foo, ||, bar | foo | bar]
</code>```

答:
I have prepared the following regex and tested it it produces exactly the same output as described on your input string:

```<code>(?<=&&)[^;()]*|\(|\)|(?<=\|\|)[^;()]*|;|&&|\|\||([^|;()&]+(\|[^|;()&]+)*)*
</code>```

or this one:

```<code>\(|\)|;|&&|\|\||([^|;()&]+(&[^|;()&]+|\|[^|;()&]+)*)
</code>```

Let me know if it works as expected!

Matches:

```<code>a < b | c | d > e >> f
&&

(
(
g
)

||
 h
)

;
 i
</code>```

and tested on:

```<code>(cat file > outFile) || ( ls -l | grep -i )
(cat file >> outFile) && ls -l | grep -i
((file < file) || ls -l ; ls)
cat < InputFile | tr a-z A-Z | tee out1 > out2 >> out3 | asd aasdasd  | asd | asd || asd | asd
a | b || c | d && a || b && d ; g &&
a && b || c > d >> e < f | g
a < b | c | d > e >> f && ((g) || h) ; i
</code>```

Body:
I would like to modify the given regular expression to produce the following list of matches. I am having a hard time describing the problem in words.

I want to use a regular expression to match a set of 'tokens'. Specifically I want &&,||,;,(,) to be matched, and any string that does not contain those characters should be a match.
The problem I am having is distinguishing between one pipe and two pipes. How can i produce the desired matches? Thank you a lot for your help!

Link to this example

The expression:

((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+)

Test String

a  e >> f && ((g) || h) ; i

Expected Matches

a  e >> f
&&

(
(
g
)

||
 h
)

;
 i

Actual Matches

a  e >> f
&&

(
(
g
)

||
 h
)

;
 i

I am trying to implement a custom tokenizer for a program in C++.

Example Code

std::vector<std::string> Parser::tokenizeInput(std::string s) {
    std::vector<std::string> returnTokens;

    //tokenize correctly using this regex
    std::regex rgx(R"S(((&{2})|(\|{2})|(\()|(\))|(;)|[^&|;()]+))S");

    std::regex_iterator<std::string::iterator> rit ( s.begin(), s.end(), rgx );
    std::regex_iterator<std::string::iterator> rend;

    while (rit!=rend) {

        std::string tokenStr = rit->str();

        if(tokenStr.size() > 0 && tokenStr != " "){
            //assure the token is not blank
            //and push the token
            boost::algorithm::trim(tokenStr);
            returnTokens.push_back(tokenStr);
        }

        ++rit;
    }

    return returnTokens;
}

Example Driver Code

//in main
std::vector<std::string> testVec = Parser::tokenizeInput(inputWithNoComments);
std::cout << "input string: " << inputWithNoComments << std::endl;
std::cout << "tokenized string[";
for(unsigned int i = 0; i < testVec.size(); i++){
    std::cout << testVec[i];
    if ( i + 1 < testVec.size() ) { std::cout << ", "; }
}
std::cout << "]" << std::endl;

Produced Output

input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l, grep -i, )]

input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f, g]

input string: foo | bar || foo || bar | foo | bar
tokenized string[foo, bar, ||, foo, ||, bar, foo, bar]

What I Want the Output to be

input string: (cat file > outFile) || ( ls -l | grep -i )
tokenized string[(, cat file > outFile, ), ||, (, ls -l | grep -i, )]

input string: a && b || c > d >> e < f | g
tokenized string[a, &&, b, ||, c > d >> e < f | g]

input string: foo | bar || foo || bar | foo | bar
tokenized string[foo | bar, ||, foo, ||, bar | foo | bar]

Body:
I have prepared the following regex and tested it it produces exactly the same output as described on your input string:

(?<=&&)[^;()]*|\(|\)|(?<=\|\|)[^;()]*|;|&&|\|\||([^|;()&]+(\|[^|;()&]+)*)*

or this one:

\(|\)|;|&&|\|\||([^|;()&]+(&[^|;()&]+|\|[^|;()&]+)*)

Let me know if it works as expected!

Matches:

a < b | c | d > e >> f
&&

(
(
g
)

||
 h
)

;
 i

and tested on:

(cat file > outFile) || ( ls -l | grep -i )
(cat file >> outFile) && ls -l | grep -i
((file < file) || ls -l ; ls)
cat < InputFile | tr a-z A-Z | tee out1 > out2 >> out3 | asd aasdasd  | asd | asd || asd | asd
a | b || c | d && a || b && d ; g &&
a && b || c > d >> e < f | g
a < b | c | d > e >> f && ((g) || h) ; i


问:
what does the error means in angular 2?
```<code>export class DashboardComponent implements OnInit {
@ViewChild('modal') modal: ModalComponent;
        dashboards: IDashboard[];
        dashboard: IDashboard;
    constructor(private fb: FormBuilder, private _dshboardService: DashboardService, private router: Router) {
                var sesssion = sessionStorage.getItem('EmpDetail');
                var ses = JSON.parse(sesssion);
                var EmpNo = ses[0].EmpNumber;
                var CompanyCode = ses[0].CompanyCode;
                this.dashboard = {};
                this.dashboard.EmpName = ses[0].EmpName;
                this.dashboard.EmpNumber = ses[0].EmpNumber;
            }
}
</code>```

this shows the below error on the line this.dashboard = {};

Error TS2322  Type '{}' is not assignable to type 'IDashboard'.

  Property 'EmpName' is missing in type '{}'.

I need to assign the value to the properties of dashboard model and bind the same in html component

Below is my IDashboard:

```<code>export interface IDashboard {
    EmpName: string,
    EmpNumber: string,
    EmailId: string,
    FirstName: string,
    LastName: string,
    Gender: string,
    Program:string
}
</code>```

答:
you need to declare and initialize it with empty object inside the constructor or ngOninit.

You need to have the Dashboard declared in the component as,

```<code>const dashboard: Dashboard= {  param1: "", param2: ""...etc};
</code>```

Title: what does the error means in angular 2?

Body:
export class DashboardComponent implements OnInit {
@ViewChild('modal') modal: ModalComponent;
        dashboards: IDashboard[];
        dashboard: IDashboard;
    constructor(private fb: FormBuilder, private _dshboardService: DashboardService, private router: Router) {
                var sesssion = sessionStorage.getItem('EmpDetail');
                var ses = JSON.parse(sesssion);
                var EmpNo = ses[0].EmpNumber;
                var CompanyCode = ses[0].CompanyCode;
                this.dashboard = {};
                this.dashboard.EmpName = ses[0].EmpName;
                this.dashboard.EmpNumber = ses[0].EmpNumber;
            }
}

this shows the below error on the line this.dashboard = {};

Error TS2322  Type '{}' is not assignable to type 'IDashboard'.

  Property 'EmpName' is missing in type '{}'.

I need to assign the value to the properties of dashboard model and bind the same in html component

Below is my IDashboard:

export interface IDashboard {
    EmpName: string,
    EmpNumber: string,
    EmailId: string,
    FirstName: string,
    LastName: string,
    Gender: string,
    Program:string
}

Body:
you need to declare and initialize it with empty object inside the constructor or ngOninit.

You need to have the Dashboard declared in the component as,

const dashboard: Dashboard= {  param1: "", param2: ""...etc};


问:
getting "No JSON object could be decoded" for json URL
The api returning json on brower but when parsing it on python I am getting this exception: No JSON object could be decoded. I have used both json.load() and json.loads() but failed.

Here is that code.

```<code>def handler_timeout(self):
        try:
            data = json.load(
                urlopen(
                    'https://www.zebapi.com/api/v1/market/ticker/btc/inr'
                )
            )
            buy_price = data['buy']
            sell_price = data['sell']
            status_message = "Buy: ₹ " + "{:,}".format(buy_price) + "   Sell: ₹ " + "{:,}".format(sell_price)
            self.ind.set_label(status_message, "")
        except Exception, e:
            print str(e)
            self.ind.set_label("!", "")
        return True
</code>```

Here is the output for urlopen(URL):

```<code><addinfourl at 140336849031752 whose fp = <socket._fileobject object at 0x7fa2bb6f1cd0>>
</code>```

Here is the output for urlopen(URL).read() :

```<code>��`I�%&/m�{J�J��t�`$ؐ@�������iG#)�*��eVe]f@�흼��{����{����;�N'���?\fdl��J�ɞ!���?~|?"~�o���G��~��=J�vv��;#�x���}��e���?=�N�u�/�h��ًWɧ�U�^���Ã���;���}�'���Q��ct
</code>```

答:
The content of the url is gzip-encoded.

```<code>>>> u = urllib.urlopen('https://www.zebapi.com/api/v1/market/ticker/btc/inr')
>>> info = u.info()
>>> info['Content-Encoding']
'gzip'
</code>```

Decompress the content.

```<code>import gzip
import io
import json
import urllib

u = urllib.urlopen('https://www.zebapi.com/api/v1/market/ticker/btc/inr')
with io.BytesIO(u.read()) as f:
    gz = gzip.GzipFile(fileobj=f)
    print json.load(gz)
</code>```

or use requests which decode gzip automatically:

```<code>import requests
print requests.get('https://www.zebapi.com/api/v1/market/ticker/btc/inr').json()
</code>```

Body:
The api returning json on brower but when parsing it on python I am getting this exception: No JSON object could be decoded. I have used both json.load() and json.loads() but failed.

Here is that code.

def handler_timeout(self):
        try:
            data = json.load(
                urlopen(
                    'https://www.zebapi.com/api/v1/market/ticker/btc/inr'
                )
            )
            buy_price = data['buy']
            sell_price = data['sell']
            status_message = "Buy: ₹ " + "{:,}".format(buy_price) + "   Sell: ₹ " + "{:,}".format(sell_price)
            self.ind.set_label(status_message, "")
        except Exception, e:
            print str(e)
            self.ind.set_label("!", "")
        return True

Here is the output for urlopen(URL):

<addinfourl at 140336849031752 whose fp = <socket._fileobject object at 0x7fa2bb6f1cd0>>

Here is the output for urlopen(URL).read() :

��`I�%&/m�{J�J��t�`$ؐ@�������iG#)�*��eVe]f@�흼��{����{����;�N'���?\fdl��J�ɞ!���?~|?"~�o���G��~��=J�vv��;#�x���}��e���?=�N�u�/�h��ًWɧ�U�^���Ã���;���}�'���Q��ct

Body:
The content of the url is gzip-encoded.

>>> u = urllib.urlopen('https://www.zebapi.com/api/v1/market/ticker/btc/inr')
>>> info = u.info()
>>> info['Content-Encoding']
'gzip'

Decompress the content.

import gzip
import io
import json
import urllib

u = urllib.urlopen('https://www.zebapi.com/api/v1/market/ticker/btc/inr')
with io.BytesIO(u.read()) as f:
    gz = gzip.GzipFile(fileobj=f)
    print json.load(gz)

or use requests which decode gzip automatically:

import requests
print requests.get('https://www.zebapi.com/api/v1/market/ticker/btc/inr').json()


问:
how to find which table contain record when using union in mysql
I want the table name which contain record when using union in mysql.
I want to delete the records from that table or else i have to go through all tables and find the records and delete manually.

The query:

```<code>SELECT id FROM table1 WHERE cfid='2'
UNION
SELECT id FROM table2 WHERE ob_id='2'
UNION
SELECT id FROM table3 WHERE jid='2'
</code>```

答:
Include a discriminator column in the individual SELECT statements, with a distinct hardcoded value in each. As an example, we add a column named src_ to each query ...

```<code>SELECT '1' AS src_, foo FROM bar WHERE ...

 UNION ALL

SELECT '2' AS src_, grumblestilt FROM skin WHERE ...
</code>```

We can use the value returned in that column to determine which SELECT returned a particular row.

Note: if we don't need to eliminate duplicate rows, we can use the UNION ALL set operator. The UNION operator will go through the work of identifying rows that are duplicates, and eliminating duplicates so we get a result set containing unique tuples.

Body:
I want the table name which contain record when using union in mysql.
I want to delete the records from that table or else i have to go through all tables and find the records and delete manually.

The query:

SELECT id FROM table1 WHERE cfid='2'
UNION
SELECT id FROM table2 WHERE ob_id='2'
UNION
SELECT id FROM table3 WHERE jid='2'

Body:
Include a discriminator column in the individual SELECT statements, with a distinct hardcoded value in each. As an example, we add a column named src_ to each query ...

SELECT '1' AS src_, foo FROM bar WHERE ...

 UNION ALL

SELECT '2' AS src_, grumblestilt FROM skin WHERE ...

We can use the value returned in that column to determine which SELECT returned a particular row.

Note: if we don't need to eliminate duplicate rows, we can use the UNION ALL set operator. The UNION operator will go through the work of identifying rows that are duplicates, and eliminating duplicates so we get a result set containing unique tuples.


问:
How to find a number divisible by 7 in Visual Basic using function?
My task is: Display numbers that are divisible by 7 (range 10-25). Calculate and display an average of the numbers that are not divisible by 7

So I wrote this code in Visual Basic. How can it be improved? I do not know how to display numbers 14 and 21 in other way.

```<code>Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim counter As Byte = 0
    Dim accumulator As Short = 0
    Dim average As Single
    Dim loopcounter As Byte

    For loopcounter = 10 To 25
        If loopcounter Mod 7 <> 0 Then
            accumulator += loopcounter
            counter += 1
        Else
            Label1.Text = loopcounter & ", 14"
        End If
    Next

    average = accumulator / counter
    Label2.Text = average
End Sub
End Class
</code>```

答:
You could put the numbers divisible by 7 into a List(Of Integer) and then use String.Join() to combine them into a string at the end of the loop.

```<code>    Dim counter As Byte = 0
    Dim accumulator As Short = 0
    Dim average As Single
    Dim loopcounter As Byte
    Dim multiples As List(Of Integer) = New List(Of Integer)()  ' Declare list

    For loopcounter = 10 To 25
        If loopcounter Mod 7 <> 0 Then
            accumulator += loopcounter
            counter += 1
        Else
            multiples.Add(loopcounter)  ' Add multiple of 7 to list
        End If
    Next

    Label1.Text = String.Join(", ", multiples) ' Combine list into a comma-separated string
    average = accumulator / counter
    Label2.Text = average
</code>```

Body:
My task is: Display numbers that are divisible by 7 (range 10-25). Calculate and display an average of the numbers that are not divisible by 7

So I wrote this code in Visual Basic. How can it be improved? I do not know how to display numbers 14 and 21 in other way.

Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim counter As Byte = 0
    Dim accumulator As Short = 0
    Dim average As Single
    Dim loopcounter As Byte

    For loopcounter = 10 To 25
        If loopcounter Mod 7 <> 0 Then
            accumulator += loopcounter
            counter += 1
        Else
            Label1.Text = loopcounter & ", 14"
        End If
    Next

    average = accumulator / counter
    Label2.Text = average
End Sub
End Class

Body:
You could put the numbers divisible by 7 into a List(Of Integer) and then use String.Join() to combine them into a string at the end of the loop.

    Dim counter As Byte = 0
    Dim accumulator As Short = 0
    Dim average As Single
    Dim loopcounter As Byte
    Dim multiples As List(Of Integer) = New List(Of Integer)()  ' Declare list

    For loopcounter = 10 To 25
        If loopcounter Mod 7 <> 0 Then
            accumulator += loopcounter
            counter += 1
        Else
            multiples.Add(loopcounter)  ' Add multiple of 7 to list
        End If
    Next

    Label1.Text = String.Join(", ", multiples) ' Combine list into a comma-separated string
    average = accumulator / counter
    Label2.Text = average


问:
Python- The Word Game "Ghost", File I/O, and List question
I want to create computer for the word-game Ghost.   However, I'm having problems thinking of a good way to deal with accessing the huge word list.  Here's my current implementation (which doesn't work):

```<code>import os, random, sys, math, string

def main():

    #Contains a huge wordlist-- opened up for reading
    dictionary = open("wordlist.txt", "r")
    wordlist = []
    win= 0
    turn= 0
    firstrun = 0
    word = ""

    #while nobody has won the game
    while win==0:
        if turn == 0:
            #get first letter from input
            foo = raw_input("Choose a letter: ")[0]
            word+=foo
            print "**Current word**: "+ word
            #Computer's turn
            turn = 1
        if turn == 1:
            #During the first run the program gets all definitively
            #winning words (words that have odd-number lengths)
            #from the "dictionary" file and puts them in a list
            if firstrun== 0:
                for line in dictionary:
                    #if the line in the dictionary starts with the current
                    #word and has an odd-number of letters
                    if str(line).startswith(word) and len(line)%2 == 0:
                        wordlist.append(line[0: len(line)-1])
                print "first run complete... size = "+str(len(wordlist))
                firstrun = 1
            else:   #This is run after the second computer move
                for line in wordlist:
                    #THIS DOES NOT WORK-- THIS IS THE PROBLEM.
                    #I want it to remove from the list every single
                    #word that does not conform to the current limitations
                    #of the "word" variable.
                    if not line.startswith(word):
                        wordlist.remove(line)
                print "removal complete... size = "+str(len(wordlist))

            turn = 0

if __name__ == "__main__":
    main()
</code>```

I have demarcated the problem area in the code.  I have no idea why it doesn't work.  What should happen: Imagine the list is populated with all words that start with 'a.' The user then picks the letter 'b.' The target word then must have the starting letters 'ab.' What should happen is that all 'a' words that are in the list that are not directly followed with a 'b' should be removed.

I also would appreciate it if somebody could let me know a more efficient way of doing this then making a huge initial list.

答:
Peter Norvig has a great discussion on autocorrect here:

http://norvig.com/spell-correct.html

The large-list comprehension and context matching seem relevant - and at 21 lines it's a quick read (with good explanation following). Also check out the "Charming python" 3-part on functional programming with python (IBM). You can do all the setup with a few list comprehensions.

ContentLicense: CC BY-SA 2.5

Body:
I want to create computer for the word-game Ghost.   However, I'm having problems thinking of a good way to deal with accessing the huge word list.  Here's my current implementation (which doesn't work):

import os, random, sys, math, string

def main():

    #Contains a huge wordlist-- opened up for reading
    dictionary = open("wordlist.txt", "r")
    wordlist = []
    win= 0
    turn= 0
    firstrun = 0
    word = ""

    #while nobody has won the game
    while win==0:
        if turn == 0:
            #get first letter from input
            foo = raw_input("Choose a letter: ")[0]
            word+=foo
            print "**Current word**: "+ word
            #Computer's turn
            turn = 1
        if turn == 1:
            #During the first run the program gets all definitively
            #winning words (words that have odd-number lengths)
            #from the "dictionary" file and puts them in a list
            if firstrun== 0:
                for line in dictionary:
                    #if the line in the dictionary starts with the current
                    #word and has an odd-number of letters
                    if str(line).startswith(word) and len(line)%2 == 0:
                        wordlist.append(line[0: len(line)-1])
                print "first run complete... size = "+str(len(wordlist))
                firstrun = 1
            else:   #This is run after the second computer move
                for line in wordlist:
                    #THIS DOES NOT WORK-- THIS IS THE PROBLEM.
                    #I want it to remove from the list every single
                    #word that does not conform to the current limitations
                    #of the "word" variable.
                    if not line.startswith(word):
                        wordlist.remove(line)
                print "removal complete... size = "+str(len(wordlist))

            turn = 0

if __name__ == "__main__":
    main()

I have demarcated the problem area in the code.  I have no idea why it doesn't work.  What should happen: Imagine the list is populated with all words that start with 'a.' The user then picks the letter 'b.' The target word then must have the starting letters 'ab.' What should happen is that all 'a' words that are in the list that are not directly followed with a 'b' should be removed.

I also would appreciate it if somebody could let me know a more efficient way of doing this then making a huge initial list.


问:
How to create Drop Down Pop Up View
I want to show a drop-down menu on button click.I follow the below link for this.

```<code>https://richardallen.me/2014/11/28/popovers.html
</code>```

But my button is in table view cell and I want to show the popup on below the button.I searched a lot and find the way by using popovers. But I don't know how to use and show it.If I follow the above link then below error is shown.And popup is shown on full screen.So please help me.

```<code>/Base.lproj/Main.storyboard:%20Couldn't%20compile%20connection:%20<IBCocoaTouchOutletConnection:%200x7fc9f5fa6330%20(KPd-LK-kJS)%20source=<IBProxyObject:%200x7fc9f5fa6020%20(mgH-pb-OhC)%20'Placeholder%20for%20UIStoryboardPopoverPresentationSegueTemplate%20with%20OID%20qoG-n8-Yu0'>%20property=anchorView%20destination=<IBUIButton:%200x7fc9f796dd40%20(xk1-Vu-vnj)%20'Anchor%20View'>>
</code>```

Thanks in Advance.

答:
To create a dropdown using tableview and popover was little bit time consuming work but luckily we have an alternative solution for that use this library very easy to use

Initialization:

```<code>let dropDown = DropDown()

// The view to which the drop down will appear on
dropDown.anchorView = view // UIView or UIBarButtonItem

// The list of items to display. Can be changed dynamically
dropDown.dataSource = ["Car", "Motorcycle", "Truck"]
</code>```

Handle selection:

```<code>// Action triggered on selection
dropDown.selectionAction = { [unowned self] (index: Int, item: String) in
  print("Selected item: \(item) at index: \(index)")
}

// Will set a custom width instead of the anchor view width
dropDownLeft.width = 200
</code>```

Display actions:

```<code>dropDown.show()
dropDown.hide()
</code>```

Hope this will help you

Title: How to create Drop Down Pop Up View

Body:
I want to show a drop-down menu on button click.I follow the below link for this.

https://richardallen.me/2014/11/28/popovers.html

But my button is in table view cell and I want to show the popup on below the button.I searched a lot and find the way by using popovers. But I don't know how to use and show it.If I follow the above link then below error is shown.And popup is shown on full screen.So please help me.

/Base.lproj/Main.storyboard:%20Couldn't%20compile%20connection:%20<IBCocoaTouchOutletConnection:%200x7fc9f5fa6330%20(KPd-LK-kJS)%20source=<IBProxyObject:%200x7fc9f5fa6020%20(mgH-pb-OhC)%20'Placeholder%20for%20UIStoryboardPopoverPresentationSegueTemplate%20with%20OID%20qoG-n8-Yu0'>%20property=anchorView%20destination=<IBUIButton:%200x7fc9f796dd40%20(xk1-Vu-vnj)%20'Anchor%20View'>>

Thanks in Advance.

Body:
To create a dropdown using tableview and popover was little bit time consuming work but luckily we have an alternative solution for that use this library very easy to use

Initialization:

let dropDown = DropDown()

// The view to which the drop down will appear on
dropDown.anchorView = view // UIView or UIBarButtonItem

// The list of items to display. Can be changed dynamically
dropDown.dataSource = ["Car", "Motorcycle", "Truck"]

Handle selection:

// Action triggered on selection
dropDown.selectionAction = { [unowned self] (index: Int, item: String) in
  print("Selected item: \(item) at index: \(index)")
}

// Will set a custom width instead of the anchor view width
dropDownLeft.width = 200

Display actions:

dropDown.show()
dropDown.hide()

Hope this will help you


问:
After App Signing - IAP not working
As per latest Google Play Store, we have enroll our applications into App Signing.
After this enrollment our IAP product is not working and showing error as :

"This version of the application is not configured for billing through Google Play".

WE HAVE ALREADY UPLOADED NEW BUILDS FOR ALPHA RELEASE.

Still, we are getting this error.

Also we have checked that if we sign an APK with older keystore.

We are able to see the IAP dialog correctly.

Please suggest.

答:
I have found this,

If you create sign APK from new keystore.

And tried installing new APK rather than Play Store.

Then IAP will not work.

Previously this is working as expected.

Also installing new APK from anywhere else. You are not able to test Application upgrade scenarios.

That means if you have previously released app from old Sign APK then you enroll into App Signing and test upgrade scenarios from APK which has been uploaded on your private server, then your application will not install on the device.

The solution for this is to each time you want to test above scenarios, you should have to upload sign APKs to Play Store (Alpha).

Title: After App Signing - IAP not working


问:
cannot check(select) radio button inside a modal dialog
In my page I am using custom modal dialog and inside that modal I am using a form. I have put two radio button inside that form but I cannot check either one.</p>

```<code><div id="user_modal" class="modal modal__bg" role="dialog" aria-hidden="true">
    <div class="modal__dialog">
        <div class="modal__content">
            <h1>User registration</h1>

            <form action="" id="u_register_form">

                <div class="form-group">
                  <input type="text" class="form-control" id="fullname" placeholder="Full name" required/>
                </div>

                <div class="form-group">
                    <label class="radio-inline"><input type="radio" value="w" name="optradio"/>Worker</label>
                    <label class="radio-inline"><input type="radio" value="e" name="optradio"/>Engineer</label>
                </div>

                <div class="form-group">
                  <input type="text" class="form-control" id="username" required placeholder="Username">
                </div>

                <div class="form-group">
                  <input type="password" class="form-control" id="u_pwd1" pattern=".{8,}" required placeholder="Password"/>
                </div>

                <div class="form-group submit_btn">
                    <input class="btn btn-success" id="u_register_btn" type="submit" value="SAVE">
                </div>

            </form>

            <!-- modal close button -->
            <a href="" class="modal__close demo-close">
                <svg class="" viewBox="0 0 24 24"><path d="M19 6.41l-1.41-1.41-5.59 5.59-5.59-5.59-1.41 1.41 5.59 5.59-5.59 5.59 1.41 1.41 5.59-5.59 5.59 5.59 1.41-1.41-5.59-5.59z"/><path d="M0 0h24v24h-24z" fill="none"/></svg>
            </a>

        </div>
    </div>
</div>
</code>```

答:
Its working properly i did't change anything ..

User registration

            <form action="" id="u_register_form">

                  <input type="text" class="form-control" id="fullname" placeholder="Full name" required/>

                    <input type="radio" value="w" name="optradio"/>Worker
                    <input type="radio" value="e" name="optradio"/>Engineer

                  <input type="text" class="form-control" id="username" required placeholder="Username">

                  <input type="password" class="form-control" id="u_pwd1" pattern=".{8,}" required placeholder="Password"/>

                    <input class="btn btn-success" id="u_register_btn" type="submit" value="SAVE">

            </form>

                <svg class="" viewBox="0 0 24 24"><path d="M19 6.41l-1.41-1.41-5.59 5.59-5.59-5.59-1.41 1.41 5.59 5.59-5.59 5.59 1.41 1.41 5.59-5.59 5.59 5.59 1.41-1.41-5.59-5.59z"/><path d="M0 0h24v24h-24z" fill="none"/></svg>

```

Body:
In my page I am using custom modal dialog and inside that modal I am using a form. I have put two radio button inside that form but I cannot check either one.

User registration

            <form action="" id="u_register_form">

                  <input type="text" class="form-control" id="fullname" placeholder="Full name" required/>

                    <input type="radio" value="w" name="optradio"/>Worker
                    <input type="radio" value="e" name="optradio"/>Engineer

                  <input type="text" class="form-control" id="username" required placeholder="Username">

                  <input type="password" class="form-control" id="u_pwd1" pattern=".{8,}" required placeholder="Password"/>

                    <input class="btn btn-success" id="u_register_btn" type="submit" value="SAVE">

            </form>

                <svg class="" viewBox="0 0 24 24"><path d="M19 6.41l-1.41-1.41-5.59 5.59-5.59-5.59-1.41 1.41 5.59 5.59-5.59 5.59 1.41 1.41 5.59-5.59 5.59 5.59 1.41-1.41-5.59-5.59z"/><path d="M0 0h24v24h-24z" fill="none"/></svg>

Body:
Its working properly i did't change anything ..

<div id="user_modal" class="modal modal__bg" role="dialog" aria-hidden="true">
    <div class="modal__dialog">
        <div class="modal__content">
            <h1>User registration</h1>

            <form action="" id="u_register_form">

                <div class="form-group">
                  <input type="text" class="form-control" id="fullname" placeholder="Full name" required/>
                </div>

                <div class="form-group">
                    <label class="radio-inline"><input type="radio" value="w" name="optradio"/>Worker</label>
                    <label class="radio-inline"><input type="radio" value="e" name="optradio"/>Engineer</label>
                </div>

                <div class="form-group">
                  <input type="text" class="form-control" id="username" required placeholder="Username">
                </div>

                <div class="form-group">
                  <input type="password" class="form-control" id="u_pwd1" pattern=".{8,}" required placeholder="Password"/>
                </div>

                <div class="form-group submit_btn">
                    <input class="btn btn-success" id="u_register_btn" type="submit" value="SAVE">
                </div>

            </form>

            <!-- modal close button -->
            <a href="" class="modal__close demo-close">
                <svg class="" viewBox="0 0 24 24"><path d="M19 6.41l-1.41-1.41-5.59 5.59-5.59-5.59-1.41 1.41 5.59 5.59-5.59 5.59 1.41 1.41 5.59-5.59 5.59 5.59 1.41-1.41-5.59-5.59z"/><path d="M0 0h24v24h-24z" fill="none"/></svg>
            </a>

        </div>
    </div>
</div>


答:
Error there:

```<code>this.dashboard = {};
</code>```

this.dashboard has type IDashboard, i guess it has at least one to optional field. So you can't set object without setting this required fields.
Something like:

```<code>interface Person {
  name: string;
}

const person = {} // Error
const person1 = {name: 'Test'} // No Error

interface Person1 {
 name?: string; //name is optional field
}
 const person = {} // No Error
</code>```

Title: what does the error means in angular 2?

Body:
Error there:

this.dashboard = {};

this.dashboard has type IDashboard, i guess it has at least one to optional field. So you can't set object without setting this required fields.
Something like:

interface Person {
  name: string;
}

const person = {} // Error
const person1 = {name: 'Test'} // No Error

interface Person1 {
 name?: string; //name is optional field
}
 const person = {} // No Error


问:
Loop synchronization deadlock
I've got the following classes in Java

```<code>public class Counter {
    private int value;

    public Counter(int value) {
        this.value = value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public void decrement() {
        this.value--;
    }
    public int getValue() {
        return this.value;
    }
}

public class Cell extends Thread {

    private Object sync;
    private Counter counter;

    public Cell(Object sync, Counter counter) {
        this.sync = sync;
        this.counter = counter;
    }

    public void run() {
        for (int r=0; r<Simulation.ROUND_NUM; r++) {

            // do something

            synchronized(counter) {
                counter.decrement();
                counter.notifyAll();
            }
            synchronized(sync) {
                try {
                    sync.wait();
                }
                catch (Exception ex) {}
            }

        }
    }
}

public class Simulation extends Thread {

    public static final int THREAD_NUM = 5;
    public static final int ROUND_NUM = 5;

    public Object sync = new Object();
    private Counter counter = new Counter(THREAD_NUM);

    public void run() {

        for (int i=0; i<THREAD_NUM; i++) {
            Cell c = new Cell(sync,counter);
            c.start();
        }

        for (int i=0; i<ROUND_NUM; i++) {
            synchronized(counter) {
                while(counter.getValue() != 0) {
                    try {
                        counter.wait();
                    }
                    catch (Exception ex) {}
                }
                counter.setValue(THREAD_NUM);
            }

            synchronized(sync) {
                sync.notifyAll();
            }
        }
    }
}
</code>```

The aim is to prevent from executing the next iteration of loop in each Cell Thread, until every Cell Thread will be done on each iteration. My solution sometimes leads to deadlock. I can't understand why. Please help

答: This is not a deadlock.  Your main thread can miss a notify on the counter and will be stuck on counter.wait() after it is alread at 0.  Use jstack JDK tool to analyze what threads are doing in a situation like this.</p>

Title: Loop synchronization deadlock

Body:
I've got the following classes in Java

public class Counter {
    private int value;

    public Counter(int value) {
        this.value = value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public void decrement() {
        this.value--;
    }
    public int getValue() {
        return this.value;
    }
}

public class Cell extends Thread {

    private Object sync;
    private Counter counter;

    public Cell(Object sync, Counter counter) {
        this.sync = sync;
        this.counter = counter;
    }

    public void run() {
        for (int r=0; r<Simulation.ROUND_NUM; r++) {

            // do something

            synchronized(counter) {
                counter.decrement();
                counter.notifyAll();
            }
            synchronized(sync) {
                try {
                    sync.wait();
                }
                catch (Exception ex) {}
            }

        }
    }
}

public class Simulation extends Thread {

    public static final int THREAD_NUM = 5;
    public static final int ROUND_NUM = 5;

    public Object sync = new Object();
    private Counter counter = new Counter(THREAD_NUM);

    public void run() {

        for (int i=0; i<THREAD_NUM; i++) {
            Cell c = new Cell(sync,counter);
            c.start();
        }

        for (int i=0; i<ROUND_NUM; i++) {
            synchronized(counter) {
                while(counter.getValue() != 0) {
                    try {
                        counter.wait();
                    }
                    catch (Exception ex) {}
                }
                counter.setValue(THREAD_NUM);
            }

            synchronized(sync) {
                sync.notifyAll();
            }
        }
    }
}

The aim is to prevent from executing the next iteration of loop in each Cell Thread, until every Cell Thread will be done on each iteration. My solution sometimes leads to deadlock. I can't understand why. Please help


问:
Selectively removing trailing string
I want to remove the last letter "O", except where is is part of the word "HELLO".

I've tried doing this:

Example:

```<code>a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("[^HELLO]O\\>","",a)

[1] "HELLO " " HELLO" "T " "HO"
</code>```

but I want

```<code>"HELLO X" "D HELLO" "TW X" "H"
</code>```

答:
Try replacing using the following pattern:

```<code>\b(?!HELLO\b)(\w+)O\b
</code>```

This says to assert that the word HELLO does not appear as the word, and then captures everything up until the final O, should it occur.  Then, it replaces with that optional final O removed.

```<code>\b          - from the start of the word
(?!HELLO\b) - assert that the word is not HELLO
(\w+)O      - match a word ending in O, but don't capture final O
\b          - end of word
</code>```

The capture group, if a match happens, will contain the entire word minus the final O.

Code:

```<code>a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("\\b(?!HELLO\\b)(\\w+)O\\b", "\\1", a, perl=TRUE)
[1] "HELLO X" "D HELLO" "TW X"    "H"
</code>```

Note that we must Perl mode enabled (perl=TRUE) with gsub in order to use the negative lookahead.

Demo

Title: Selectively removing trailing string

Body:
I want to remove the last letter "O", except where is is part of the word "HELLO".

I've tried doing this:

Example:

a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("[^HELLO]O\\>","",a)

[1] "HELLO " " HELLO" "T " "HO"

but I want

"HELLO X" "D HELLO" "TW X" "H"

Body:
Try replacing using the following pattern:

\b(?!HELLO\b)(\w+)O\b

This says to assert that the word HELLO does not appear as the word, and then captures everything up until the final O, should it occur.  Then, it replaces with that optional final O removed.

\b          - from the start of the word
(?!HELLO\b) - assert that the word is not HELLO
(\w+)O      - match a word ending in O, but don't capture final O
\b          - end of word

The capture group, if a match happens, will contain the entire word minus the final O.

Code:

a <- c("HELLO XO","DO HELLO","TWO XO","HO")
gsub("\\b(?!HELLO\\b)(\\w+)O\\b", "\\1", a, perl=TRUE)
[1] "HELLO X" "D HELLO" "TW X"    "H"

Note that we must Perl mode enabled (perl=TRUE) with gsub in order to use the negative lookahead.

Demo


问:
Positioning of footer text
I am trying to add a footer similar to the Airbnb one. I have been able to do the first two columns. However the third one is always slightly below the rest. I've tried:
Position: Absolute (however this makes it disappear)
Position: relative (this works fine however it remove the links from the other two columns).
Float: right and left but doesn't let me move it up.

I'm running out of ideas of what to do so if someone could help me that would be great. here is my code and a image of what I have made.

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
  -moz-box-shadow: 0 5px 10px -6px black;
  box-shadow: 0 5px 10px -6px black;
  /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%;
  /* NOTE: where the footer sits on page */
}

.footer-links {
  color: white;
}

.footer-links:hover {
  color: black;
}

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}

.col-1 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
}

.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 550px;
  padding-bottom: 100px;
  bottom: 100px;
  color: white;
  font-weight: bold;
  display: table;
  float: left;
  positi
}

.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>

  <div class="col-1">
    Revel
    <hr>
    <span> About us       </span>
    <span> Contact us     </span>
    <span> FAQ            </span>
    <span> Careers        </span>
  </div>

  <div class="col-2">
    Event Host
    <hr>
    <span>  Why use Revel  </span>
    <span>  test           </span>
    <span>  test           </span>
    <span>  Join Revel     </span>
  </div>

  <div class="col-3">
    Event Service
    <hr>
    <span> Why partner with Revel  </span>
    <span> Guidebooks              </span>
    <span> FAQ                     </span>
    <span> Partner with Revel      </span>
  </div>

</footer></code>```

enter image description here

答:
You should use box-sizing: border-box; to prevent width increasing because of padding.

```<code>footer *{
   box-sizing:border-box;
}
</code>```

Use Flexbox for better alignment and positioning.

```<code>.footer{
   display: -webkit-flex;
   display: flex;
   -webkit-flex-direction: row /* works with row or column */
   flex-direction: row;
   -webkit-align-items: center;
   align-items: center;
   -webkit-justify-content: center;
   justify-content: center;
}
</code>```

Fiddle Demo here

Title: Positioning of footer text

Body:
I am trying to add a footer similar to the Airbnb one. I have been able to do the first two columns. However the third one is always slightly below the rest. I've tried:
Position: Absolute (however this makes it disappear)
Position: relative (this works fine however it remove the links from the other two columns).
Float: right and left but doesn't let me move it up.

I'm running out of ideas of what to do so if someone could help me that would be great. here is my code and a image of what I have made.

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
  -moz-box-shadow: 0 5px 10px -6px black;
  box-shadow: 0 5px 10px -6px black;
  /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%;
  /* NOTE: where the footer sits on page */
}

.footer-links {
  color: white;
}

.footer-links:hover {
  color: black;
}

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}

.col-1 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
}

.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 550px;
  padding-bottom: 100px;
  bottom: 100px;
  color: white;
  font-weight: bold;
  display: table;
  float: left;
  positi
}

.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

    Revel

     About us
     Contact us
     FAQ
     Careers

    Event Host

      Why use Revel
      test
      test
      Join Revel

    Event Service

     Why partner with Revel
     Guidebooks
     FAQ
     Partner with Revel

enter image description here

Body:
You should use box-sizing: border-box; to prevent width increasing because of padding.

footer *{
   box-sizing:border-box;
}

Use Flexbox for better alignment and positioning.

.footer{
   display: -webkit-flex;
   display: flex;
   -webkit-flex-direction: row /* works with row or column */
   flex-direction: row;
   -webkit-align-items: center;
   align-items: center;
   -webkit-justify-content: center;
   justify-content: center;
}

Fiddle Demo here