问:
.Resources$NotFoundException: String resource ID #0x3
In my application when i pass an intent into another class,so that user can send sms messages and that data get stored in database,..and when user click on select contact button he get the contacts checked on which he send the messages,firstly it worked fine but when i added update code on button click it start giving back the error..and logcat is showing me the error

```<code>03-24 11:45:10.811: E/AndroidRuntime(18748): android.content.res.Resources$NotFoundException: String resource ID #0x3
        03-24 11:45:10.811: E/AndroidRuntime(18748):    at android.widget.Toast.makeText(Toast.java:311)
</code>```

smsSend.java

```<code>    public class SmsSend extends Activity implements OnClickListener {
        BroadcastReceiver smsSentReciver, smsSentDelivery;
        static EditText edName, edMessage;
        static int ResultCode = 12;
        static ArrayList<String> sendlist = new ArrayList<String>();
        Button btnSaveForLater, btnStart, btnExternal, btnSelect;
        static TextView txt;
        static StringBuilder conct = new StringBuilder();
        static String contacts = "";
        String delim = ";";
        public static String Name;
        TextView ed;
        int i = 0;
        String rowid, rowid1, value;
        int j;
        String Name1, msg, msg1;
        String[] cellArray;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.create_camp);

            btnExternal.setOnClickListener(this);
            txt = (TextView) findViewById(R.id.textnum2);
            ActionBar actionBar = getActionBar();
            actionBar.setDisplayHomeAsUpEnabled(true);

            rowid = getIntent().getStringExtra("rowid");
            value = getIntent().getStringExtra("key");
            rowid1 = getIntent().getStringExtra("rowid1");
            entryData();

            edName.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    edName.setError(null);
                }
            });
            edMessage.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    edMessage.setError(null);
                }
            });
            txt.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    txt.setError(null);
                }
            });
            // Toast.makeText(getApplication(), contacts.toString(),
            // Toast.LENGTH_LONG).show();
            Name1 = edName.getText().toString();

            msg1 = edMessage.getText().toString();
        }

        @Override
        public void onBackPressed() {
            // TODO Auto-generated method stub
            super.onBackPressed();
            edName.setText(null);
            edMessage.setText(null);
            conct.delete(0, conct.length());
            contacts = null;
            txt.setText("0");
        }

        @Override
        protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            unregisterReceiver(smsSentReciver);
            unregisterReceiver(smsSentDelivery);
        }

        @Override
        protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();

            smsSentReciver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    // TODO Auto-generated method stub
                    switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "sms has been sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic Fail",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No Service",
                                Toast.LENGTH_SHORT).show();

                    default:
                        break;

                    }
                }

            };
            smsSentDelivery = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {
                    // TODO Auto-generated method stub
                    switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "Sms Delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "Sms not Delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    }
                }

            };
            registerReceiver(smsSentReciver, new IntentFilter("SMS_SENT"));
            registerReceiver(smsSentDelivery, new IntentFilter("SMS_DELIVERED"));

        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            DatabaseHelp entry = new DatabaseHelp(SmsSend.this);
            entry.open();
            switch (v.getId()) {

            case R.id.btnSelect:

                Intent a = new Intent(SmsSend.this, MainActivity.class);
                startActivityForResult(a,ResultCode);
                break;
            case R.id.btnExternal:
                Intent file = new Intent(SmsSend.this, File_Selecter.class);
                startActivity(file);
                break;

            case R.id.btnStart:

                Log.i("SMS", "Sendlist Size: " + sendlist.size());
                if (edName.getText().toString().length() == 0
                        || edName.getText().toString().length() == 0
                        || txt.getText().equals("0")) {
                    edName.setError("First name is required!");
                    edMessage.setError("Message is required!");
                    txt.setError("Contacts required!");
                } else {

                    /*  if (rowid1 != null
                                && edName.getText().toString().length() != 0
                                && edName.getText().toString().length() != 0
                                && txt.getText().equals("0")
                                && edName.getText().toString() == value) {
                            Toast.makeText(getApplication(), "update", Toast.LENGTH_LONG).show();
                            SmsManager smsManager = SmsManager.getDefault();

                            PendingIntent piSend = PendingIntent.getBroadcast(this,
                                    0, new Intent("SMS_SENT"), 0);
                            PendingIntent piDelivered = PendingIntent.getBroadcast(
                                    this, 0, new Intent("SMS_DELIVERED"), 0);

                            Log.i("SMS", "contacts: " + contacts);

                            contacts = conct.toString();

                            cellArray = contacts.split(";");

                            for (int a1 = 0; a1 < cellArray.length; a1++) {

                                smsManager.sendTextMessage(cellArray[i].toString(),
                                        null, msg1, piSend, piDelivered);

                            }
                            long ltt = Long.parseLong(rowid1);
                            entry.updateEntry(ltt, Name1, msg1, contacts);
                            Toast.makeText(getApplication(), "updated",
                                    Toast.LENGTH_LONG).show();

                        } else {*/
                            boolean diditwork1 = true;
                            try {
                                Toast.makeText(getApplication(), "insert", Toast.LENGTH_LONG).show();

                            SmsManager smsManager = SmsManager.getDefault();

                            PendingIntent piSend = PendingIntent.getBroadcast(this,
                                    0, new Intent("SMS_SENT"), 0);
                            PendingIntent piDelivered = PendingIntent.getBroadcast(
                                    this, 0, new Intent("SMS_DELIVERED"), 0);

                            Log.i("SMS", "contacts: " + contacts);

                            contacts = conct.toString();
                            //Toast.makeText(getApplication(), contacts.toString(), Toast.LENGTH_LONG).show();
                            cellArray = contacts.split(";");
                            Toast.makeText(getApplication(), cellArray.length, Toast.LENGTH_LONG).show();
                            for (int a1 = 0; a1 < cellArray.length; a1++) {

                                smsManager.sendTextMessage(cellArray[i].toString(),
                                        null, msg1, piSend, piDelivered);

                            }

                            DatabaseHelp entry1 = new DatabaseHelp(SmsSend.this);
                            entry1.open();

                            entry1.entryCreate(Name1, msg1, contacts);

                            entry1.close();
                        }
                     catch (Exception e) {
                        diditwork1 = false;
                        String erroe = e.toString();

                        Dialog d = new Dialog(this);
                        d.setTitle("Dang it!");
                        TextView tv = new TextView(this);
                        tv.setText(erroe);
                        d.setContentView(tv);
                        d.show();

                    } finally {
                        if (diditwork1) {
                            Dialog d = new Dialog(this);
                            d.setTitle("Heck Yeah!");
                            TextView tv = new TextView(this);
                            tv.setText("Success");
                            d.setContentView(tv);
                            d.show();
                        }
                    }

                }

                edName.setText("");
                edMessage.setText("");
                txt.setText("0");

                break;
            }
            }
        //}

        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            if (requestCode == ResultCode) {

                if (resultCode == RESULT_OK) {
                        sendlist = data.getStringArrayListExtra("name");
                        Toast.makeText(getApplication(), sendlist.size(), Toast.LENGTH_LONG).show();
                    if (sendlist != null) {

                        for (int i = 0; i < sendlist.size(); i++) {
                            conct.append(sendlist.get(i).toString());
                            conct.append(delim);
                            //Toast.makeText(getApplication(), conct.toString(),Toast.LENGTH_LONG).show();
                        }

                    }

                }

                i = sendlist.size();
                txt.setText(Integer.toString(i));
                if (resultCode == RESULT_CANCELED) {

                }

            }
        }

    }
</code>```

MainaActiivty.java

```<code>    public class MainActivity extends Activity implements OnItemClickListener {

        ArrayList<String> name1 = new ArrayList<String>();
        static ArrayList<String> phno1 = new ArrayList<String>();
        ArrayList<String> phno0 = new ArrayList<String>();
        MyAdapter ma;
        Button send;
        String[] cellArray = null;
        int[] str;
        int v = 0;
        String contacts;
        static int check1;
        ListView lv;
        int index;
        int top;
        StringBuilder b = new StringBuilder();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            ActionBar actionBar = getActionBar();
            actionBar.setDisplayHomeAsUpEnabled(true);
            setContentView(R.layout.get);
        //  TextView txt = (TextView) findViewById(R.id.textView1);
            getAllCallLogs(this.getContentResolver());
            lv = (ListView) findViewById(R.id.lv);
            ma = new MyAdapter();
            lv.setAdapter(ma);
            lv.setOnItemClickListener(this);
            lv.setItemsCanFocus(false);
            lv.setTextFilterEnabled(true);
            // b = SmsSend.contacts;

            contacts = SmsSend.contacts;
            if (SmsSend.contacts != null) {
                cellArray = contacts.split(";");
                // Toast.makeText(getApplication(),contacts.toString(),
                // Toast.LENGTH_LONG).show();
                for (int i = 0; i < cellArray.length; i++) {

                    for (int j = 0; j < phno1.size(); j++) {

                        if (cellArray[i].equals(phno1.get(j))) {
                             Toast.makeText(getApplication(),cellArray[i].toString(),
                             Toast.LENGTH_LONG).show();
                            ma.setChecked(j, true);

                        }
                    }

                }
            }

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            // TODO Auto-generated method stub
            getMenuInflater().inflate(R.menu.contact_main, menu);

            return true;

        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // TODO Auto-generated method stub

            switch (item.getItemId()) {
            case R.id.addPage:

                break;

            }
            return super.onOptionsItemSelected(item);
        }

        @Override
        public void onBackPressed() {
            // TODO Auto-generated method stub

            StringBuilder checkedcontacts = new StringBuilder();
            System.out.println(".............." + ma.mCheckStates.size());
            for (int i = 0; i < name1.size(); i++)

            {
                if (ma.mCheckStates.get(i) == true) {
                    phno0.add(phno1.get(i).toString());
                    checkedcontacts.append(name1.get(i).toString());
                    checkedcontacts.append("\n");

                } else {
                    System.out.println("..Not Checked......"
                            + name1.get(i).toString());
                }

            }

            Intent returnIntent = new Intent();
            returnIntent.putStringArrayListExtra("name", phno0);
            setResult(RESULT_OK, returnIntent);
            Toast.makeText(getApplication(), phno0.size(), Toast.LENGTH_LONG).show();
            finish();

        }

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            // TODO Auto-generated method stub
            ma.toggle(arg2);

        }

        public void getAllCallLogs(ContentResolver cr) {

            Cursor phones = cr.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
                    null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                            + " ASC");
            while (phones.moveToNext()) {
                String phoneNumber = phones
                        .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                String name = phones
                        .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

                System.out.println(phoneNumber);

                name1.add(name);
                phno1.add(phoneNumber);

            }

            phones.close();

        }

        class MyAdapter extends BaseAdapter implements
                CompoundButton.OnCheckedChangeListener {
            public SparseBooleanArray mCheckStates;
            LayoutInflater mInflater;
            TextView tv1, tv;
            CheckBox cb;

            MyAdapter() {
                mCheckStates = new SparseBooleanArray(name1.size());
                mInflater = (LayoutInflater) MainActivity.this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            }

            // Save ListView state

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return name1.size();
            }

            @Override
            public Object getItem(int position) {
                // TODO Auto-generated method stub

                return position;
            }

            @Override
            public long getItemId(int position) {
                // TODO Auto-generated method stub

                return 0;
            }

            @Override
            public View getView(final int position, View convertView,
                    ViewGroup parent) {
                // TODO Auto-generated method stub
                View vi = convertView;
                if (convertView == null)
                    vi = mInflater.inflate(R.layout.row, null);
                tv = (TextView) vi.findViewById(R.id.textView1);
                tv1 = (TextView) vi.findViewById(R.id.textView2);
                cb = (CheckBox) vi.findViewById(R.id.checkBox1);
                tv.setText(name1.get(position));
                tv1.setText(phno1.get(position));
                cb.setTag(position);

                cb.setChecked(mCheckStates.get(position, false));
                cb.setOnCheckedChangeListener(this);

                return vi;

            }

            public boolean isChecked(int position) {

                return mCheckStates.get(position, false);
            }

            public void setChecked(int position, boolean isChecked) {
                mCheckStates.put(position, isChecked);
            }

            public void toggle(int position) {
                setChecked(position, !isChecked(position));
            }

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                mCheckStates.put((Integer) buttonView.getTag(), isChecked);

            }
        }

    }
</code>```

答:
try this one</p>

```<code>Toast.makeText(ExploreMatchDetail.this,sendlist.size()+"",Toast.LENGTH_SHORT).show();
</code>```

Body:
In my application when i pass an intent into another class,so that user can send sms messages and that data get stored in database,..and when user click on select contact button he get the contacts checked on which he send the messages,firstly it worked fine but when i added update code on button click it start giving back the error..and logcat is showing me the error

03-24 11:45:10.811: E/AndroidRuntime(18748): android.content.res.Resources$NotFoundException: String resource ID #0x3
        03-24 11:45:10.811: E/AndroidRuntime(18748):    at android.widget.Toast.makeText(Toast.java:311)

smsSend.java

    public class SmsSend extends Activity implements OnClickListener {
        BroadcastReceiver smsSentReciver, smsSentDelivery;
        static EditText edName, edMessage;
        static int ResultCode = 12;
        static ArrayList<String> sendlist = new ArrayList<String>();
        Button btnSaveForLater, btnStart, btnExternal, btnSelect;
        static TextView txt;
        static StringBuilder conct = new StringBuilder();
        static String contacts = "";
        String delim = ";";
        public static String Name;
        TextView ed;
        int i = 0;
        String rowid, rowid1, value;
        int j;
        String Name1, msg, msg1;
        String[] cellArray;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.create_camp);

            btnExternal.setOnClickListener(this);
            txt = (TextView) findViewById(R.id.textnum2);
            ActionBar actionBar = getActionBar();
            actionBar.setDisplayHomeAsUpEnabled(true);

            rowid = getIntent().getStringExtra("rowid");
            value = getIntent().getStringExtra("key");
            rowid1 = getIntent().getStringExtra("rowid1");
            entryData();

            edName.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    edName.setError(null);
                }
            });
            edMessage.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    edMessage.setError(null);
                }
            });
            txt.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    txt.setError(null);
                }
            });
            // Toast.makeText(getApplication(), contacts.toString(),
            // Toast.LENGTH_LONG).show();
            Name1 = edName.getText().toString();

            msg1 = edMessage.getText().toString();
        }

        @Override
        public void onBackPressed() {
            // TODO Auto-generated method stub
            super.onBackPressed();
            edName.setText(null);
            edMessage.setText(null);
            conct.delete(0, conct.length());
            contacts = null;
            txt.setText("0");
        }

        @Override
        protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            unregisterReceiver(smsSentReciver);
            unregisterReceiver(smsSentDelivery);
        }

        @Override
        protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();

            smsSentReciver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    // TODO Auto-generated method stub
                    switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "sms has been sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic Fail",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No Service",
                                Toast.LENGTH_SHORT).show();

                    default:
                        break;

                    }
                }

            };
            smsSentDelivery = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context, Intent intent) {
                    // TODO Auto-generated method stub
                    switch (getResultCode()) {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "Sms Delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "Sms not Delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    }
                }

            };
            registerReceiver(smsSentReciver, new IntentFilter("SMS_SENT"));
            registerReceiver(smsSentDelivery, new IntentFilter("SMS_DELIVERED"));

        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            DatabaseHelp entry = new DatabaseHelp(SmsSend.this);
            entry.open();
            switch (v.getId()) {

            case R.id.btnSelect:

                Intent a = new Intent(SmsSend.this, MainActivity.class);
                startActivityForResult(a,ResultCode);
                break;
            case R.id.btnExternal:
                Intent file = new Intent(SmsSend.this, File_Selecter.class);
                startActivity(file);
                break;

            case R.id.btnStart:

                Log.i("SMS", "Sendlist Size: " + sendlist.size());
                if (edName.getText().toString().length() == 0
                        || edName.getText().toString().length() == 0
                        || txt.getText().equals("0")) {
                    edName.setError("First name is required!");
                    edMessage.setError("Message is required!");
                    txt.setError("Contacts required!");
                } else {

                    /*  if (rowid1 != null
                                && edName.getText().toString().length() != 0
                                && edName.getText().toString().length() != 0
                                && txt.getText().equals("0")
                                && edName.getText().toString() == value) {
                            Toast.makeText(getApplication(), "update", Toast.LENGTH_LONG).show();
                            SmsManager smsManager = SmsManager.getDefault();

                            PendingIntent piSend = PendingIntent.getBroadcast(this,
                                    0, new Intent("SMS_SENT"), 0);
                            PendingIntent piDelivered = PendingIntent.getBroadcast(
                                    this, 0, new Intent("SMS_DELIVERED"), 0);

                            Log.i("SMS", "contacts: " + contacts);

                            contacts = conct.toString();

                            cellArray = contacts.split(";");

                            for (int a1 = 0; a1 < cellArray.length; a1++) {

                                smsManager.sendTextMessage(cellArray[i].toString(),
                                        null, msg1, piSend, piDelivered);

                            }
                            long ltt = Long.parseLong(rowid1);
                            entry.updateEntry(ltt, Name1, msg1, contacts);
                            Toast.makeText(getApplication(), "updated",
                                    Toast.LENGTH_LONG).show();

                        } else {*/
                            boolean diditwork1 = true;
                            try {
                                Toast.makeText(getApplication(), "insert", Toast.LENGTH_LONG).show();

                            SmsManager smsManager = SmsManager.getDefault();

                            PendingIntent piSend = PendingIntent.getBroadcast(this,
                                    0, new Intent("SMS_SENT"), 0);
                            PendingIntent piDelivered = PendingIntent.getBroadcast(
                                    this, 0, new Intent("SMS_DELIVERED"), 0);

                            Log.i("SMS", "contacts: " + contacts);

                            contacts = conct.toString();
                            //Toast.makeText(getApplication(), contacts.toString(), Toast.LENGTH_LONG).show();
                            cellArray = contacts.split(";");
                            Toast.makeText(getApplication(), cellArray.length, Toast.LENGTH_LONG).show();
                            for (int a1 = 0; a1 < cellArray.length; a1++) {

                                smsManager.sendTextMessage(cellArray[i].toString(),
                                        null, msg1, piSend, piDelivered);

                            }

                            DatabaseHelp entry1 = new DatabaseHelp(SmsSend.this);
                            entry1.open();

                            entry1.entryCreate(Name1, msg1, contacts);

                            entry1.close();
                        }
                     catch (Exception e) {
                        diditwork1 = false;
                        String erroe = e.toString();

                        Dialog d = new Dialog(this);
                        d.setTitle("Dang it!");
                        TextView tv = new TextView(this);
                        tv.setText(erroe);
                        d.setContentView(tv);
                        d.show();

                    } finally {
                        if (diditwork1) {
                            Dialog d = new Dialog(this);
                            d.setTitle("Heck Yeah!");
                            TextView tv = new TextView(this);
                            tv.setText("Success");
                            d.setContentView(tv);
                            d.show();
                        }
                    }

                }

                edName.setText("");
                edMessage.setText("");
                txt.setText("0");

                break;
            }
            }
        //}

        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            if (requestCode == ResultCode) {

                if (resultCode == RESULT_OK) {
                        sendlist = data.getStringArrayListExtra("name");
                        Toast.makeText(getApplication(), sendlist.size(), Toast.LENGTH_LONG).show();
                    if (sendlist != null) {

                        for (int i = 0; i < sendlist.size(); i++) {
                            conct.append(sendlist.get(i).toString());
                            conct.append(delim);
                            //Toast.makeText(getApplication(), conct.toString(),Toast.LENGTH_LONG).show();
                        }

                    }

                }

                i = sendlist.size();
                txt.setText(Integer.toString(i));
                if (resultCode == RESULT_CANCELED) {

                }

            }
        }

    }

MainaActiivty.java

    public class MainActivity extends Activity implements OnItemClickListener {

        ArrayList<String> name1 = new ArrayList<String>();
        static ArrayList<String> phno1 = new ArrayList<String>();
        ArrayList<String> phno0 = new ArrayList<String>();
        MyAdapter ma;
        Button send;
        String[] cellArray = null;
        int[] str;
        int v = 0;
        String contacts;
        static int check1;
        ListView lv;
        int index;
        int top;
        StringBuilder b = new StringBuilder();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            ActionBar actionBar = getActionBar();
            actionBar.setDisplayHomeAsUpEnabled(true);
            setContentView(R.layout.get);
        //  TextView txt = (TextView) findViewById(R.id.textView1);
            getAllCallLogs(this.getContentResolver());
            lv = (ListView) findViewById(R.id.lv);
            ma = new MyAdapter();
            lv.setAdapter(ma);
            lv.setOnItemClickListener(this);
            lv.setItemsCanFocus(false);
            lv.setTextFilterEnabled(true);
            // b = SmsSend.contacts;

            contacts = SmsSend.contacts;
            if (SmsSend.contacts != null) {
                cellArray = contacts.split(";");
                // Toast.makeText(getApplication(),contacts.toString(),
                // Toast.LENGTH_LONG).show();
                for (int i = 0; i < cellArray.length; i++) {

                    for (int j = 0; j < phno1.size(); j++) {

                        if (cellArray[i].equals(phno1.get(j))) {
                             Toast.makeText(getApplication(),cellArray[i].toString(),
                             Toast.LENGTH_LONG).show();
                            ma.setChecked(j, true);

                        }
                    }

                }
            }

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            // TODO Auto-generated method stub
            getMenuInflater().inflate(R.menu.contact_main, menu);

            return true;

        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // TODO Auto-generated method stub

            switch (item.getItemId()) {
            case R.id.addPage:

                break;

            }
            return super.onOptionsItemSelected(item);
        }

        @Override
        public void onBackPressed() {
            // TODO Auto-generated method stub

            StringBuilder checkedcontacts = new StringBuilder();
            System.out.println(".............." + ma.mCheckStates.size());
            for (int i = 0; i < name1.size(); i++)

            {
                if (ma.mCheckStates.get(i) == true) {
                    phno0.add(phno1.get(i).toString());
                    checkedcontacts.append(name1.get(i).toString());
                    checkedcontacts.append("\n");

                } else {
                    System.out.println("..Not Checked......"
                            + name1.get(i).toString());
                }

            }

            Intent returnIntent = new Intent();
            returnIntent.putStringArrayListExtra("name", phno0);
            setResult(RESULT_OK, returnIntent);
            Toast.makeText(getApplication(), phno0.size(), Toast.LENGTH_LONG).show();
            finish();

        }

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            // TODO Auto-generated method stub
            ma.toggle(arg2);

        }

        public void getAllCallLogs(ContentResolver cr) {

            Cursor phones = cr.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
                    null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
                            + " ASC");
            while (phones.moveToNext()) {
                String phoneNumber = phones
                        .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                String name = phones
                        .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

                System.out.println(phoneNumber);

                name1.add(name);
                phno1.add(phoneNumber);

            }

            phones.close();

        }

        class MyAdapter extends BaseAdapter implements
                CompoundButton.OnCheckedChangeListener {
            public SparseBooleanArray mCheckStates;
            LayoutInflater mInflater;
            TextView tv1, tv;
            CheckBox cb;

            MyAdapter() {
                mCheckStates = new SparseBooleanArray(name1.size());
                mInflater = (LayoutInflater) MainActivity.this
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            }

            // Save ListView state

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return name1.size();
            }

            @Override
            public Object getItem(int position) {
                // TODO Auto-generated method stub

                return position;
            }

            @Override
            public long getItemId(int position) {
                // TODO Auto-generated method stub

                return 0;
            }

            @Override
            public View getView(final int position, View convertView,
                    ViewGroup parent) {
                // TODO Auto-generated method stub
                View vi = convertView;
                if (convertView == null)
                    vi = mInflater.inflate(R.layout.row, null);
                tv = (TextView) vi.findViewById(R.id.textView1);
                tv1 = (TextView) vi.findViewById(R.id.textView2);
                cb = (CheckBox) vi.findViewById(R.id.checkBox1);
                tv.setText(name1.get(position));
                tv1.setText(phno1.get(position));
                cb.setTag(position);

                cb.setChecked(mCheckStates.get(position, false));
                cb.setOnCheckedChangeListener(this);

                return vi;

            }

            public boolean isChecked(int position) {

                return mCheckStates.get(position, false);
            }

            public void setChecked(int position, boolean isChecked) {
                mCheckStates.put(position, isChecked);
            }

            public void toggle(int position) {
                setChecked(position, !isChecked(position));
            }

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                mCheckStates.put((Integer) buttonView.getTag(), isChecked);

            }
        }

    }

Body:
try this one

Toast.makeText(ExploreMatchDetail.this,sendlist.size()+"",Toast.LENGTH_SHORT).show();


来源: stackexchange

问:
Add Bearer token option in swagger for particular version in web api
I am using Swagger in the Web API application. I have multiple versions of API, but I want to apply Bearer token option to version 2 only. There is no authentication for both versions. Here is my code:

```<code>services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    c.SwaggerDoc("v2", new OpenApiInfo { Title = "My API", Version = "v2" });

    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
    });
});
</code>```

答:
You can install NSwag.AspNetCore and add different options with different versions.

```<code>services.AddSwaggerDocument(a =>
{
    a.DocumentName = "v1";
    a.Version = "v1";
});

services.AddSwaggerDocument(a =>
{
    a.DocumentName = "v2";
    a.Version = "v2";
    a.AddSecurity("bearer", new NSwag.OpenApiSecurityScheme
    {
        Description = "jwt",
        In = NSwag.OpenApiSecurityApiKeyLocation.Header,
        Type = NSwag.OpenApiSecuritySchemeType.ApiKey,
        Scheme = "bearer"
    });
});
</code>```

```<code>app.UseOpenApi();
app.UseSwaggerUi3();
</code>```

You can read more about it in Microsoft Docs.

ContentLicense: CC BY-SA 4.0

Body:
I am using Swagger in the Web API application. I have multiple versions of API, but I want to apply Bearer token option to version 2 only. There is no authentication for both versions. Here is my code:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    c.SwaggerDoc("v2", new OpenApiInfo { Title = "My API", Version = "v2" });

    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,
    });
});

Body:
You can install NSwag.AspNetCore and add different options with different versions.

services.AddSwaggerDocument(a =>
{
    a.DocumentName = "v1";
    a.Version = "v1";
});

services.AddSwaggerDocument(a =>
{
    a.DocumentName = "v2";
    a.Version = "v2";
    a.AddSecurity("bearer", new NSwag.OpenApiSecurityScheme
    {
        Description = "jwt",
        In = NSwag.OpenApiSecurityApiKeyLocation.Header,
        Type = NSwag.OpenApiSecuritySchemeType.ApiKey,
        Scheme = "bearer"
    });
});

app.UseOpenApi();
app.UseSwaggerUi3();

You can read more about it in Microsoft Docs.


问:
vue-router change only one of the named view without affecting the others
I am testing with vue-router and come across this problem, what if i have two named views but i only want to change one of it without changing the default view. Currently I do it like this:

const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        default: Foo,
        change: Bar,
      }
    }
    {
      path: '/foo/test1',
      components: {
        default: Foo,
        change: test1,
      }
    }

    //is it possible to do it something like this?
    {
      path: '/:foo/test1',
      components: {
        default: :foo//<--- how to keep default to whatever it previously have?
        change: test1
      }
    }

  ]
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><router-view></router-view>
<router-view name="change"></router-view></code>```

I think i can do this with dynamic matching, get the current route name and pass it as param, but I need to keep the current default route (like some form inputs), so i'd rather want to change only one of the views without affecting the others... please help...

答:
I took long to find someone with the same problem!

I believe you solved it already but I think there is no solution when the named router-view isn't to be used by current route children.

What I mean is, can't use in your Vue app a router in a router-view (named or not) without loosing the current rendered view in other route unless it is through defining it in children route.

What I've seen was by using the same component as parent component entry and has children components entry, in the same router-view it doesn't loose what was rendered by parent route. [https://dev.to/berniwittmann/handling-dialogs-with-vue-router-29ji]

What I did was removed it from the router, render it in the same place where the router-view was, unattached from any route, now is working as intended!

Hope it helps. (even after some years later)

ContentLicense: CC BY-SA 3.0

Body:
I am testing with vue-router and come across this problem, what if i have two named views but i only want to change one of it without changing the default view. Currently I do it like this:

const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        default: Foo,
        change: Bar,
      }
    }
    {
      path: '/foo/test1',
      components: {
        default: Foo,
        change: test1,
      }
    }

    //is it possible to do it something like this?
    {
      path: '/:foo/test1',
      components: {
        default: :foo//<--- how to keep default to whatever it previously have?
        change: test1
      }
    }

  ]
})

<router-view></router-view>
<router-view name="change"></router-view>

I think i can do this with dynamic matching, get the current route name and pass it as param, but I need to keep the current default route (like some form inputs), so i'd rather want to change only one of the views without affecting the others... please help...


问:
ASP.net c# Error, CS1061: 'Web2Print.ArtworkLabel' does not contain a definition for 'ID' and no extension method 'ID'
The error I am getting is:

CS1061: 'Web2Print.ArtworkLabel' does
  not contain a definition for 'ID' and
  no extension method 'ID' accepting a
  first argument of type
  'Web2Print.ArtworkLabel' could be
  found (are you missing a using
  directive or an assembly reference?)

On the line:

```<code>string FormVal = Request.Form["label" + TheLabel.ID];
</code>```

The code block the line is in is:

```<code>public void SaveData(object sender, EventArgs e)
{
    // New data record
    ArtworkData DataRecord = new ArtworkData(DataID);
    DataRecord.LoadTemplate();
    DataRecord.Template.LoadLabels();
    DataRecord.LoadDataLabels();

    // Delete all from DB
    ArtworkCommon.DeleteDataLabels(DataID);

    ArrayList LabelsCollection = new ArrayList();

    // Loop through all the fields
    foreach (ArtworkLabel TheLabel in DataRecord.Template.Labels)
    {
        string FormVal = Request.Form["label" + TheLabel.ID];
</code>```

The definition of ArtworkLabel is:

```<code>/// <summary>
/// A template label
/// </summary>
public class ArtworkLabel
{
    public bool Loaded { get; set; }
    public int ID { get; set; }
    public string Text { get; set; }
    public LabelStyle Style { get; set; }
    public Coordinate Coords { get; set; }
    public int TemplateID { get; set; }
    public int PageNumber { get; set; }
</code>```

The code isn't very well formed, I know.  The function throwing the error exists in namespace Web2Print, but the ArtworkLabel class does not exist in a namespace.  I don't think this should be a problem.

I've tried rebuilding, clearing temp files as well.

答:
The function throwing the error exists
  in namespace Web2Print, but the
  ArtworkLabel class does not exist in a
  namespace

Everything must be in a namespace.  Figure out what namespace ArtworkLabel is in, and refer to it as ArtworkLabelNameSpace.ArtworkLabel.

Also check if there's a control called ArtworkLabel in your ASPX file; the error message sounds like it actually finds a matching object, but the object doesn't define an ID property.

Body:
The error I am getting is:

CS1061: 'Web2Print.ArtworkLabel' does
  not contain a definition for 'ID' and
  no extension method 'ID' accepting a
  first argument of type
  'Web2Print.ArtworkLabel' could be
  found (are you missing a using
  directive or an assembly reference?)

On the line:

string FormVal = Request.Form["label" + TheLabel.ID];

The code block the line is in is:

public void SaveData(object sender, EventArgs e)
{
    // New data record
    ArtworkData DataRecord = new ArtworkData(DataID);
    DataRecord.LoadTemplate();
    DataRecord.Template.LoadLabels();
    DataRecord.LoadDataLabels();

    // Delete all from DB
    ArtworkCommon.DeleteDataLabels(DataID);

    ArrayList LabelsCollection = new ArrayList();

    // Loop through all the fields
    foreach (ArtworkLabel TheLabel in DataRecord.Template.Labels)
    {
        string FormVal = Request.Form["label" + TheLabel.ID];

The definition of ArtworkLabel is:

///
/// A template label
///
public class ArtworkLabel
{
    public bool Loaded { get; set; }
    public int ID { get; set; }
    public string Text { get; set; }
    public LabelStyle Style { get; set; }
    public Coordinate Coords { get; set; }
    public int TemplateID { get; set; }
    public int PageNumber { get; set; }

The code isn't very well formed, I know.  The function throwing the error exists in namespace Web2Print, but the ArtworkLabel class does not exist in a namespace.  I don't think this should be a problem.

I've tried rebuilding, clearing temp files as well.


问:
Is Actions for Families mandatory for Actions targeting children?
I have an Action that requires email address or Account Linking and is primarily made for children.
But Actions for Families disallows use of Account Linking.

Can I publish an Action designed for kids but not a part of Actions for Families?

答:
I am not a lawyer, StackOverflow is not a suitable place for legal advice, and if in doubt you should consult your own lawyer.

However, the answer is probably "no". If your action is "designed for kids", you must make it part of the Actions for Family program.

As per the Actions on Google policies:

If your Action targets children or provides content explicitly for children, it must participate in the Actions for Families program. This includes both Actions targeting children as their primary audience or as one of their audiences.


问:
Convert MySQL (JSON) Query Into Laravel Eloquent
I am trying to convert a MySQL query (having mysql-json functions in it) into a Laravel Eloquent query. Below is my Mysql query. I have to build this eloquent query in laravel version 5.3. Tried and stuck at json functions

MYSQL Query :

```<code>SELECT  id FROM `house_json`  WHERE JSON_CONTAINS( JSON_EXTRACT(construction_json, "$.house.room[*].window"), '"Removed"' ) AND form_id=5 AND action_date BETWEEN '2020-05-25' AND '2020-05-27'
</code>```

Eloquent Query :

```<code>$data_query = HouseData::select('house_json.id as ID')
->where('house_json.form_id',5)
->whereBetween('house_json.action_date', ['2020-05-25', '2020-05-27']) ->whereRaw('json_contains("json_extract("house_json.construction_json", "$.house.room[*].window")", '"Removed"')')
->get();
</code>```

sample JSON (which is stored into table field named - construction_json) :

```<code>{
  "visit_date": "2020-05-25",
  "operative_name": "Peter",
  "tenant_name": "Denny",
  "id": "433",
  "house": {
    "room": [
      {
        "appliance_id": "72329",
        "landlord": "Yes",
        "location_id": 4,
        "location_name": "Back Hall",
        "status": "Removed",
        "comment": "",
        "reason": "Landlord denied"
      },
      {
        "appliance_id": "72330",
        "landlord": "Yes",
        "location_id": 4,
        "location_name": "Kitchen",
        "status": "Completed",
        "comment": "",
        "reason": ""
      }
    ],
    "other_detail": {
      "pipework_done": "Yes",
      "paperwork_done": "No",
      "general_comments": ""
    }
  }
}
</code>```

答:
Try this I had the same issue earlier I solved as below.</p>

```<code>
$data_query = HouseData::select('house_json.id as ID')->
where('house_json.form_id', 5)->
whereBetween('house_json.action_date', ['2020-05-25', '2020-05-27'])->
whereRaw('JSON_CONTAINS(
    JSON_EXTRACT(
        house_json.construction_json,
        "$.house.room[*].window"),
    "Removed")')->
get();

</code>```

Body:
I am trying to convert a MySQL query (having mysql-json functions in it) into a Laravel Eloquent query. Below is my Mysql query. I have to build this eloquent query in laravel version 5.3. Tried and stuck at json functions

MYSQL Query :

SELECT  id FROM `house_json`  WHERE JSON_CONTAINS( JSON_EXTRACT(construction_json, "$.house.room[*].window"), '"Removed"' ) AND form_id=5 AND action_date BETWEEN '2020-05-25' AND '2020-05-27'

Eloquent Query :

$data_query = HouseData::select('house_json.id as ID')
->where('house_json.form_id',5)
->whereBetween('house_json.action_date', ['2020-05-25', '2020-05-27']) ->whereRaw('json_contains("json_extract("house_json.construction_json", "$.house.room[*].window")", '"Removed"')')
->get();

sample JSON (which is stored into table field named - construction_json) :

{
  "visit_date": "2020-05-25",
  "operative_name": "Peter",
  "tenant_name": "Denny",
  "id": "433",
  "house": {
    "room": [
      {
        "appliance_id": "72329",
        "landlord": "Yes",
        "location_id": 4,
        "location_name": "Back Hall",
        "status": "Removed",
        "comment": "",
        "reason": "Landlord denied"
      },
      {
        "appliance_id": "72330",
        "landlord": "Yes",
        "location_id": 4,
        "location_name": "Kitchen",
        "status": "Completed",
        "comment": "",
        "reason": ""
      }
    ],
    "other_detail": {
      "pipework_done": "Yes",
      "paperwork_done": "No",
      "general_comments": ""
    }
  }
}

Body:
Try this I had the same issue earlier I solved as below.

$data_query = HouseData::select('house_json.id as ID')->
where('house_json.form_id', 5)->
whereBetween('house_json.action_date', ['2020-05-25', '2020-05-27'])->
whereRaw('JSON_CONTAINS(
    JSON_EXTRACT(
        house_json.construction_json,
        "$.house.room[*].window"),
    "Removed")')->
get();


问:
C# Exchange Web Services Managed API Impersonation -> Microsoft Graph API
I have a c# application that queries our Microsoft Exchange servers (now Exchange Online).  It was written using Microsoft.Exchange.WebServices .NET library.  The application pool in IIS runs under an account with elevated permissions in Exchange.  This allows it to query the calendars of all users so that the application can show if they are busy/out of office or working elsewhere.  _service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, emailAddress); sets the service tells the service that the app pool account will be impersonating the user (email address) to query the calendar.

All of that being said, the Microsoft Exchange Web Services Managed API will be depreciated by the end of this year.  I want to re-write this process with Microsoft Graph.  I have found a good amount of information on how to access the exchange data and query calendars by using this.

Does anyone have any good examples they have found of how to accomplish the function below using Microsoft Graph API?  Is there a .NET wrapper class I can use or do I need to use the REST web service endpoints and create my own?

```<code>public FindItemsResults<Appointment> GetCalendarAppointments(string emailAddress, string calendarName, DateTime start, DateTime end)
{
        // start with on prem exchange
        _service.UseDefaultCredentials = true; // use app pool security context
        _service.Url = new Uri(ConfigurationManager.ConnectionStrings["ExchangeURL"].ConnectionString);

        _service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, emailAddress);

        FolderView folderView = new FolderView(25);
        folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly);
        folderView.PropertySet.Add(FolderSchema.DisplayName);
        SearchFilter searchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, calendarName);
        folderView.Traversal = FolderTraversal.Deep;
        FindFoldersResults findFolderResults = _service.FindFolders(WellKnownFolderName.Root, searchFilter, folderView);

        if (findFolderResults.TotalCount == 0)
            return null;

        FindItemsResults<Appointment> appointments;
        CalendarFolder calendarFolder;
        CalendarView calendarView = new CalendarView(start, end, 30);

        calendarView.PropertySet = new PropertySet(AppointmentSchema.Id,
                                                    AppointmentSchema.Start,
                                                    AppointmentSchema.End,
                                                    AppointmentSchema.Subject,
                                                    AppointmentSchema.Location);

        calendarFolder = (CalendarFolder)findFolderResults.Folders[0];

        try
        {
            appointments = calendarFolder.FindAppointments(calendarView);
        }
        catch (Exception e)
        {
            if (e.Message == "The SMTP address has no mailbox associated with it.")
            {
                // try exchange online
                _service.Credentials = new WebCredentials(ConfigurationManager.ConnectionStrings["ExchangeOnlineServiceAccountUsername"].ConnectionString,
                                                          ConfigurationManager.ConnectionStrings["ExchangeOnlineServiceAccountPassword"].ConnectionString);

                _service.Url = new Uri(ConfigurationManager.ConnectionStrings["ExchangeOnlineUrl"].ConnectionString);

                try
                {
                    appointments = calendarFolder.FindAppointments(calendarView);
                }
                catch (Exception ex)
                {
                    throw new Exception("Error when trying to read exchange to get calendar " + calendarName + " from exchange online inbox " + emailAddress + ": " + ex.Message);
                }

            }
            else
            {
                throw new Exception("Error when trying to read exchange to get calendar " + calendarName + " from on prem exchange inbox " + emailAddress + ": " + e.Message);
            }
        }

        if (appointments == null || appointments.Items.Count < 1)
            return null;

        return appointments;
}
</code>```

答:
@Eric
You can use the sdk's provided by Microsoft and achieve the above functionalities with the Graph API Endpoints. The overview of the sdk's for various platforms along with examples can be found here.

You can also try the Graph explorer and their postman collection to have an idea on the API endpoints.

Github link to MS-GRAPH-DOTNET-SDK.

Body:
I have a c# application that queries our Microsoft Exchange servers (now Exchange Online).  It was written using Microsoft.Exchange.WebServices .NET library.  The application pool in IIS runs under an account with elevated permissions in Exchange.  This allows it to query the calendars of all users so that the application can show if they are busy/out of office or working elsewhere.  _service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, emailAddress); sets the service tells the service that the app pool account will be impersonating the user (email address) to query the calendar.

All of that being said, the Microsoft Exchange Web Services Managed API will be depreciated by the end of this year.  I want to re-write this process with Microsoft Graph.  I have found a good amount of information on how to access the exchange data and query calendars by using this.

Does anyone have any good examples they have found of how to accomplish the function below using Microsoft Graph API?  Is there a .NET wrapper class I can use or do I need to use the REST web service endpoints and create my own?

public FindItemsResults<Appointment> GetCalendarAppointments(string emailAddress, string calendarName, DateTime start, DateTime end)
{
        // start with on prem exchange
        _service.UseDefaultCredentials = true; // use app pool security context
        _service.Url = new Uri(ConfigurationManager.ConnectionStrings["ExchangeURL"].ConnectionString);

        _service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, emailAddress);

        FolderView folderView = new FolderView(25);
        folderView.PropertySet = new PropertySet(BasePropertySet.IdOnly);
        folderView.PropertySet.Add(FolderSchema.DisplayName);
        SearchFilter searchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, calendarName);
        folderView.Traversal = FolderTraversal.Deep;
        FindFoldersResults findFolderResults = _service.FindFolders(WellKnownFolderName.Root, searchFilter, folderView);

        if (findFolderResults.TotalCount == 0)
            return null;

        FindItemsResults<Appointment> appointments;
        CalendarFolder calendarFolder;
        CalendarView calendarView = new CalendarView(start, end, 30);

        calendarView.PropertySet = new PropertySet(AppointmentSchema.Id,
                                                    AppointmentSchema.Start,
                                                    AppointmentSchema.End,
                                                    AppointmentSchema.Subject,
                                                    AppointmentSchema.Location);

        calendarFolder = (CalendarFolder)findFolderResults.Folders[0];

        try
        {
            appointments = calendarFolder.FindAppointments(calendarView);
        }
        catch (Exception e)
        {
            if (e.Message == "The SMTP address has no mailbox associated with it.")
            {
                // try exchange online
                _service.Credentials = new WebCredentials(ConfigurationManager.ConnectionStrings["ExchangeOnlineServiceAccountUsername"].ConnectionString,
                                                          ConfigurationManager.ConnectionStrings["ExchangeOnlineServiceAccountPassword"].ConnectionString);

                _service.Url = new Uri(ConfigurationManager.ConnectionStrings["ExchangeOnlineUrl"].ConnectionString);

                try
                {
                    appointments = calendarFolder.FindAppointments(calendarView);
                }
                catch (Exception ex)
                {
                    throw new Exception("Error when trying to read exchange to get calendar " + calendarName + " from exchange online inbox " + emailAddress + ": " + ex.Message);
                }

            }
            else
            {
                throw new Exception("Error when trying to read exchange to get calendar " + calendarName + " from on prem exchange inbox " + emailAddress + ": " + e.Message);
            }
        }

        if (appointments == null || appointments.Items.Count < 1)
            return null;

        return appointments;
}


问:
How can I pass data from child component to parent component in Reactjs?
I have two components one child and another is parent component. I am conditionally rendring my child component. Function of this code is just when you click on button a timer will display and when you click stop timer will stop. Here "Timer" is child componenet and I have used state property in "timer" componenet and I want to display the value of Timer when a just before clicking on "stop timer button". So how do I pass the "timer" state variable value from child to parent component.

```<code> const[time,setTime]=useState(0);
 const handleStart=()=>{
    setTime(true);
 }
const handleStop=()=>{
    setTime(false);
 }
 .....
<button onClick={handleStart}>Start StopWatch</button>
<button onClick={handleStop}>Stop StopWatch</button>
{time?<Timer/>:null}
</code>```

This was the parent component and the following code is for "timer" component.

```<code>import React,{useEffect,useState} from 'react';
const Timer = () => {
    const[timer,setTimer]=useState(0);
    useEffect(()=>{
        setTimeout(()=>{
            setTimer(prevTime=>prevTime+1);
        },100)
    },[timer])
    let style={
        position:"absolute",
        height:"100px",
        weight:"200px",
        backgroundColor:"red",
        zIndex:"1"
    }
    const handleStopTime=()=>{
        console.log(timer);
        setTimer(0);
    }
    return (
        <div style={style}>
            <h1>{timer}</h1>
        </div>
      );
}

export default Timer;
</code>```

答:
You can pass a function to your timer like this:

const[time,setTime]=useState(0);
const[timerValue,setTimerValue]=useState(0);
 const handleStart=()=>{
    setTime(true);
 }
const handleStop=()=>{
    setTime(false);
 }

 .....
<button onClick={handleStart}>Start StopWatch</button>
<button onClick={handleStop}>Stop StopWatch</button>
{time?<Timer updateTimerValue={setTimerValue}/>:null}

```

<p>after in you timer you can use this prop to update parent state:</p>

<pre class="lang-js prettyprint-override"><code>const handleStopTime=()=>{
        console.log(timer);
        props.updateTimer(timer)
        setTimer(0);
    }
</code>```

Body:
I have two components one child and another is parent component. I am conditionally rendring my child component. Function of this code is just when you click on button a timer will display and when you click stop timer will stop. Here "Timer" is child componenet and I have used state property in "timer" componenet and I want to display the value of Timer when a just before clicking on "stop timer button". So how do I pass the "timer" state variable value from child to parent component.

 const[time,setTime]=useState(0);
 const handleStart=()=>{
    setTime(true);
 }
const handleStop=()=>{
    setTime(false);
 }
 .....
<button onClick={handleStart}>Start StopWatch</button>
<button onClick={handleStop}>Stop StopWatch</button>
{time?<Timer/>:null}

This was the parent component and the following code is for "timer" component.

import React,{useEffect,useState} from 'react';
const Timer = () => {
    const[timer,setTimer]=useState(0);
    useEffect(()=>{
        setTimeout(()=>{
            setTimer(prevTime=>prevTime+1);
        },100)
    },[timer])
    let style={
        position:"absolute",
        height:"100px",
        weight:"200px",
        backgroundColor:"red",
        zIndex:"1"
    }
    const handleStopTime=()=>{
        console.log(timer);
        setTimer(0);
    }
    return (

{timer}

      );
}

export default Timer;

Body:
You can pass a function to your timer like this:

const[time,setTime]=useState(0);
const[timerValue,setTimerValue]=useState(0);
 const handleStart=()=>{
    setTime(true);
 }
const handleStop=()=>{
    setTime(false);
 }

 .....
<button onClick={handleStart}>Start StopWatch</button>
<button onClick={handleStop}>Stop StopWatch</button>
{time?<Timer updateTimerValue={setTimerValue}/>:null}

after in you timer you can use this prop to update parent state:

const handleStopTime=()=>{
        console.log(timer);
        props.updateTimer(timer)
        setTimer(0);
    }


问:
Owned Storage vs Referenced Storage
Looking at this page in the Snowflake docs: https://docs.snowflake.com/en/user-guide/tables-storage-considerations.html#owned-storage-vs-referenced-storage ...

If T2 is cloned from T1 and then data is changed in T2, T2 is the owner of that changed data.

If T3 and T4 are both cloned from T2 and then T2 is dropped, is the data that T2 owned then duplicated between T3 and T4 and both own their copies of that data?

If not, how does this work?

Thanks

答:
The cloned table(s) are owned by the ROLE who performed the CLONEing.

If the original table(s) dropped, the ownership of the cloned table doesn't change.

There is no ownership concept of "changed data". The table is owned by a ROLE

Title: Owned Storage vs Referenced Storage


问:
I'm unable to upload a file whose name has a space in it to Google Cloud Storage using Python. What am I doing wrong?
I'm new to Python and Google Cloud. Using Flask I have created a web page where a user can choose a file from their computer and upload it to a GCS bucket that I have already created. I'm following Google's documentation example which uses the Google Python API library. I'm able to upload files whose names are just a single word, like 'image' but if my file is named 'image one' then I get the following error-
 FileNotFoundError: [Errno 2] No such file or directory: 'image one.jpg'

Here's my code:

```<code>@app.route('/upload', methods = ['GET'  , 'POST'])
def upload():
    if request.method == "POST":
        f = request.files['file']
        f.save(secure_filename(f.filename))
        gcs_upload(f.filename)

def gcs_upload(filename):
    storage_client = storage.Client()   # instantiate a client
    bucket = storage_client.bucket('bucket_name')
    blob=bucket.blob(filename)      # file name at the destination should be the same
    blob.upload_from_filename(filename)     # file to be uploaded

if __name__ == '__main__':
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    app.run(port=8080, debug=True)
</code>```

If I'm writing a production level application then I would want a user to upload a file even if it has spaces in its name.

答:
I reproduced the issue on my own project and the problem you face arise from the use of secure_filename function. According to werkzeug documentation the function secure_filename will replace any whitespace of the user provided filename with an underscore. Adding some logging you might see that:

f.filename # 'foo bar.png'
secure_filename(f.filename) # 'foo_bar.png'
```

<p>So, when you call the <strong>gcs_upload</strong> function you're passing the original filename instead of the one returned by secure_filename and as the error message points out such file does not exist.</p>

<p>To solve the issue just change your upload function to:</p>

<pre class="lang-py prettyprint-override"><code>def upload():
    if request.method == "POST":
        f = request.files['file']
        filename = secure_filename(f.filename)
        f.save(filename)
        gcs_upload(filename)
</code>```

Body:
I'm new to Python and Google Cloud. Using Flask I have created a web page where a user can choose a file from their computer and upload it to a GCS bucket that I have already created. I'm following Google's documentation example which uses the Google Python API library. I'm able to upload files whose names are just a single word, like 'image' but if my file is named 'image one' then I get the following error-
 FileNotFoundError: [Errno 2] No such file or directory: 'image one.jpg'

Here's my code:

@app.route('/upload', methods = ['GET'  , 'POST'])
def upload():
    if request.method == "POST":
        f = request.files['file']
        f.save(secure_filename(f.filename))
        gcs_upload(f.filename)

def gcs_upload(filename):
    storage_client = storage.Client()   # instantiate a client
    bucket = storage_client.bucket('bucket_name')
    blob=bucket.blob(filename)      # file name at the destination should be the same
    blob.upload_from_filename(filename)     # file to be uploaded

if __name__ == '__main__':
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    app.run(port=8080, debug=True)

If I'm writing a production level application then I would want a user to upload a file even if it has spaces in its name.

Body:
I reproduced the issue on my own project and the problem you face arise from the use of secure_filename function. According to werkzeug documentation the function secure_filename will replace any whitespace of the user provided filename with an underscore. Adding some logging you might see that:

f.filename # 'foo bar.png'
secure_filename(f.filename) # 'foo_bar.png'

So, when you call the gcs_upload function you're passing the original filename instead of the one returned by secure_filename and as the error message points out such file does not exist.

To solve the issue just change your upload function to:

def upload():
    if request.method == "POST":
        f = request.files['file']
        filename = secure_filename(f.filename)
        f.save(filename)
        gcs_upload(filename)


问:
ASP - how to remove single quote from user input text
```<code>answer  = Request.Form("Text" & i)
</code>```

In a form a user inputs random text which is inserted into a database. Currently if the user puts in single quotes it creates an error. How do i remove just single quotes' from the users answer?

答:
Right way to solve this problem is use parameters when inserting to database.
instead of:

```<code>SqlCommand cmd = new SqlCommand("INSERT INTO TABLE VALUES ('" + answer + "')");
</code>```

use

```<code>SqlCommand cmd = new SqlCommand("INSERT INTO TABLE VALUES (@answer)",answer);
</code>```

Body:
answer  = Request.Form("Text" & i)

In a form a user inputs random text which is inserted into a database. Currently if the user puts in single quotes it creates an error. How do i remove just single quotes' from the users answer?

Body:
Right way to solve this problem is use parameters when inserting to database.
instead of:

SqlCommand cmd = new SqlCommand("INSERT INTO TABLE VALUES ('" + answer + "')");

use

SqlCommand cmd = new SqlCommand("INSERT INTO TABLE VALUES (@answer)",answer);


问:
Find min/max of two dates (typed)
I want a strongly typed code. When I apply solutions from a similar question - Min/Max of dates in an array? - I get error

```<code>TS2345: Argument of type 'Date' is not assignable to parameter of type 'number'.
</code>```

my code

```<code>  const min: Date = Math.min(begin as Date, (end || defaultDate) as Date);
  const max: Date = Math.max(begin as Date, (end || defaultDate) as Date);
</code>```

begin as Date part is underlined.

What's the correct way of finding min/max dates in Typescript?

答:
Lets say you have an array, you will map the date part by taking its getTime(), then pass it to Math.min and when you get it back, again convert it to date.

const result:number[] = array.map((item)=>new Date(item.date).getTime());
console.log(new Date(Math.min(...result)));```

Title: Find min/max of two dates (typed)

Body:
I want a strongly typed code. When I apply solutions from a similar question - Min/Max of dates in an array? - I get error

TS2345: Argument of type 'Date' is not assignable to parameter of type 'number'.

my code

  const min: Date = Math.min(begin as Date, (end || defaultDate) as Date);
  const max: Date = Math.max(begin as Date, (end || defaultDate) as Date);

begin as Date part is underlined.

What's the correct way of finding min/max dates in Typescript?


问:
Function for converting numeric value into word
Is there any function in progress for converting a numeric value into word or there is another way of doing it?
For ex- 1234 -> one thousand two hundred thirty four.</p>

答:
I dug this out of a (very) dusty corner and updated it a bit:</p>

```<code>/* num2words.p
 *
 * convert integers to words...
 *
 * original: june 23, 1988
 * upgraded: june 01, 2020  (changed to a function with parameter passing rather than shared variables, added int64)
 *
 */

function num2words returns character( number as int64 ):

  define variable spelled as character no-undo.

  define variable i   as integer no-undo.
  define variable buf as character no-undo.
  define variable tmp as character no-undo.
  define variable mag as integer extent 3 no-undo.

  define variable ones  as character extent 10 initial [ "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "" ] no-undo.
  define variable teens as character extent 10 initial [ "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" ] no-undo.
  define variable tens  as character extent 10 initial [ "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "" ] no-undo.
  define variable order as character extent  5 initial [ "Trillion", "Billion", "Million", "Thousand", "" ] no-undo.

  tmp = string( number, "999999999999999" ).
  spelled = "".
  if number = 0 then
    do:
      spelled = "Zero".
      return spelled.
    end.

  i = 0.
  do while i < 5:

    buf = substring( tmp, (( i * 3 ) + 1 ), 3 ).

    mag[1] = integer( substring( buf, 3, 1 )).
    mag[2] = integer( substring( buf, 2, 1 )).
    mag[3] = integer( substring( buf, 1, 1 )).

    if mag[3] > 0 then                spelled = spelled + ones[mag[3]] + " " + "Hundred" + " ".
    if mag[2] > 1 and mag[1] = 0 then spelled = spelled + tens[mag[2]] + " ".
    if mag[2] > 1 and mag[1] > 0 then spelled = spelled + tens[mag[2]] + " " + ones[mag[1]] + " ".
    if mag[2] = 1 then                spelled = spelled + teens[mag[1] + 1] + " ".
    if mag[2] = 0 and mag[1] > 0 then spelled = spelled + ones[mag[1]] + " ".

    i = i + 1.

    if /* spelled <> "" and */
       ( mag[1] <> 0 or mag[2] <> 0 or mag[3] <> 0 )           /* bug fix */
     then spelled = spelled + order[i] + " ".

  end.

  return trim( spelled ).

end.

display ( num2words( 1234567890123 ) + "." )format "x(150)".
</code>```

Body:
I dug this out of a (very) dusty corner and updated it a bit:

/* num2words.p
 *
 * convert integers to words...
 *
 * original: june 23, 1988
 * upgraded: june 01, 2020  (changed to a function with parameter passing rather than shared variables, added int64)
 *
 */

function num2words returns character( number as int64 ):

  define variable spelled as character no-undo.

  define variable i   as integer no-undo.
  define variable buf as character no-undo.
  define variable tmp as character no-undo.
  define variable mag as integer extent 3 no-undo.

  define variable ones  as character extent 10 initial [ "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "" ] no-undo.
  define variable teens as character extent 10 initial [ "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" ] no-undo.
  define variable tens  as character extent 10 initial [ "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "" ] no-undo.
  define variable order as character extent  5 initial [ "Trillion", "Billion", "Million", "Thousand", "" ] no-undo.

  tmp = string( number, "999999999999999" ).
  spelled = "".
  if number = 0 then
    do:
      spelled = "Zero".
      return spelled.
    end.

  i = 0.
  do while i < 5:

    buf = substring( tmp, (( i * 3 ) + 1 ), 3 ).

    mag[1] = integer( substring( buf, 3, 1 )).
    mag[2] = integer( substring( buf, 2, 1 )).
    mag[3] = integer( substring( buf, 1, 1 )).

    if mag[3] > 0 then                spelled = spelled + ones[mag[3]] + " " + "Hundred" + " ".
    if mag[2] > 1 and mag[1] = 0 then spelled = spelled + tens[mag[2]] + " ".
    if mag[2] > 1 and mag[1] > 0 then spelled = spelled + tens[mag[2]] + " " + ones[mag[1]] + " ".
    if mag[2] = 1 then                spelled = spelled + teens[mag[1] + 1] + " ".
    if mag[2] = 0 and mag[1] > 0 then spelled = spelled + ones[mag[1]] + " ".

    i = i + 1.

    if /* spelled <> "" and */
       ( mag[1] <> 0 or mag[2] <> 0 or mag[3] <> 0 )           /* bug fix */
     then spelled = spelled + order[i] + " ".

  end.

  return trim( spelled ).

end.

display ( num2words( 1234567890123 ) + "." )format "x(150)".


问:
Regex with multiple groups, some of which are optional
I have trouble matching multiple groups, some of which are optional. I've tried variations of greedy/non greedy, but can't get it to work.

As input, I have cells which look like this:

```<code>SEPA Overboeking                 IBAN: AB1234        BIC: LALA678                    Naam: John Smith            Omschrijving: Hello hello        Kenmerk: 03-05-2019 23:12 533238
</code>```

I wanna split these up into groups of IBAN, BIC, Naam, Omschrijving, Kenmerk.

For this example, this yields: AB1234; LALA678; John Smith; Hello hello; 03-05-2019 23:12 533238.
To obtain this, I've used:

```<code>.*IBAN: (.*)\s+BIC: (.*)\s+Naam: (.*)\s+Omschrijving: (.*)\s+Kenmerk: (.*)
</code>```

This works perfectly as long as all these groups are present in the input. Some cells, however don't have the "Omschrijving" and/or "Kenmerk" part. As output, I would like to have empty groups if they're not present. Right now, nothing is matched.
I've tried variations with greedy/non greedy, but couldn't get it to work.

Help would be greatly appreciated!

N.B.:  I'm working in KNIME (open source data analysis tool)

答:
I was able to split your input using the following regular expression:

```<code>^.*
\s+IBAN\:\s*(?<IBAN>.*?)
\s+BIC\:\s*(?<BIC>.*?)
\s+Naam\:\s*(?<Naam>.*?)
(?:\s+Omschrijving\:\s*(?<Omschrijving>.*?))?
(?:\s+Kenmerk\:\s*(?<Kenmerk>.*?))?
$
</code>```

This requires your fields to follow the given order and will treat the fields IBAN, BIC and Naam as required. Fields Omschrijving and Kenmerk may be optional. I am pretty sure, this can still be optimized, but it results in the following output, which should be fine for you (or at least a starting point):

For evaluation and testing in KNIME, I used Palladian's Regex Extractor node, that can be configured as follows and provides a nice preview functionality:

I added an example workflow to my NodePit Space. It contains some example lines, parses them and provides the above seen output.

Body:
I have trouble matching multiple groups, some of which are optional. I've tried variations of greedy/non greedy, but can't get it to work.

As input, I have cells which look like this:

SEPA Overboeking                 IBAN: AB1234        BIC: LALA678                    Naam: John Smith            Omschrijving: Hello hello        Kenmerk: 03-05-2019 23:12 533238

I wanna split these up into groups of IBAN, BIC, Naam, Omschrijving, Kenmerk.

For this example, this yields: AB1234; LALA678; John Smith; Hello hello; 03-05-2019 23:12 533238.
To obtain this, I've used:

.*IBAN: (.*)\s+BIC: (.*)\s+Naam: (.*)\s+Omschrijving: (.*)\s+Kenmerk: (.*)

This works perfectly as long as all these groups are present in the input. Some cells, however don't have the "Omschrijving" and/or "Kenmerk" part. As output, I would like to have empty groups if they're not present. Right now, nothing is matched.
I've tried variations with greedy/non greedy, but couldn't get it to work.

Help would be greatly appreciated!

N.B.:  I'm working in KNIME (open source data analysis tool)

Body:
I was able to split your input using the following regular expression:

^.*
\s+IBAN\:\s*(?<IBAN>.*?)
\s+BIC\:\s*(?<BIC>.*?)
\s+Naam\:\s*(?<Naam>.*?)
(?:\s+Omschrijving\:\s*(?<Omschrijving>.*?))?
(?:\s+Kenmerk\:\s*(?<Kenmerk>.*?))?
$

This requires your fields to follow the given order and will treat the fields IBAN, BIC and Naam as required. Fields Omschrijving and Kenmerk may be optional. I am pretty sure, this can still be optimized, but it results in the following output, which should be fine for you (or at least a starting point):

For evaluation and testing in KNIME, I used Palladian's Regex Extractor node, that can be configured as follows and provides a nice preview functionality:

I added an example workflow to my NodePit Space. It contains some example lines, parses them and provides the above seen output.


问:
"ImportError: file_cache is unavailable" when using Python client for Google service account file_cache
I'm using a service account for G Suite with full domain delegation. I have a script with readonly access to Google Calendar. The script works just fine, but throws an error (on a background thread?) when I "build" the service. Here's the code:

```<code>from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
import urllib
import requests
from apiclient.discovery import build

cal_id = "my_calendar_id@group.calendar.google.com"

scopes                = ['https://www.googleapis.com/auth/calendar.readonly']
credentials           = ServiceAccountCredentials.from_json_keyfile_name('my_cal_key.json', scopes=scopes)
delegated_credentials = credentials.create_delegated('me@mydomain.com')
http_auth             = delegated_credentials.authorize(Http())

# This is the line that throws the error
cal_service  = build('calendar','v3',http=http_auth)

#Then everything continues to work normally
request = cal_service.events().list(calendarId=cal_id)
response = request.execute()

# etc...
</code>```

The error thrown is:

```<code>WARNING:googleapiclient.discovery_cache:file_cache is unavailable when using oauth2client >= 4.0.0
Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/__init__.py", line 36, in autodetect
    from google.appengine.api import memcache
ImportError: No module named 'google'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 33, in <module>
    from oauth2client.contrib.locked_file import LockedFile
ImportError: No module named 'oauth2client.contrib.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 37, in <module>
    from oauth2client.locked_file import LockedFile
ImportError: No module named 'oauth2client.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/__init__.py", line 41, in autodetect
    from . import file_cache
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 41, in <module>
    'file_cache is unavailable when using oauth2client >= 4.0.0')
ImportError: file_cache is unavailable when using oauth2client >= 4.0.0
</code>```

What's going on here and is this something that I can fix? I've tried reinstalling and/or upgrading the google package.

答:
Fwiw this is a reposting of my answer here

Since they are technically warnings (not errors), if you don't have direct access to the call, you can do this wherever you instantiate the service to suppress them:

import logging
logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)

With thanks to theacodes who gave that answer here (but with a missing 'n' in 'client' that seems to have led to a lot of downvotes there).

See also the discussion here

Body:
I'm using a service account for G Suite with full domain delegation. I have a script with readonly access to Google Calendar. The script works just fine, but throws an error (on a background thread?) when I "build" the service. Here's the code:

from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
import urllib
import requests
from apiclient.discovery import build

cal_id = "my_calendar_id@group.calendar.google.com"

scopes                = ['https://www.googleapis.com/auth/calendar.readonly']
credentials           = ServiceAccountCredentials.from_json_keyfile_name('my_cal_key.json', scopes=scopes)
delegated_credentials = credentials.create_delegated('me@mydomain.com')
http_auth             = delegated_credentials.authorize(Http())

# This is the line that throws the error
cal_service  = build('calendar','v3',http=http_auth)

#Then everything continues to work normally
request = cal_service.events().list(calendarId=cal_id)
response = request.execute()

# etc...

The error thrown is:

WARNING:googleapiclient.discovery_cache:file_cache is unavailable when using oauth2client >= 4.0.0
Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/__init__.py", line 36, in autodetect
    from google.appengine.api import memcache
ImportError: No module named 'google'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 33, in <module>
    from oauth2client.contrib.locked_file import LockedFile
ImportError: No module named 'oauth2client.contrib.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 37, in <module>
    from oauth2client.locked_file import LockedFile
ImportError: No module named 'oauth2client.locked_file'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/__init__.py", line 41, in autodetect
    from . import file_cache
  File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 41, in <module>
    'file_cache is unavailable when using oauth2client >= 4.0.0')
ImportError: file_cache is unavailable when using oauth2client >= 4.0.0

What's going on here and is this something that I can fix? I've tried reinstalling and/or upgrading the google package.


问:
upscaling an image using Nearest-neighbor in processing
While doing something like this in processing 3.5.4

```<code>void draw() {
  image(img.source, 0, 0, 50000, 50000);
}
</code>```

The image comes out blurry.
Is there a way I can do this using nearest-neighbor?
The image is 1000 by 1000 pixels.

答:
If it's the default (JAVA2D) renderer you're using with size() then

simply calling noSmooth() in setup() should do the trick.

If you use P2D you need to tell OpenGL to use nearest neighbour in setup():

```<code>((PGraphicsOpenGL) g).textureSampling(2);
</code>```

(I learned this from Vallentin's answer)

Body:
While doing something like this in processing 3.5.4

void draw() {
  image(img.source, 0, 0, 50000, 50000);
}

The image comes out blurry.
Is there a way I can do this using nearest-neighbor?
The image is 1000 by 1000 pixels.

Body:
If it's the default (JAVA2D) renderer you're using with size() then

simply calling noSmooth() in setup() should do the trick.

If you use P2D you need to tell OpenGL to use nearest neighbour in setup():

((PGraphicsOpenGL) g).textureSampling(2);

(I learned this from Vallentin's answer)


问:
Cocoa/iPhone: How to I keep ibtool from outputing non-localizable strings in a xib file?
I'm working on internationalizing an iPhone application, and I'm using ibtool to extract the string from my xib files so they can be translated by a localization house like so:

```<code>ibtool --generate-strings-file BlahBlahView.strings English.lproj/BlahBlahView.xib
</code>```

The problem with this is that the .strings file I end up with contains all the strings contained in the xib when I really want the subset that I actually care about for i18n. Is there any best best practice for dealing with this? Ideally I'd like to be able to add some kind of annotation in interface builder to say either "This is localizable" or "This is not localizable" and have ibtool only output the localizable strings when I run it.

Thanks!

Edit: OK, let me expand the parameters a bit. The solution doesn't need to use ibtool only. Ibtool + some data in the xib + a shell script is fine. As long as it works!

答:
I think you can automate this, but it'll take a few steps. You can extract arbitrary properties from your xib using ibtool, so maybe you could set the tag of the non-localizable items to a particular value (-1, for example), then extract the tags and use that to filter the strings file and remove the unwanted entries.

check out the man page for ibtool, in particular the -export option.

OwnerDisplayName: Mike Akers

ContentLicense: CC BY-SA 2.5

Body:
I'm working on internationalizing an iPhone application, and I'm using ibtool to extract the string from my xib files so they can be translated by a localization house like so:

ibtool --generate-strings-file BlahBlahView.strings English.lproj/BlahBlahView.xib

The problem with this is that the .strings file I end up with contains all the strings contained in the xib when I really want the subset that I actually care about for i18n. Is there any best best practice for dealing with this? Ideally I'd like to be able to add some kind of annotation in interface builder to say either "This is localizable" or "This is not localizable" and have ibtool only output the localizable strings when I run it.

Thanks!

Edit: OK, let me expand the parameters a bit. The solution doesn't need to use ibtool only. Ibtool + some data in the xib + a shell script is fine. As long as it works!

LastEditorDisplayName: Mike Akers

OwnerDisplayName: Mark Bessey


问:
How to add image that depend on names in birt report?
I want to add image to my report that depend on names.If i choose a name Eg : "Michael", report wiil show up the information about him and his image.Do i have to use dynamic image? Please , give me any advice and Thank you.</p>

答:
To achieve the dynamic images into the BIRT based report, there are many options but mainly used below two options:

Images stored into a directory and filename (image name) is dynamically set into the BIRT image control. This could be achieved just by setting the image control value using some SQL record (column from the sql query which stores the image filename)

The second and mostly used for adding logos and user faces into reports for printing. In this methodology, images are stored into the database by using BLOB type columns and the SQL query picks the image column and set into the BIRT's Image control dynamically

To select the record for each person, one parameter is to be created which takes input at runtime and determine the person data from the database or other source.

Example,
Employee table

```<code>ID                 Name               Adress               Image
1                  Abc                Xyz                  8743ho4orh39hof (binary image)
2                  Def                XXv                  klsjlajerownln3oj3n4jo4
</code>```

Now, we create a parameter which take employee id as input and based upon input the report fetch record from database and render data into report for the employee.

It will be fully dynamic and every details will be loaded dynamically for the employee for which employee id has been passed.

Body:
To achieve the dynamic images into the BIRT based report, there are many options but mainly used below two options:

Images stored into a directory and filename (image name) is dynamically set into the BIRT image control. This could be achieved just by setting the image control value using some SQL record (column from the sql query which stores the image filename)

The second and mostly used for adding logos and user faces into reports for printing. In this methodology, images are stored into the database by using BLOB type columns and the SQL query picks the image column and set into the BIRT's Image control dynamically

To select the record for each person, one parameter is to be created which takes input at runtime and determine the person data from the database or other source.

Example,
Employee table

ID                 Name               Adress               Image
1                  Abc                Xyz                  8743ho4orh39hof (binary image)
2                  Def                XXv                  klsjlajerownln3oj3n4jo4

Now, we create a parameter which take employee id as input and based upon input the report fetch record from database and render data into report for the employee.

It will be fully dynamic and every details will be loaded dynamically for the employee for which employee id has been passed.


问:
Can I solve "Your requirements could not be resolved to an installable set of packages." in laravel composer
when I want to install laravel/ui the composer show this:

and my composer.json :

my laravel version is 6.13 and I went to laravel.com and I click the Authentication for laravel 6X and says for laravel 6 you have to install this package and the package is composer require laravel/ui "^1.0" --dev and composer show me that problem again what can I do?

答:
Add this in composer.json and then use command composer update

```<code>"laravel/ui": "^1.2",
</code>```

Sometimes the library which you're installing is not satisfied PHP version not only laravel version.

Body:
Add this in composer.json and then use command composer update

"laravel/ui": "^1.2",

Sometimes the library which you're installing is not satisfied PHP version not only laravel version.


问:
How to make step in 10 points without save value outside?
Actually what I need is I have a progress bar logic that tracking every second count of files, but case here that I don't need to update every time when I get trigger, like 1%, 3%, 7% ... I would like to define kind of step_progress variable (for example 10) and get this progress bar update steps like 10%, 20%, 30%...

So, for this case I wrote such logic

```<code>...
->set_progress_bar_callback([&](int count, int copied_file) {
        const int PROGRESS_UPDATE_STEP = 10;
        const int MAX_PERCENTAGE = 100;
        float progress_step = (float)MAX_PERCENTAGE / (float)count;
        float progress_result = progress_step * copied_file;

        if ((int)progress_result % PROGRESS_UPDATE_STEP == 0)
        {
            if (progress_callback != nullptr)
            {
                printf("HERE!!! execute_copy_process Progress count %f\n", progress_result);
                progress_callback(progress_result);
            }
        }
}
</code>```

and I need to mention that I don't want to define outside variable(like class member), I would like that all this values should be inside lambda.

So, as you can see count - is a full amount (for example 124), and copied_file - it is a progress(for example 34)

Thus I calculate progress_result and try to get module(%) in order to understand if it is step of 10, but issue here that not every time progress_result value came to round number and eventually I get my progress like 10%, 40%, 60%...

Is there is some kind of trick to do it without to save outside values?

答:
You should stay in integer arithmetic.</p>

```<code>[&](int current, int total) {
    const int PROGRESS_UPDATE_STEP = 10;
    const int MAX_PERCENTAGE = 100;
    int step = std::max(total * PROGRESS_UPDATE_STEP / MAX_PERCENTAGE, 1);

    if ((current % step) == 0)
    {
        if (progress_callback != nullptr)
        {
            float progress_result = static_cast<float>(current) / total;
            printf("HERE!!! execute_copy_process Progress count %f\n", progress_result);
            progress_callback(progress_result);
        }
    }
}
</code>```

Body:
Actually what I need is I have a progress bar logic that tracking every second count of files, but case here that I don't need to update every time when I get trigger, like 1%, 3%, 7% ... I would like to define kind of step_progress variable (for example 10) and get this progress bar update steps like 10%, 20%, 30%...

So, for this case I wrote such logic

...
->set_progress_bar_callback([&](int count, int copied_file) {
        const int PROGRESS_UPDATE_STEP = 10;
        const int MAX_PERCENTAGE = 100;
        float progress_step = (float)MAX_PERCENTAGE / (float)count;
        float progress_result = progress_step * copied_file;

        if ((int)progress_result % PROGRESS_UPDATE_STEP == 0)
        {
            if (progress_callback != nullptr)
            {
                printf("HERE!!! execute_copy_process Progress count %f\n", progress_result);
                progress_callback(progress_result);
            }
        }
}

and I need to mention that I don't want to define outside variable(like class member), I would like that all this values should be inside lambda.

So, as you can see count - is a full amount (for example 124), and copied_file - it is a progress(for example 34)

Thus I calculate progress_result and try to get module(%) in order to understand if it is step of 10, but issue here that not every time progress_result value came to round number and eventually I get my progress like 10%, 40%, 60%...

Is there is some kind of trick to do it without to save outside values?

Body:
You should stay in integer arithmetic.

[&](int current, int total) {
    const int PROGRESS_UPDATE_STEP = 10;
    const int MAX_PERCENTAGE = 100;
    int step = std::max(total * PROGRESS_UPDATE_STEP / MAX_PERCENTAGE, 1);

    if ((current % step) == 0)
    {
        if (progress_callback != nullptr)
        {
            float progress_result = static_cast<float>(current) / total;
            printf("HERE!!! execute_copy_process Progress count %f\n", progress_result);
            progress_callback(progress_result);
        }
    }
}