Programs & Examples On #Listactivity

A ListActivity is an Activity (main UI component of the Android System) that displays a list of items by binding to a data source such as an array or Cursor, and exposes event handlers when the user selects an item.

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

It can be that you need to add or update your privacy policy. You can easily create a privacy policy using this template

https://app-privacy-policy-generator.firebaseapp.com/

android: data binding error: cannot find symbol class

For me it was an error in the layout xml binding, I had

app:setNameString="@{person}"

instead of

app:nameString="@{person}"

the type name must match the name you have set up in the @BindingAdapter class (if you are using binding adapter)

How to show an empty view with a RecyclerView?

if you want to display a text view when the recycler view is empty you can do it like this :

ArrayList<SomeDataModel> arrayList = new ArrayList<>();

RecycleAdapter recycleAdapter =  new RecycleAdapter(getContext(),project_Ideas);

recyclerView..setAdapter(recycleAdapter);

if(arrayList.isEmpty())
{
    emptyTextView.setVisibility(View.VISIBLE);
    recyclerView.setVisibility(View.GONE);
}

I Assume you have TextView

and XML like this

 android:visibility="gone"

    
  

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

The same problem when I used 'org.springframework.android:spring-android-rest-template:2.0.0.M1' in Android Studio 1.0.1. I need include this in build.gradle

android{
...
    packagingOptions{
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
    }
...
}

Android + Pair devices via bluetooth programmatically

if you have the BluetoothDevice object you can create bond(pair) from api 19 onwards with bluetoothDevice.createBond() method.

Edit

for callback, if the request was accepted or denied you will have to create a BroadcastReceiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED action

how to show progress bar(circle) in an activity having a listview before loading the listview with data

You can do this easier.
Source: http://www.tutorialspoint.com/android/android_loading_spinner.htm
It helped me.

Layout:

<ProgressBar
   android:id="@+id/progressBar1"
   style="?android:attr/progressBarStyleLarge"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true" />

After defining it in xml, you have to get its reference in java file through ProgressBar class. Its syntax is given below:

private ProgressBar spinner;
spinner = (ProgressBar)findViewById(R.id.progressBar1);

After that you can make its disappear , and bring it back when needed through setVisibility Method. Its syntax is given below:

spinner.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);

Where/How to getIntent().getExtras() in an Android Fragment?

What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments.

There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity and Fragment from the support library.

You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:

public static class DetailsActivity extends FragmentActivity {

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

        // (omitted some other stuff)

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction().add(
                    android.R.id.content, details).commit();
        }
    }
}

In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance in the examples given by Google. There actually is a newInstance method in DetailsFragment, so I'm unsure why it isn't used in the snippet above...

Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments(). Since this returns a Bundle, its usage is similar to that of the extras in an Activity.

public static class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    // (other stuff omitted)

}

Your content must have a ListView whose id attribute is 'android.R.id.list'

Exact way I fixed this based on feedback above since I couldn't get it to work at first:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/list"
>
</ListView>

MainActivity.java:

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

preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
    android:key="upgradecategory"
    android:title="Upgrade" >
    <Preference
        android:key="download"
        android:title="Get OnCall Pager Pro"
        android:summary="Touch to download the Pro Version!" />
</PreferenceCategory>
</PreferenceScreen>

Show ProgressDialog Android

I am using the following code in one of my current projects where i download data from the internet. It is all inside my activity class.

// ---------------------------- START DownloadFileAsync // -----------------------//
class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // DIALOG_DOWNLOAD_PROGRESS is defined as 0 at start of class
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... urls) {
        try {
            String xmlUrl = urls[0];

            URL u = new URL(xmlUrl);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            int lengthOfFile = c.getContentLength();

            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;

            while ((len1 = in.read(buffer)) > 0) {
                total += len1; // total = total + len1
                publishProgress("" + (int) ((total * 100) / lengthOfFile));
                xmlContent += buffer;
            }
        } catch (Exception e) {
            Log.d("Downloader", e.getMessage());
        }
        return null;
    }

    protected void onProgressUpdate(String... progress) {
        Log.d("ANDRO_ASYNC", progress[0]);
        mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Retrieving latest announcements...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
        return mProgressDialog;
    default:
        return null;
    }

}

Using ListView : How to add a header view?

You can add as many headers as you like by calling addHeaderView() multiple times. You have to do it before setting the adapter to the list view.

And yes you can add header something like this way:

LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.header, myListView, false);
myListView.addHeaderView(header, null, false);

How to change color and font on ListView

Even better, you do not need to create separate android xml layout for list cell view. You can just use "android.R.layout.simple_list_item_1" if the list only contains textview.

private class ExampleAdapter extends ArrayAdapter<String>{

    public ExampleAdapter(Context context, int textViewResourceId, String[] objects) {
        super(context, textViewResourceId, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        View view =  super.getView(position, convertView, parent);

        TextView tv = (TextView) view.findViewById(android.R.id.text1);
        tv.setTextColor(0);

        return view;
    }

Programmatically Hide/Show Android Soft Keyboard

Try this code.

For showing Softkeyboard:

InputMethodManager imm = (InputMethodManager)
                                 getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }

For Hiding SoftKeyboard -

InputMethodManager imm = (InputMethodManager)
                                  getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm != null){
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

Android app unable to start activity componentinfo

The question is answered already, but I want add more information about the causes.

Android app unable to start activity componentinfo

This error often comes with appropriate logs. You can read logs and can solve this issue easily.

Here is a sample log. In which you can see clearly ClassCastException. So this issue came because TextView cannot be cast to EditText.

Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText

11-04 01:24:10.403: D/AndroidRuntime(1050): Shutting down VM
11-04 01:24:10.403: W/dalvikvm(1050): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:24:10.543: E/AndroidRuntime(1050): FATAL EXCEPTION: main
11-04 01:24:10.543: E/AndroidRuntime(1050): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Looper.loop(Looper.java:137)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:45)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:24:10.543: E/AndroidRuntime(1050):     ... 11 more
11-04 01:29:11.177: I/Process(1050): Sending signal. PID: 1050 SIG: 9
11-04 01:31:32.080: D/AndroidRuntime(1109): Shutting down VM
11-04 01:31:32.080: W/dalvikvm(1109): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:31:32.194: E/AndroidRuntime(1109): FATAL EXCEPTION: main
11-04 01:31:32.194: E/AndroidRuntime(1109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Looper.loop(Looper.java:137)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:31:32.194: E/AndroidRuntime(1109):     ... 11 more
11-04 01:36:33.195: I/Process(1109): Sending signal. PID: 1109 SIG: 9
11-04 02:11:09.684: D/AndroidRuntime(1167): Shutting down VM
11-04 02:11:09.684: W/dalvikvm(1167): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 02:11:09.855: E/AndroidRuntime(1167): FATAL EXCEPTION: main
11-04 02:11:09.855: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Looper.loop(Looper.java:137)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at dalvik.system.NativeStart.main(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 02:11:09.855: E/AndroidRuntime(1167):     ... 11 more

Some Common Mistakes.

1.findViewById() of non existing view

Like when you use findViewById(R.id.button) when button id does not exist in layout XML.

2. Wrong cast.

If you wrong cast some class, then you get this error. Like you cast RelativeLayout to LinearLayout or EditText to TextView.

3. Activity not registered in manifest.xml

If you did not register Activity in manifest.xml then this error comes.

4. findViewById() with declaration at top level

Below code is incorrect. This will create error. Because you should do findViewById() after calling setContentView(). Because an View can be there after it is created.

public class MainActivity extends Activity {

  ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect way

  @Override
  protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mainImage = (ImageView) findViewById(R.id.imageViewMain); //correct way
    //...
  }
}

5. Starting abstract Activity class.

When you try to start an Activity which is abstract, you will will get this error. So just remove abstract keyword before activity class name.

6. Using kotlin but kotlin not configured.

If your activity is written in Kotlin and you have not setup kotlin in your app. then you will get error. You can follow simple steps as written in Android Link or Kotlin Link. You can check this answer too.

More information

Read about Downcast and Upcast

Read about findViewById() method of Activity class

Super keyword in Java

How to register activity in manifest

Extending from two classes

you can't do multiple inheritance in java. consider using interfaces:

interface I1 {}
interface I2 {}
class C implements I1, I2 {}

or inner classes:

class Outer {
    class Inner1 extends Class1 {}
    class Inner2 extends Class2 {}
}

How to change text color of simple list item

The simplest way to do this without needing to create anything extra would be to just modify the simple list TextView:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, strings) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView textView = (TextView) super.getView(position, convertView, parent);
                textView.setTextColor({YourColorHere});
                return textView;
            }
        };

Hide a EditText & make it visible by clicking a menu

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.waist2height); {
        final EditText edit = (EditText)findViewById(R.id.editText);          
        final RadioButton rb1 = (RadioButton) findViewById(R.id.radioCM);
        final RadioButton rb2 = (RadioButton) findViewById(R.id.radioFT);                       
        if(rb1.isChecked()){    
            edit.setVisibility(View.VISIBLE);              
        }
        else if(rb2.isChecked()){               
            edit.setVisibility(View.INVISIBLE);
        }
}

ProgressDialog in AsyncTask

A couple of days ago I found a very nice solution of this problem. Read about it here. In two words Mike created a AsyncTaskManager that mediates ProgressDialog and AsyncTask. It's very easy to use this solution. You just need to include in your project several interfaces and several classes and in your activity write some simple code and nest your new AsyncTask from BaseTask. I also advice you to read comments because there are some useful tips.

Android ListView Text Color

You can do this in your code:

final ListView lv = (ListView) convertView.findViewById(R.id.list_view);

for (int i = 0; i < lv.getChildCount(); i++) {
    ((TextView)lv.getChildAt(i)).setTextColor(getResources().getColor(R.color.black));
}

Updating the list view when the adapter data changes

substitute:

mMyListView.invalidate();

for:

((BaseAdapter) mMyListView.getAdapter()).notifyDataSetChanged(); 

If that doesnt work, refer to this thread: Android List view refresh

How to start Activity in adapter?

callback from adapter to activity can be done using registering listener in form of interface: Make an interface:

      public MyInterface{
         public void  yourmethod(//incase needs parameters );
         }

In Adapter Let's Say MyAdapter:

    public MyAdapter extends BaseAdapter{
       private MyInterface listener;

    MyAdapter(Context context){
        try {
            this. listener = (( MyInterface ) context);
              } catch (ClassCastException e) {
               throw new ClassCastException("Activity must implement MyInterface");
          }

//do this where u need to fire listener l

          try {
                listener . yourmethod ();
            } catch (ClassCastException exception) {
               // do something
            }

      In Activity Implement your method:


         MyActivity extends AppCompatActivity implements MyInterface{

                yourmethod(){
                //do whatever you want
                     }
                     }

No generated R.java file in my project

This could also be the problem of an incorrect xml layout file for example. If your xml files are not valid (containing errors) the R file will not re-generate after a clean-up. If you fix this, the R file will be generated automatically again.

How to get String Array from arrays.xml file

Your XML is not entirely clear, but arrays XML can cause force closes if you make them numbers, and/or put white space in their definition.

Make sure they are defined like No Leading or Trailing Whitespace

How to start an Intent by passing some parameters to it?

In order to pass the parameters you create new intent and put a parameter map:

Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);

In order to get the parameters values inside the started activity, you must call the get[type]Extra() on the same intent:

// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"

If your parameters are ints you would use getIntExtra() instead etc. Now you can use your parameters like you normally would.

How to call Android contacts list?

I am using this method to read Contacts

public static List<ContactItem> readPhoneContacts(Context context) {
        List<ContactItem> contactItems = new ArrayList<ContactItem>();
        try {
            Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
                    null, null, "upper("+ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") ASC");

            /*context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?",
                    new String[] { id },
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");*/

            Integer contactsCount = cursor.getCount(); // get how many contacts you have in your contacts list
            if (contactsCount > 0) {
                while (cursor.moveToNext()) {

                    String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                        ContactItem contactItem = new ContactItem();
                        contactItem.setContactName(contactName);
                        //the below cursor will give you details for multiple contacts
                        Cursor pCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                                new String[]{id}, null);
                        // continue till this cursor reaches to all phone numbers which are associated with a contact in the contact list
                        while (pCursor.moveToNext()) {
                            int phoneType = pCursor.getInt(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                            //String isStarred      = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
                            String phoneNo = pCursor.getString(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            //you will get all phone numbers according to it's type as below switch case.
                            //Logs.e will print the phone number along with the name in DDMS. you can use these details where ever you want.
                            switch (phoneType) {
                                case Phone.TYPE_MOBILE:
                                    contactItem.setContactNumberMobile(phoneNo);
                                    Log.e(contactName + ": TYPE_MOBILE", " " + phoneNo);
                                    break;
                                case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
                                    contactItem.setContactNumberMobile(phoneNo);
                                    Log.e(contactName + ": TYPE_HOME", " " + phoneNo);
                                    break;
                                case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
                                    contactItem.setContactNumberMobile(phoneNo);
                                    Log.e(contactName + ": TYPE_WORK", " " + phoneNo);
                                    break;
                                case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE:
                                    contactItem.setContactNumberMobile(phoneNo);
                                    Log.e(contactName + ": TYPE_WORK_MOBILE", " " + phoneNo);
                                    break;
                                case Phone.TYPE_OTHER:
                                    contactItem.setContactNumberMobile(phoneNo);
                                    Log.e(contactName + ": TYPE_OTHER", " " + phoneNo);
                                    break;
                                default:
                                    break;
                            }
                        }
                        contactItem.setSelectedAddress(getContactPostalAddress(pCursor));
                        pCursor.close();
                        contactItems.add(contactItem);
                    }

                }
                cursor.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }


        return contactItems;
    }//loadContacts

Are static methods inherited in Java?

Many have voiced out their answer in words. This is an extended explanation in codes:

public class A {
    public static void test() {
        System.out.println("A");
    }
    public static void test2() {
        System.out.println("Test");
    }
}

public class B extends A {
    public static void test() {
        System.out.println("B");
    }
}

// Called statically
A.test();
B.test();
System.out.println();

// Called statically, testing static inheritance
A.test2();
B.test2();
System.out.println();

// Called via instance object
A a = new A();
B b = new B();
a.test();
b.test();
System.out.println();

// Testing inheritance via instance call
a.test2();
b.test2();
System.out.println();

// Testing whether calling static method via instance object is dependent on compile or runtime type
((A) b).hi();
System.out.println();

// Testing whether null instance works
A nullObj = null;
nullObj.hi();

Results:

A
B

Test
Test

A
B

Test
Test

A

A

Therefore, this is the conclusion:

  1. When we call the static in a static manner via ., it will look for the static defined in that class, or the class nearest to that in the inheritance chain. This proves that static methods are inherited.
  2. When static method is called from an instance, it calls the static method defined in the compile-time type.
  3. Static method can be called from a null instance. My guess is that the compiler will use the variable type to find the class during compilation, and translate that to the appropriate static method call.

Bootstrap with jQuery Validation Plugin

For full compatibility with Bootstrap 3 I added support for input-group, radio and checkbox, that was missing in the other solutions.

Update 10/20/2017: Inspected suggestions of the other answers and added additional support for special markup of radio-inline, better error placement for a group of radios or checkboxes and added support for a custom .novalidation class to prevent validation of controls. Hope this helps and thanks for the suggestions.

After including the validation plugin add the following call:

$.validator.setDefaults({
    errorElement: "span",
    errorClass: "help-block",
    highlight: function (element, errorClass, validClass) {
        // Only validation controls
        if (!$(element).hasClass('novalidation')) {
            $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
        }
    },
    unhighlight: function (element, errorClass, validClass) {
        // Only validation controls
        if (!$(element).hasClass('novalidation')) {
            $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
        }
    },
    errorPlacement: function (error, element) {
        if (element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        }
        else if (element.prop('type') === 'radio' && element.parent('.radio-inline').length) {
            error.insertAfter(element.parent().parent());
        }
        else if (element.prop('type') === 'checkbox' || element.prop('type') === 'radio') {
            error.appendTo(element.parent().parent());
        }
        else {
            error.insertAfter(element);
        }
    }
});

This works for all Bootstrap 3 form classes. If you use a horizontal form you have to use the following markup. This ensures that the help-block text respects the validation states ("has-error", ...) of the form-group.

<div class="form-group">
    <div class="col-lg-12">
        <div class="checkbox">
            <label id="LabelConfirm" for="CheckBoxConfirm">
                <input type="checkbox" name="CheckBoxConfirm" id="CheckBoxConfirm" required="required" />
                I have read all the information 
            </label>
        </div>
    </div>
</div>

difference between variables inside and outside of __init__()

As noted by S.Lott,

Variable set outside init belong to the class. They're shared by all instances.

Variables created inside init (and all other method functions) and prefaced with self. belong to the object instance.

However, Note that class variables can be accessed via self.<var> until they are masked by an object variable with a similar name This means that reading self.<var> before assigning it a value will return the value of Class.<var> but afterwards it will return obj.<var> . Here is an example

In [20]: class MyClass: 
    ...:     elem = 123 
    ...:  
    ...:     def update(self,i): 
    ...:         self.elem=i  
    ...:     def print(self): 
    ...:         print (MyClass.elem, self.elem) 
    ...:  
    ...: c1 = MyClass()  
    ...: c2 = MyClass() 
    ...: c1.print() 
    ...: c2.print()                                                                                                                                                                                                                                                               
123 123 
123 123 
In [21]: c1.update(1) 
    ...: c2.update(42) 
    ...: c1.print() 
    ...: c2.print()                                                                                                                                                                                                                                                               
123 1 
123 42
In [22]: MyClass.elem=22 
    ...: c1.print()  
    ...: c2.print()                                                                                                                                                                                                                                                               
22 1 
22 42

Second note: Consider slots. They may offer a better way to implement object variables.

Include files from parent or other directory

Had same issue earlier solved like this :

include('/../includes/config.php'); //note '/' appearing before '../includes/config.php'

What is the best workaround for the WCF client `using` block issue?

I have written a simple base class that handles this. It's available as a NuGet package and it's quite easy to use.

//MemberServiceClient is the class generated by SvcUtil
public class MemberServiceManager : ServiceClientBase<MemberServiceClient>
{
    public User GetUser(int userId)
    {
        return PerformServiceOperation(client => client.GetUser(userId));
    }

    //you can also check if any error occured if you can't throw exceptions       
    public bool TryGetUser(int userId, out User user)
    {
        return TryPerformServiceOperation(c => c.GetUser(userId), out user);
    }
}

How to access remote server with local phpMyAdmin client?

Just add below lines to your /etc/phpmyadmin/config.inc.php file in the bottom:

$i++;
$cfg['Servers'][$i]['host'] = 'HostName:port'; //provide hostname and port if other than default
$cfg['Servers'][$i]['user'] = 'userName';   //user name for your remote server
$cfg['Servers'][$i]['password'] = 'Password';  //password
$cfg['Servers'][$i]['auth_type'] = 'config';       // keep it as config

You will get Current Server: drop down with both 127.0.0.1 and one what you have provided with $cfg['Servers'][$i]['host'] can switch between the servers.

More Details: http://sforsuresh.in/access-remote-mysql-server-using-local-phpmyadmin/

Java: how to represent graphs?

Time ago I had the same problem and did my own implementation. What I suggest you is to implement another class: Edge. Then, a Vertex will have a List of Edge.

public class Edge {
    private Node a, b;
    private directionEnum direction;     // AB, BA or both
    private int weight;
    ...
}

It worked for me. But maybe is so simple. There is this library that maybe can help you if you look into its code: http://jgrapht.sourceforge.net/

Python and pip, list all versions of a package that's available?

This is Py3.9+ version of Limmy+EricChiang 's solution.

import json
import urllib.request
from distutils.version import StrictVersion


# print PyPI versions of package
def versions(package_name):
    url = "https://pypi.org/pypi/%s/json" % (package_name,)
    data = json.load(urllib.request.urlopen(url))
    versions = list(data["releases"])
    sortfunc = lambda x: StrictVersion(x.replace('rc', 'b').translate(str.maketrans('cdefghijklmn', 'bbbbbbbbbbbb')))
    versions.sort(key=sortfunc)
    return versions

How to create javascript delay function

Ah yes. Welcome to Asynchronous execution.

Basically, pausing a script would cause the browser and page to become unresponsive for 3 seconds. This is horrible for web apps, and so isn't supported.

Instead, you have to think "event-based". Use setTimeout to call a function after a certain amount of time, which will continue to run the JavaScript on the page during that time.

MySQL: View with Subquery in the FROM Clause Limitation

It appears to be a known issue.

http://dev.mysql.com/doc/refman/5.1/en/unnamed-views.html

http://bugs.mysql.com/bug.php?id=16757

Many IN queries can be re-written as (left outer) joins and an IS (NOT) NULL of some sort. for example

SELECT * FROM FOO WHERE ID IN (SELECT ID FROM FOO2)

can be re-written as

SELECT FOO.* FROM FOO JOIN FOO2 ON FOO.ID=FOO2.ID

or

SELECT * FROM FOO WHERE ID NOT IN (SELECT ID FROM FOO2)

can be

SELECT FOO.* FROM FOO 
LEFT OUTER JOIN FOO2 
ON FOO.ID=FOO2.ID WHERE FOO.ID IS NULL

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

Responsive image map

It depends, you can use jQuery to adjust the ranges proportionally I think. Why do you use an image map by the way? Can't you use scaling divs or other elements for it?

Print number of keys in Redis

dbsize() returns the total number of keys.

You can quickly estimate the number of keys matching a given pattern by sampling keys at random, then checking what fraction of them matches the pattern.

Example in python; counting all keys starting with prefix_:

import redis
r = redis.StrictRedis(host = 'localhost', port=6379)
iter=1000
print 'Approximately', r.dbsize() * float(sum([r.randomkey().startswith('prefix_') for i in xrange(iter)])) / iter

Even iter=100 gives a decent estimate in my case, yet is very fast, compared to keys prefix_.

An improvement is to sample 1000 keys on every request, but keep the total count, so that after two requests you'll divide by 2000, after three requests you'll divide by 3000. Thus, if your application is interested in the total number of matching keys fairly often, then every time it will get closer and closer to the true value.

How to stop the task scheduled in java.util.Timer class

Either call cancel() on the Timer if that's all it's doing, or cancel() on the TimerTask if the timer itself has other tasks which you wish to continue.

How do you render primitives as wireframes in OpenGL?

If it's OpenGL ES 2.0 you're dealing with, you can choose one of draw mode constants from

GL_LINE_STRIP, GL_LINE_LOOP, GL_LINES, to draw lines,

GL_POINTS (if you need to draw only vertices), or

GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN, and GL_TRIANGLES to draw filled triangles

as first argument to your

glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid * indices)

or

glDrawArrays(GLenum mode, GLint first, GLsizei count) calls.

java.math.BigInteger cannot be cast to java.lang.Long

Imagine d.getId is a Long, then wrap like this:

BigInteger l  = BigInteger.valueOf(d.getId());

Best way to center a <div> on a page vertically and horizontally?

I would use translate:

First position the div's top left corner at the center of the page (using position: fixed; top: 50%; left: 50%). Then, translate moves it up by 50% of the div's height to center it vertically on the page. Finally, translate also moves the div to the right by 50% of it's width to center it horizontally.

I actually think that this method is better than many of the others, since it does not require any changes on the parent element.

translate is better than translate3d in some scenarios due to it being supported by a greater number of browsers. https://caniuse.com/#feat=transforms2d

To sum it up, this method is supported on all versions of Chrome, Firefox 3.5+, Opera 11.5+, all versions of Safari, IE 9+, and Edge.

_x000D_
_x000D_
.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  
  font-size: 20px;
  background-color: cyan;
  border: darkgreen 5px solid;
  padding: 5px;
  z-index: 100;
}

table {
    position: absolute;
    top: 0;
    left: 0;
}

td {
    position: relative;
    top: 0;
    left: 0;
}
_x000D_
<table>
<tr>
    <td>
        <div class="centered">This div<br />is centered</div>
        <p>
            Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
        </p>
    </td>
    <td>
        <p>
            Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
        </p>
    </td>
</tr>
</table>
_x000D_
_x000D_
_x000D_

Notice, however, that this method makes this div stay in one place while the page is being scrolled. This may be what you want but if not, there is another method.


Now, if we try the same CSS, but with position set to absolute, it will be in the center of the last parent that has an absolute position.

_x000D_
_x000D_
.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);

  font-size: 20px;
  background-color: cyan;
  border: darkgreen 5px solid;
  padding: 5px;
  z-index: 100;
}

table {
    position: absolute;
    top: 0;
    left: 0;
}

td {
    position: relative;
    top: 0;
    left: 0;
}
_x000D_
<table>
<tr>
    <td>
        <div class="centered">This div<br />is centered</div>
        <p>
            Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
        </p>
    </td>
    <td>
        <p>
            Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
        </p>
    </td>
</tr>
</table>
_x000D_
_x000D_
_x000D_

Get all inherited classes of an abstract class

typeof(AbstractDataExport).Assembly tells you an assembly your types are located in (assuming all are in the same).

assembly.GetTypes() gives you all types in that assembly or assembly.GetExportedTypes() gives you types that are public.

Iterating through the types and using type.IsAssignableFrom() gives you whether the type is derived.

How to use Lambda in LINQ select statement

You appear to be trying to mix query expression syntax and "normal" lambda expression syntax. You can either use:

IEnumerable<SelectListItem> stores =
        from store in database.Stores
        where store.CompanyID == curCompany.ID
        select new SelectListItem { Value = store.Name, Text = store.ID};
ViewBag.storeSelector = stores;

Or:

IEnumerable<SelectListItem> stores = database.Stores
        .Where(store => store.CompanyID == curCompany.ID)
        .Select(s => new SelectListItem { Value = s.Name, Text = s.ID});
ViewBag.storeSelector = stores;

You can't mix the two like you're trying to.

ImportError: No module named psycopg2

Try with these:

virtualenv -p /usr/bin/python3 test_env
source test_env/bin/activate
pip install psycopg2

run python and try to import if you insist on installing it on your systems python try:

pip3 install psycopg2

Validating a Textbox field for only numeric input.

I have this extension which is kind of multi-purpose:

    public static bool IsNumeric(this object value)
    {
        if (value == null || value is DateTime)
        {
            return false;
        }

        if (value is Int16 || value is Int32 || value is Int64 || value is Decimal || value is Single || value is Double || value is Boolean)
        {
            return true;
        }

        try
        {
            if (value is string)
                Double.Parse(value as string);
            else
                Double.Parse(value.ToString());
            return true;
        }
        catch { }
        return false;
    }

It works for other data types. Should work fine for what you want to do.

jQuery access input hidden value

There is nothing special about <input type="hidden">:

$('input[type="hidden"]').val()

Python popen command. Wait until the command is finished

Force popen to not continue until all output is read by doing:

os.popen(command).read()

Axios handling errors

You can go like this: error.response.data
In my case, I got error property from backend. So, I used error.response.data.error

My code:

axios
  .get(`${API_BASE_URL}/students`)
  .then(response => {
     return response.data
  })
  .then(data => {
     console.log(data)
  })
  .catch(error => {
     console.log(error.response.data.error)
  })

How to insert text at beginning of a multi-line selection in vi/Vim

Mark the area to be comment as a visual block (<C-V)

and do c#<ESC>p

  1. change it to "#"
  2. put it back

If you do it often, define a short cut (example \q) in your .vimrc

:vmap \q c#<ESC>p

Bootstrap 3 jquery event for active tab change

This worked for me.

$('.nav-pills > li > a').click( function() {
    $('.nav-pills > li.active').removeClass('active');
    $(this).parent().addClass('active');
} );

How do I disable Git Credential Manager for Windows?

To prevent the dialog use git config --global credential.modalPrompt false, that'll drive the queries to the console.

Creating InetAddress object in Java

The api is fairly easy to use.

// Lookup the dns, if the ip exists.
 if (!ip.isEmpty()) {
     InetAddress inetAddress = InetAddress.getByName(ip);
     dns = inetAddress.getCanonicalHostName(); 
 }

Is there a download function in jsFiddle?

In a recent work I had to download a list of fiddle urls and create separate folder for each fiddles having separate html css js file for each, i have created the following crawler program for this. https://github.com/sguha-work/FiddleCrawler .It will create folder name with counter value and each folder will have a html, a css, a js and a details file. (The details file will holds the links of external resources).

Handling identity columns in an "Insert Into TABLE Values()" statement?

By default, if you have an identity column, you do not need to specify it in the VALUES section. If your table is:

ID    NAME    ADDRESS

Then you can do:

INSERT INTO MyTbl VALUES ('Joe', '123 State Street, Boston, MA')

This will auto-generate the ID for you, and you don't have to think about it at all. If you SET IDENTITY_INSERT MyTbl ON, you can assign a value to the ID column.

Why does Git say my master branch is "already up to date" even though it is not?

I had the same problem as you.

I did git status git fetch git pull, but my branch was still behind to origin. I had folders and files pushed to remote and I saw the files on the web, but on my local they were missing.

Finally, these commands updated all the files and folders on my local:

git fetch --all
git reset --hard origin/master 

or if you want a branch

git checkout your_branch_name_here
git reset --hard origin/your_branch_name_here

Creating a range of dates in Python

You can write a generator function that returns date objects starting from today:

import datetime

def date_generator():
  from_date = datetime.datetime.today()
  while True:
    yield from_date
    from_date = from_date - datetime.timedelta(days=1)

This generator returns dates starting from today and going backwards one day at a time. Here is how to take the first 3 dates:

>>> import itertools
>>> dates = itertools.islice(date_generator(), 3)
>>> list(dates)
[datetime.datetime(2009, 6, 14, 19, 12, 21, 703890), datetime.datetime(2009, 6, 13, 19, 12, 21, 703890), datetime.datetime(2009, 6, 12, 19, 12, 21, 703890)]

The advantage of this approach over a loop or list comprehension is that you can go back as many times as you want.

Edit

A more compact version using a generator expression instead of a function:

date_generator = (datetime.datetime.today() - datetime.timedelta(days=i) for i in itertools.count())

Usage:

>>> dates = itertools.islice(date_generator, 3)
>>> list(dates)
[datetime.datetime(2009, 6, 15, 1, 32, 37, 286765), datetime.datetime(2009, 6, 14, 1, 32, 37, 286836), datetime.datetime(2009, 6, 13, 1, 32, 37, 286859)]

how to add the missing RANDR extension

I had the same problem with Firefox 30 + Selenium 2.49 + Ubuntu 15.04.

It worked fine with Ubuntu 14 but after upgrade to 15.04 I got same RANDR warning and problem at starting Firefox using Xfvb.

After adding +extension RANDR it worked again.

$ vim /etc/init/xvfb.conf

#!upstart
description "Xvfb Server as a daemon"

start on filesystem and started networking
stop on shutdown

respawn

env XVFB=/usr/bin/Xvfb
env XVFBARGS=":10 -screen 1 1024x768x24 -ac +extension GLX +extension RANDR +render -noreset"
env PIDFILE=/var/run/xvfb.pid

exec start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE --exec $XVFB -- $XVFBARGS >> /var/log/xvfb.log 2>&1

Exposing a port on a live Docker container

Based on Robm's answer I have created a Docker image and a Bash script called portcat.

Using portcat, you can easily map multiple ports to an existing Docker container. An example using the (optional) Bash script:

curl -sL https://raw.githubusercontent.com/archan937/portcat/master/script/install | sudo bash
portcat my-awesome-container 3456 4444:8080

And there you go! Portcat is mapping:

  • port 3456 to my-awesome-container:3456
  • port 4444 to my-awesome-container:8080

Please note that the Bash script is optional, the following commands:

ipAddress=$(docker inspect my-awesome-container | grep IPAddress | grep -o '[0-9]\{1,3\}\(\.[0-9]\{1,3\}\)\{3\}' | head -n 1)
docker run -p 3456:3456 -p 4444:4444 --name=alpine-portcat -it pmelegend/portcat:latest $ipAddress 3456 4444:8080

I hope portcat will come in handy for you guys. Cheers!

Change placeholder text

Using jquery you can do this by following code:

<input type="text" id="tbxEmail" name="Email" placeholder="Some Text"/>

$('#tbxEmail').attr('placeholder','Some New Text');

How to get index of object by its property in JavaScript?

This might be useful

function showProps(obj, objName) {  
  var result = "";  
  for (var i in obj)  
    result += objName + "." + i + " = " + obj[i] + "\n";  
  return result;  
}

Copied this from https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects

Ruby capitalize every word first letter

"hello world".split.each{|i| i.capitalize!}.join(' ')

What is [Serializable] and when should I use it?

Since the original question was about the SerializableAttribute, it should be noted that this attribute only applies when using the BinaryFormatter or SoapFormatter.

It is a bit confusing, unless you really pay attention to the details, as to when to use it and what its actual purpose is.

It has NOTHING to do with XML or JSON serialization.

Used with the SerializableAttribute are the ISerializable Interface and SerializationInfo Class. These are also only used with the BinaryFormatter or SoapFormatter.

Unless you intend to serialize your class using Binary or Soap, do not bother marking your class as [Serializable]. XML and JSON serializers are not even aware of its existence.

Disallow Twitter Bootstrap modal window from closing

Override the Bootstrap ‘hide’ event of Dialog and stop its default behavior (to dispose the dialog).

Please see the below code snippet:

   $('#yourDialogID').on('hide.bs.modal', function(e) {

       e.preventDefault();
   });

It works fine in our case.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

For me it was different from any of the above,

The activity was declared as abstract, That is why giving the error. Once it removed it worked.

Earlier

     public abstract class SampleActivity extends AppcompatActivity{
     }

After removal

     public class SampleActivity extends AppcompatActivity{
     }

Under which circumstances textAlign property works in Flutter?

You can align text anywhere in the scaffold or container except center:-

Its works for me anywhere in my application:-

new Text(

                "Nextperience",

//i have setted in center.

                textAlign: TextAlign.center,

//when i want it left.

 //textAlign: TextAlign.left,

//when i want it right.

 //textAlign: TextAlign.right,

                style: TextStyle(

                    fontSize: 16,

                    color: Colors.blue[900],

                    fontWeight: FontWeight.w500),

              ), 

How to downgrade Xcode to previous version?

When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools

Convert UTC/GMT time to local time

I'd look into using the System.TimeZoneInfo class if you are in .NET 3.5. See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx. This should take into account the daylight savings changes correctly.

// Coordinated Universal Time string from 
// DateTime.Now.ToUniversalTime().ToString("u");
string date = "2009-02-25 16:13:00Z"; 
// Local .NET timeZone.
DateTime localDateTime = DateTime.Parse(date); 
DateTime utcDateTime = localDateTime.ToUniversalTime();

// ID from: 
// "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zone"
// See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.id.aspx
string nzTimeZoneKey = "New Zealand Standard Time";
TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);
DateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);

How to print a float with 2 decimal places in Java?

double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));

Delete a row in Excel VBA

Better yet, use union to grab all the rows you want to delete, then delete them all at once. The rows need not be continuous.

dim rng as range
dim rDel as range

for each rng in {the range you're searching}
   if {Conditions to be met} = true then
      if not rDel is nothing then
         set rDel = union(rng,rDel)
      else
         set rDel = rng
      end if
   end if
 next
 
 rDel.entirerow.delete

That way you don't have to worry about sorting or things being at the bottom.

After submitting a POST form open a new window showing the result

If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");

// setting form target to a window named 'formresult'
form.setAttribute("target", "formresult");

var hiddenField = document.createElement("input");              
hiddenField.setAttribute("name", "id");
hiddenField.setAttribute("value", "bob");
form.appendChild(hiddenField);
document.body.appendChild(form);

// creating the 'formresult' window with custom features prior to submitting the form
window.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');

form.submit();

What is the Java ?: operator called and what does it do?

int count = isHere ? getHereCount(index) : getAwayCount(index);

means :

if (isHere) {
    count = getHereCount(index);
} else {
    count = getAwayCount(index);
}

Psql list all tables

This can be used in automation scripts if you don't need all tables in all schemas:

  for table in $(psql -qAntc '\dt' | cut -d\| -f2); do
      ...
  done

How do I add a delay in a JavaScript loop?

In ES6 (ECMAScript 2015) you can iterate with delay with generator and interval.

Generators, a new feature of ECMAScript 6, are functions that can be paused and resumed. Calling genFunc does not execute it. Instead, it returns a so-called generator object that lets us control genFunc’s execution. genFunc() is initially suspended at the beginning of its body. The method genObj.next() continues the execution of genFunc, until the next yield. (Exploring ES6)


Code example:

_x000D_
_x000D_
let arr = [1, 2, 3, 'b'];_x000D_
let genObj = genFunc();_x000D_
_x000D_
let val = genObj.next();_x000D_
console.log(val.value);_x000D_
_x000D_
let interval = setInterval(() => {_x000D_
  val = genObj.next();_x000D_
  _x000D_
  if (val.done) {_x000D_
    clearInterval(interval);_x000D_
  } else {_x000D_
    console.log(val.value);_x000D_
  }_x000D_
}, 1000);_x000D_
_x000D_
function* genFunc() {_x000D_
  for(let item of arr) {_x000D_
    yield item;_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

So if you are using ES6, that the most elegant way to achieve loop with delay (for my opinion).

What is the email subject length limit?

See RFC 2822, section 2.1.1 to start.

There are two limits that this standard places on the number of characters in a line. Each line of characters MUST be no more than 998 characters, and SHOULD be no more than 78 characters, excluding the CRLF.

As the RFC states later, you can work around this limit (not that you should) by folding the subject over multiple lines.

Each header field is logically a single line of characters comprising the field name, the colon, and the field body. For convenience however, and to deal with the 998/78 character limitations per line, the field body portion of a header field can be split into a multiple line representation; this is called "folding". The general rule is that wherever this standard allows for folding white space (not simply WSP characters), a CRLF may be inserted before any WSP. For example, the header field:

       Subject: This is a test

can be represented as:

       Subject: This
        is a test

The recommendation for no more than 78 characters in the subject header sounds reasonable. No one wants to scroll to see the entire subject line, and something important might get cut off on the right.

Found conflicts between different versions of the same dependent assembly that could not be resolved

I can only support further Ruben's answer with a comparison between the two messages displayed:

enter image description here

and the message:

C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets(1697,5): warning MSB3277: Found conflicts between different versions of the same dependent assembly that could not be resolved. These reference conflicts are listed in the build log when log verbosity is set to detailed.

So, Ruben's right—this is just not true. There are no conflicts whatsoever, just a missing assembly. This is especially boring when the project is an ASP.NET application, since the views are compiled on demand, that is, just before displayed for the first time. This is when it becomes necessary to have the assembly available. (There's an option to pre-compile the views together with the rest of the code, but this is another story.) On the other hand, if you set the verbosity to Diagnostic you get the following output:

C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets(1697,5): warning MSB3245: Could not resolve this reference. Could not locate the assembly "System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.

As a result, all you need to do is either:

  1. Add a reference to the assembly manually (locate it on disk, maybe GAC, and add it as a "direct" reference), or
  2. Use NuGet package (if published in the gallery) to download it and reference the assembly contained within it.

More about NuGet gallery here. More about precompiling ASP.NET views here.

How to make Bootstrap carousel slider use mobile left/right swipe

With bootstrap 4.2 its now very easy, you just need to pass the touch option in the carousel div as data-touch="true", as it accepts Boolean value only.

As in your case update bootstrap to 4.2 and paste(Or download source files) the following in exact order :

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

and then add the touch option in your bootstrap carousel div

    <div id="sidebar-carousel-1" class="carousel slide" data-ride="carousel" data-touch="true">

Font awesome is not showing icon

solved changing the targetted !importantized font-family selector from * { ... } to *:not(i) { ... }

(with scss preprocessor); hope u solved

how to install Lex and Yacc in Ubuntu?

Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:

sudo apt-get install bison flex

There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.

Redirect website after certain amount of time

If you want greater control you can use javascript rather than use the meta tag. This would allow you to have a visual of some kind, e.g. a countdown.

Here is a very basic approach using setTimeout()

_x000D_
_x000D_
<html>_x000D_
    <body>_x000D_
    <p>You will be redirected in 3 seconds</p>_x000D_
    <script>_x000D_
        var timer = setTimeout(function() {_x000D_
            window.location='http://example.com'_x000D_
        }, 3000);_x000D_
    </script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

NoClassDefFoundError in Java: com/google/common/base/Function

I got the same error, but it was resolved if you add the libraries of selenium (again if you haven't), if you are using INTELIJ

project>projectStructure>Module>+>add the selenium jars (both from lib folder and outside ones.).

Same needs to be done for other IDE's as well, like eclipse.

Best way to check for IE less than 9 in JavaScript without library

for what it's worth:

    if(  document.addEventListener  ){
        alert("you got IE9 or greater");
    }

This successfully targets IE 9+ because the addEventListener method was supported very early on for every major browser but IE. (Chrome, Firefox, Opera, and Safari) MDN Reference. It is supported currently in IE9 and we can expect it to continue to be supported here on out.

Reset Entity-Framework Migrations

In EF6

  1. Delete all your files in 'migrations' folder... But not the 'initial create' or 'config'.
  2. Delete the database.
  3. Now run Add-Migration Initial.
  4. Now you can 'update-database' and all will be well.

How to merge rows in a column into one cell in excel?

Inside CONCATENATE you can use TRANSPOSE if you expand it (F9) then remove the surrounding {}brackets like this recommends

=CONCATENATE(TRANSPOSE(B2:B19))

Becomes

=CONCATENATE("Oh ","combining ", "a " ...)

CONCATENATE(TRANSPOSE(B2:B19))

You may need to add your own separator on the end, say create a column C and transpose that column.

=B1&" "
=B2&" "
=B3&" "

Difference between no-cache and must-revalidate

Agreed with part of @Jeffrey Fox's answer:

max-age=0, must-revalidate and no-cache aren't exactly identical.

Not agreed with this part:

With no-cache, it would just show the cached content, which would be probably preferred by the user (better to have something stale than nothing at all).

What should implementations do when cache-control: no-cache revalidation failed is just not specified in the RFC document. It's all up to implementations. They may throw a 504 error like cache-control: must-revalidate or just serve a stale copy from cache.

npx command not found

if you are using macOS, use sudo command

sudo npm install -g npx

enter image description here

How to clear the interpreter console?

I'm new to python (really really new) and in one of the books I'm reading to get acquainted with the language they teach how to create this little function to clear the console of the visible backlog and past commands and prints:

Open shell / Create new document / Create function as follows:

def clear():
    print('\n' * 50)

Save it inside the lib folder in you python directory (mine is C:\Python33\Lib) Next time you nedd to clear your console just call the function with:

clear()

that's it. PS: you can name you function anyway you want. Iv' seen people using "wiper" "wipe" and variations.

Angularjs loading screen on ajax request

Include this in your "app.config":

 $httpProvider.interceptors.push('myHttpInterceptor');

And add this code:

app.factory('myHttpInterceptor', function ($q, $window,$rootScope) {
    $rootScope.ActiveAjaxConectionsWithouthNotifications = 0;
    var checker = function(parameters,status){
            //YOU CAN USE parameters.url TO IGNORE SOME URL
            if(status == "request"){
                $rootScope.ActiveAjaxConectionsWithouthNotifications+=1;
                $('#loading_view').show();
            }
            if(status == "response"){
                $rootScope.ActiveAjaxConectionsWithouthNotifications-=1;

            }
            if($rootScope.ActiveAjaxConectionsWithouthNotifications<=0){
                $rootScope.ActiveAjaxConectionsWithouthNotifications=0;
                $('#loading_view').hide();

            }


    };
return {
    'request': function(config) {
        checker(config,"request");
        return config;
    },
   'requestError': function(rejection) {
       checker(rejection.config,"request");
      return $q.reject(rejection);
    },
    'response': function(response) {
         checker(response.config,"response");
      return response;
    },
   'responseError': function(rejection) {
        checker(rejection.config,"response");
      return $q.reject(rejection);
    }
  };
});

Oracle - How to generate script from sql developer

If you want to see DDL for the objects, you can use

select dbms_metadata.get_ddl('OBJECT_TYPE','OBJECT_NAME','OBJECT_OWNER') 
  from dual
/

For example this will give you the DDL script for emp table.

select dbms_metadata.get_ddl('TABLE','EMP','HR') 
  from dual
/

You may need to set the long type format to big number. For packages, you need to access dba_source, user_source, all_source tables. You can query for object name and type to see what code is stored.

How do you reinstall an app's dependencies using npm?

You can do this with one simple command:

npm ci

Documentation:

npm ci
Install a project with a clean slate

How to perform keystroke inside powershell?

If I understand correctly, you want PowerShell to send the ENTER keystroke to some interactive application?

$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate('title of the application window')
Sleep 1
$wshell.SendKeys('~')

If that interactive application is a PowerShell script, just use whatever is in the title bar of the PowerShell window as the argument to AppActivate (by default, the path to powershell.exe). To avoid ambiguity, you can have your script retitle its own window by using the title 'new window title' command.

A few notes:

  • The tilde (~) represents the ENTER keystroke. You can also use {ENTER}, though they're not identical - that's the keypad's ENTER key. A complete list is available here: http://msdn.microsoft.com/en-us/library/office/aa202943%28v=office.10%29.aspx.
  • The reason for the Sleep 1 statement is to wait 1 second because it takes a moment for the window to activate, and if you invoke SendKeys immediately, it'll send the keys to the PowerShell window, or to nowhere.
  • Be aware that this can be tripped up, if you type anything or click the mouse during the second that it's waiting, preventing to window you activate with AppActivate from being active. You can experiment with reducing the amount of time to find the minimum that's reliably sufficient on your system (Sleep accepts decimals, so you could try .5 for half a second). I find that on my 2.6 GHz Core i7 Win7 laptop, anything less than .8 seconds has a significant failure rate. I use 1 second to be safe.
  • IMPORTANT WARNING: Be extra careful if you're using this method to send a password, because activating a different window between invoking AppActivate and invoking SendKeys will cause the password to be sent to that different window in plain text!

Sometimes wscript.shell's SendKeys method can be a little quirky, so if you run into problems, replace the fourth line above with this:

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait('~');

Multidimensional Array [][] vs [,]

double[][] are called jagged arrays , The inner dimensions aren’t specified in the declaration. Unlike a rectangular array, each inner array can be an arbitrary length. Each inner array is implicitly initialized to null rather than an empty array. Each inner array must be created manually: Reference [C# 4.0 in nutshell The definitive Reference]

for (int i = 0; i < matrix.Length; i++)
{
    matrix[i] = new int [3]; // Create inner array
    for (int j = 0; j < matrix[i].Length; j++)
        matrix[i][j] = i * 3 + j;
}

double[,] are called rectangular arrays, which are declared using commas to separate each dimension. The following piece of code declares a rectangular 3-by-3 two-dimensional array, initializing it with numbers from 0 to 8:

int [,] matrix = new int [3, 3];
for (int i = 0; i < matrix.GetLength(0); i++)
    for (int j = 0; j < matrix.GetLength(1); j++)
        matrix [i, j] = i * 3 + j;

Uploading images using Node.js, Express, and Mongoose

Here's a way to upload your images using the formidable package, which is recommended over bodyParser in later versions of Express. This also includes the ability to resize your images on the fly:

From my website: Uploading and Resizing Images (on the fly) With Node.js and Express.

Here's the gist:

var express = require("express"),
app = express(),
formidable = require('formidable'),
util = require('util')
fs   = require('fs-extra'),
qt   = require('quickthumb');

// Use quickthumb
app.use(qt.static(__dirname + '/'));

app.post('/upload', function (req, res){
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files) {
    res.writeHead(200, {'content-type': 'text/plain'});
    res.write('received upload:\n\n');
    res.end(util.inspect({fields: fields, files: files}));
  });

  form.on('end', function(fields, files) {
    /* Temporary location of our uploaded file */
    var temp_path = this.openedFiles[0].path;
    /* The file name of the uploaded file */
    var file_name = this.openedFiles[0].name;
    /* Location where we want to copy the uploaded file */
    var new_location = 'uploads/';

    fs.copy(temp_path, new_location + file_name, function(err) {  
      if (err) {
        console.error(err);
      } else {
        console.log("success!")
      }
    });
  });
});

// Show the upload form 
app.get('/', function (req, res){
  res.writeHead(200, {'Content-Type': 'text/html' });
  /* Display the file upload form. */
  form = '<form action="/upload" enctype="multipart/form-data" method="post">'+ '<input name="title" type="text" />
  '+ '<input multiple="multiple" name="upload" type="file" />
  '+ '<input type="submit" value="Upload" />'+ '</form>';
  res.end(form); 
}); 
app.listen(8080);

NOTE: This requires Image Magick for the quick thumb resizing.

How to create id with AUTO_INCREMENT on Oracle?

Starting with Oracle 12c there is support for Identity columns in one of two ways:

  1. Sequence + Table - In this solution you still create a sequence as you normally would, then you use the following DDL:

    CREATE TABLE MyTable (ID NUMBER DEFAULT MyTable_Seq.NEXTVAL, ...)

  2. Table Only - In this solution no sequence is explicitly specified. You would use the following DDL:

    CREATE TABLE MyTable (ID NUMBER GENERATED AS IDENTITY, ...)

If you use the first way it is backward compatible with the existing way of doing things. The second is a little more straightforward and is more inline with the rest of the RDMS systems out there.

z-index not working with position absolute

I faced this issue a lot when using position: absolute;, I faced this issue by using position: relative in the child element. don't need to change position: absolute to relative, just need to add in the child element look into the beneath two examples:

_x000D_
_x000D_
let toggle = document.getElementById('toggle')

toggle.addEventListener("click", () => {
 toggle.classList.toggle('change');
})
_x000D_
.container {
  width: 60px;
  height: 22px;
  background: #333;
  border-radius: 20px;
  position: relative;
  cursor: pointer;

}

.change .slide {
  transform: translateX(33px);
}

.slide {
  transition: 0.5s;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 20px;
  margin: 2px 2px;
  z-index: 100;
}

.dot {
  width: 10px;
  height: 16px;
  background: red;
  position: absolute;
  top: 4px;
  right: 5px;
  z-index: 1;
}
_x000D_
<div class="container" id="toggle">
  <div class="slide"></div>
  <div class="dot"></div>
</div>
_x000D_
_x000D_
_x000D_

This's how it can be fixed using position relative:

_x000D_
_x000D_
let toggle = document.getElementById('toggle')

toggle.addEventListener("click", () => {
 toggle.classList.toggle('change');
})
_x000D_
.container {
  width: 60px;
  height: 22px;
  background: #333;
  border-radius: 20px;
  position: relative;
  cursor: pointer;

}

.change .slide {
  transform: translateX(33px);
}

.slide {
  transition: 0.5s;
  width: 20px;
  height: 20px;
  background: #fff;
  border-radius: 20px;
  margin: 2px 2px;
  z-index: 100;
  
  // Just add position relative;
  position: relative;
}

.dot {
  width: 10px;
  height: 16px;
  background: red;
  position: absolute;
  top: 4px;
  right: 5px;
  z-index: 1;
}
_x000D_
<div class="container" id="toggle">
  <div class="slide"></div>
  <div class="dot"></div>
</div>
_x000D_
_x000D_
_x000D_

Sandbox here

CSS fixed width in a span

In an ideal world you'd achieve this simply using the following css

<style type="text/css">

span {
  display: inline-block;
  width: 50px;
}

</style>

This works on all browsers apart from FF2 and below.

Firefox 2 and lower don't support this value. You can use -moz-inline-box, but be aware that it's not the same as inline-block, and it may not work as you expect in some situations.

Quote taken from quirksmode

What are the ascii values of up down left right?

this is what i get:

Left - 19 Up - 5 Right - 4 Down - 24

Works in Visual Fox Pro

python: changing row index of pandas data frame

you can do

followers_df.index = range(20)

SVN Commit specific files

Due to my subversion state, I had to get creative. svn st showed M,A and ~ statuses. I only wanted M and A so...

svn st | grep ^[A\|M] | cut -d' ' -f8- > targets.txt

This command says find all the lines output by svn st that start with M or A, cut using space delimiter, then get colums 8 to the end. Dump that into targets.txt and overwrite.

Then modify targets.txt to prune the file list further. Then run below to commit:

svn ci -m "My commit message" --targets targets.txt

Probably not the most common use case, but hopefully it helps someone.

Rock, Paper, Scissors Game Java

int w =0 , l =0, d=0, i=0;
    Scanner sc = new Scanner(System.in);

// try tentimes
    while (i<10) {


        System.out.println("scissor(1) ,Rock(2),Paper(3) ");
        int n = sc.nextInt();
        int m =(int)(Math.random()*3+1);


        if(n==m){

            System.out.println("Com:"+m +"so>>> " + "draw");
            d++;


        }else if ((n-1)%3==(m%3)){
            w++;
            System.out.println("Com:"+m +"so>>> " +"win");
        }
        else if(n >=4 )
        {
            System.out.println("pleas enter correct number)");


    }
        else {
            System.out.println("Com:"+m +"so>>> " +"lose");
            l++;

        }
        i++;

Curl GET request with json parameter

None of the above mentioned solution worked for me due to some reason. Here is my solution. It's pretty basic.

curl -X GET API_ENDPOINT -H 'Content-Type: application/json' -d 'JSON_DATA'

API_ENDPOINT is your api endpoint e.g: http://127.0.0.1:80/api

-H has been used to added header content.

JSON_DATA is your request body it can be something like :: {"data_key": "value"} . ' ' surrounding JSON_DATA are important.

Anything after -d is the data which you need to send in the GET request

Git - how delete file from remote repository

The easiest thing to do is to move the file from your local directory temporarily, then commit changes to your remote repo. Then add it back to your local repo, make sure to update .gitignore so it doesn't commit to remote again

Add placeholder text inside UITextView in Swift?

I don't know why people over complicate this issue so much.... It's fairly straight forward and simple. Here's a subclass of UITextView that provides the requested functionality.

- (void)customInit
{
    self.contentMode = UIViewContentModeRedraw;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
}

    - (void)textChanged:(NSNotification *)notification
    {
        if (notification.object == self) {
            if(self.textStorage.length != 0 || !self.textStorage.length) {
                [self setNeedsDisplay];
            }
        }
    }


    #pragma mark - Setters

    - (void)setPlaceholderText:(NSString *)placeholderText withFont:(UIFont *)font
    {
        self.placeholderText = placeholderText;
        self.placeholderTextFont = font;

    }



    - (void)drawRect:(CGRect)rect
    {
        [super drawRect:rect];
        [[UIColor lightGrayColor] setFill];

        if (self.textStorage.length != 0) {
            return;
        }

        CGRect inset = CGRectInset(rect, 8, 8);//Default rect insets for textView
        NSDictionary *attributes =  @{NSFontAttributeName: self.placeholderTextFont, NSForegroundColorAttributeName: [UIColor grayColor]};
        [self.placeholderText drawInRect:inset withAttributes:attributes];
    }`

How to calculate age in T-SQL with years, months, and days

There is another method for calculate age is

See below table

    FirstName       LastName    DOB
    sai             krishnan    1991-11-04
    Harish          S A         1998-10-11

For finding age,you can calculate through month

  Select datediff(MONTH,DOB,getdate())/12 as dates from [Organization].[Employee]

Result will be

firstname   dates
sai         27
Harish      20

Why Response.Redirect causes System.Threading.ThreadAbortException?

I know I'm late, but I've only ever had this error if my Response.Redirect is in a Try...Catch block.

Never put a Response.Redirect into a Try...Catch block. It's bad practice

As an alternative to putting the Response.Redirect into the Try...Catch block, I'd break up the method/function into two steps.

  1. inside the Try...Catch block performs the requested actions and sets a "result" value to indicate success or failure of the actions.

  2. outside of the Try...Catch block does the redirect (or doesn't) depending on what the "result" value is.

This code is far from perfect and probably should not be copied since I haven't tested it.

public void btnLogin_Click(UserLoginViewModel model)
{
    bool ValidLogin = false; // this is our "result value"
    try
    {
        using (Context Db = new Context)
        {
            User User = new User();

            if (String.IsNullOrEmpty(model.EmailAddress))
                ValidLogin = false; // no email address was entered
            else
                User = Db.FirstOrDefault(x => x.EmailAddress == model.EmailAddress);

            if (User != null && User.PasswordHash == Hashing.CreateHash(model.Password))
                ValidLogin = true; // login succeeded
        }
    }
    catch (Exception ex)
    {
        throw ex; // something went wrong so throw an error
    }

    if (ValidLogin)
    {
        GenerateCookie(User);
        Response.Redirect("~/Members/Default.aspx");
    }
    else
    {
        // do something to indicate that the login failed.
    }
}

How to set placeholder value using CSS?

If the content is loaded via ajax anyway, use javascript to manipulate the placeholder. Every css approach is hack-isch anyway. E.g. with jQuery: $('#myFieldId').attr('placeholder', 'Search for Stuff');

Java - Convert integer to string

This will do. Pretty trustworthy. : )

    ""+number;

Just to clarify, this works and acceptable to use unless you are looking for micro optimization.

Sniff HTTP packets for GET and POST requests from an application

Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.

Regular Expression For Duplicate Words

Since some developers are coming to this page in search of a solution which not only eliminates duplicate consecutive non-whitespace substrings, but triplicates and beyond, I'll show the adapted pattern.

Pattern: /(\b\S+)(?:\s+\1\b)+/ (Pattern Demo)
Replace: $1 (replaces the fullstring match with capture group #1)

This pattern greedily matches a "whole" non-whitespace substring, then requires one or more copies of the matched substring which may be delimited by one or more whitespace characters (space, tab, newline, etc).

Specifically:

  • \b (word boundary) characters are vital to ensure partial words are not matched.
  • The second parenthetical is a non-capturing group, because this variable width substring does not need to be captured -- only matched/absorbed.
  • the + (one or more quantifier) on the non-capturing group is more appropriate than * because * will "bother" the regex engine to capture and replace singleton occurrences -- this is wasteful pattern design.

*note if you are dealing with sentences or input strings with punctuation, then the pattern will need to be further refined.

Why use 'git rm' to remove a file instead of 'rm'?

However, if you do end up using rm instead of git rm. You can skip the git add and directly commit the changes using:

git commit -a

Get image data url in JavaScript?

In HTML5 better use this:

{
//...
canvas.width = img.naturalWidth; //img.width;
canvas.height = img.naturalHeight; //img.height;
//...
}

Difference between HashMap and Map in Java..?

Map is an interface in Java. And HashMap is an implementation of that interface (i.e. provides all of the methods specified in the interface).

Could not find main class HelloWorld

Just remove your "classpath" from you environment variable. Then try running:

java HelloWorld 

This should work fine.

<SELECT multiple> - how to allow only one item selected?

You want only one option by default, but the user can select multiple options by pressing the CTRL key. This is (already) exactly how the SELECT multiple is meant to behave.

See this: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select_multiple

Can you please clarify your question?

WAMP Server doesn't load localhost

Solution(s) for this, found in the official wampserver.com forums:

SOLUTION #1:

This problem is caused by Windows (7) in combination with any software that also uses port 80 (like Skype or IIS (which is installed on most developer machines)). A video solution can be found here (34.500+ views, damn, this seems to be a big thing ! EDIT: The video now has ~60.000 views ;) )

To make it short: open command line tool, type "netstat -aon" and look for any lines that end of ":80". Note thatPID on the right side. This is the process id of the software which currently usesport 80. Press AltGr + Ctrl + Del to get into the Taskmanager. Switch to the tab where you can see all services currently running, ordered by PID. Search for that PID you just notices and stop that thing (right click). To prevent this in future, you should config the software's port settings (skype can do that).

SOLUTION #2:

left click the wamp icon in the taskbar, go to apache > httpd.conf and edit this file: change "listen to port .... 80" to 8080. Restart. Done !

SOLUTION #3:

Port 80 blocked by "Microsoft Web Deployment Service", simply deinstall this, more info here

By the way, it's not Microsoft's fault, it's a stupid usage of ports by most WAMP stacks.

IMPORTANT: you have to use localhost or 127.0.0.1 now with port 8080, this means 127.0.0.1:8080 or localhost:8080.

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

If you are working on Root Directory then you can use this approach

res.sendFile(__dirname + '/FOLDER_IN_ROOT_DIRECTORY/index.html');

but if you are using Routes which is inside a folder lets say /Routes/someRoute.js then you will need to do something like this

const path = require("path");
...
route.get("/some_route", (req, res) => {
   res.sendFile(path.resolve('FOLDER_IN_ROOT_DIRECTORY/index.html')
});

WebSocket with SSL

To support the answer by @oberstet, if the cert is not trusted by the browser (for example you get a "this site is not secure, do you want to continue?") one solution is to open the browser options, navigate to the certificates settings and add the host and post that the websocket server is being served from to the certificate provider as an exception.

for example add 'example-wss-domain.org:6001' as an exception to 'Certificate Provider Ltd'.

In firefox, this can be done from 'about:preferences' and searching for 'Certificates'

MySQL the right syntax to use near '' at line 1 error

INSERT INTO wp_bp_activity
            (
            user_id,
             component,
             `type`,
             `action`,
             content,
             primary_link,
             item_id,
             secondary_item_id,
             date_recorded,
             hide_sitewide,
             mptt_left,
             mptt_right
             )
             VALUES(
             1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
             )

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

Try the below steps:

npm uninstall webpack --save-dev

followed by

npm install [email protected] --save-dev

Then you should be able to gulp again. Fixed the issue for me.

How do I check in JavaScript if a value exists at a certain array index?

I think this decision is appropriate for guys who prefer the declarative functional programming over the imperative OOP or the procedural. If your question is "Is there some values inside? (a truthy or a falsy value)" you can use .some method to validate the values inside.

[].some(el => el || !el);
  • It isn't perfect but it doesn't require to apply any extra function containing the same logic, like function isEmpty(arr) { ... }.
  • It still sounds better than "Is it zero length?" when we do this [].length resulting to 0 which is dangerous in some cases.
  • Or even this [].length > 0 saying "Is its length greater than zero?"

Advanced examples:

[    ].some(el => el || !el); // false
[null].some(el => el || !el); // true
[1, 3].some(el => el || !el); // true

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

Find elements inside forms and iframe using Java and Selenium WebDriver

When using an iframe, you will first have to switch to the iframe, before selecting the elements of that iframe

You can do it using:

driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();

In case if your frameId is dynamic, and you only have one iframe, you can use something like:

driver.switchTo().frame(driver.findElement(By.tagName("iframe")));

How do I execute .js files locally in my browser?

Around 1:51 in the video, notice how she puts a <script> tag in there? The way it works is like this:

Create an html file (that's just a text file with a .html ending) somewhere on your computer. In the same folder that you put index.html, put a javascript file (that's just a textfile with a .js ending - let's call it game.js). Then, in your index.html file, put some html that includes the script tag with game.js, like Mary did in the video. index.html should look something like this:

<html>
    <head>
        <script src="game.js"></script>
    </head>
</html>

Now, double click on that file in finder, and it should open it up in your browser. To open up the console to see the output of your javascript code, hit Command-alt-j (those three buttons at the same time).

Good luck on your journey, hope it's as fun for you as it has been for me so far :)

Group array items using object

Beside the given approaches with a two pass approach, you could take a single loop approach by pushing the group if a new group is found.

_x000D_
_x000D_
var array = [{ group: "one", color: "red" }, { group: "two", color: "blue" }, { group: "one", color: "green" }, { group: "one", color: "black" }],_x000D_
    groups = Object.create(null),_x000D_
    grouped = [];_x000D_
_x000D_
array.forEach(function (o) {_x000D_
    if (!groups[o.group]) {_x000D_
        groups[o.group] = [];_x000D_
        grouped.push({ group: o.group, color: groups[o.group] });_x000D_
    }_x000D_
    groups[o.group].push(o.color);_x000D_
});_x000D_
_x000D_
console.log(grouped);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
_x000D_
_x000D_

One time page refresh after first page load

When I meet this problem, I search to here but most of answers are trying to modify existing url. Here is another answer which works for me using localStorage.

<script type='text/javascript'>

(function()
{
  if( window.localStorage )
  {
    if( !localStorage.getItem('firstLoad') )
    {
      localStorage['firstLoad'] = true;
      window.location.reload();
    }  
    else
      localStorage.removeItem('firstLoad');
  }
})();

</script>

How to use a variable in the replacement side of the Perl substitution operator?

As others have suggested, you could use the following:

my $find = 'start (.*) end';
my $replace = 'foo $1 bar';   # 'foo \1 bar' is an error.
my $var = "start middle end";
$var =~ s/$find/$replace/ee;

The above is short for the following:

my $find = 'start (.*) end';
my $replace = 'foo $1 bar';
my $var = "start middle end";
$var =~ s/$find/ eval($replace) /e;

I prefer the second to the first since it doesn't hide the fact that eval(EXPR) is used. However, both of the above silence errors, so the following would be better:

my $find = 'start (.*) end';
my $replace = 'foo $1 bar';
my $var = "start middle end";
$var =~ s/$find/ my $r = eval($replace); die $@ if $@; $r /e;

But as you can see, all of the above allow for the execution of arbitrary Perl code. The following would be far safer:

use String::Substitution qw( sub_modify );

my $find = 'start (.*) end';
my $replace = 'foo $1 bar';
my $var = "start middle end";
sub_modify($var, $find, $replace);

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

Problem partially was solved. Besides creating jdbc/resource(DB Derby) had to create JDBC Connection Pool for db resource in Glassfish admin console, and check it on pinging. Now all CRUD operation work just fine. I check, object Customer in database adding properly, update and delete too. But in Glassfish output log have same exception:

SEVERE:   org.hibernate.hql.internal.ast.QuerySyntaxException: CUSTOMERV is not mapped [select concat(first_name, ' ', last_name) as name from CUSTOMERV]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:96)
    at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:120)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:234)
    .......

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: CUSTOMERV is not mapped
    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:189)
    at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:109)

favicon not working in IE

Should anyone make it down to this answer:

Same issue: didn't work in IE (including IE 10), worked everywhere else.

Turns out that the file was not a "real" .ico file. I fixed this by uploading it to http://www.favicon.cc/ and then downloading it again.

First I tested it by generating a random .ico file on this site and using that instead of my original file. Saw that it worked.

ERROR 1049 (42000): Unknown database

blog_development doesn't exist

You can see this in sql by the 0 rows affected message

create it in mysql with

mysql> create database blog_development

However as you are using rails you should get used to using

$ rake db:create

to do the same task. It will use your database.yml file settings, which should include something like:

development:
  adapter: mysql2
  database: blog_development
  pool: 5

Also become familiar with:

$ rake db:migrate  # Run the database migration
$ rake db:seed     # Run thew seeds file create statements
$ rake db:drop     # Drop the database

How to handle a single quote in Oracle SQL

Use two single-quotes

SQL> SELECT 'D''COSTA' name FROM DUAL;

NAME
-------
D'COSTA

Alternatively, use the new (10g+) quoting method:

SQL> SELECT q'$D'COSTA$' NAME FROM DUAL;

NAME
-------
D'COSTA

Put icon inside input element in a form

This works for me for more or less standard forms:

  <button type="submit" value="Submit" name="ButtonType" id="whateveristheId" class="button-class">Submit<img src="/img/selectedImage.png" alt=""></button>

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

I wrote a function for my own project to do this (it doesn't use numpy, though):

def partition(seq, chunks):
    """Splits the sequence into equal sized chunks and them as a list"""
    result = []
    for i in range(chunks):
        chunk = []
        for element in seq[i:len(seq):chunks]:
            chunk.append(element)
        result.append(chunk)
    return result

If you want the chunks to be randomized, just shuffle the list before passing it in.

How to check if a "lateinit" variable has been initialized?

You can easily do this by:

::variableName.isInitialized

or

this::variableName.isInitialized

But if you are inside a listener or inner class, do this:

this@OuterClassName::variableName.isInitialized

Note: The above statements work fine if you are writing them in the same file(same class or inner class) where the variable is declared but this will not work if you want to check the variable of other class (which could be a superclass or any other class which is instantiated), for ex:

class Test {
    lateinit var str:String
}

And to check if str is initialized:

enter image description here

What we are doing here: checking isInitialized for field str of Test class in Test2 class. And we get an error backing field of var is not accessible at this point. Check a question already raised about this.

How to send redirect to JSP page in Servlet

    String u = request.getParameter("username");
    String p = request.getParameter("password");

    try {
        st = con.createStatement();
        String sql;
        sql = "SELECT * FROM TableName where USERNAME = '" + u + "' and PASSWORD = '"
                + p + "'";
        ResultSet rs = st.executeQuery(sql);
        if (rs.next()) {
            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("/home.jsp");
            requestDispatcher.forward(request, response);
        } else {

            RequestDispatcher requestDispatcher = request
                    .getRequestDispatcher("/invalidLogin.jsp");
            requestDispatcher.forward(request, response);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    finally{
        try {
            rs.close();
            ps.close();
            con.close();
            st.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Java Read Large Text File With 70million line of text

I had a similar problem, but I only needed the bytes from the file. I read through links provided in the various answers, and ultimately tried writing one similar to #5 in Evgeniy's answer. They weren't kidding, it took a lot of code.

The basic premise is that each line of text is of unknown length. I will start with a SeekableByteChannel, read data into a ByteBuffer, then loop over it looking for EOL. When something is a "carryover" between loops, it increments a counter and then ultimately moves the SeekableByteChannel position around and reads the entire buffer.

It is verbose ... but it works. It was plenty fast for what I needed, but I'm sure there are more improvements that can be made.

The process method is stripped down to the basics for kicking off reading the file.

private long startOffset;
private long endOffset;
private SeekableByteChannel sbc;

private final ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

public void process() throws IOException
{
    startOffset = 0;
    sbc = Files.newByteChannel(FILE, EnumSet.of(READ));
    byte[] message = null;
    while((message = readRecord()) != null)
    {
        // do something
    }
}

public byte[] readRecord() throws IOException
{
    endOffset = startOffset;

    boolean eol = false;
    boolean carryOver = false;
    byte[] record = null;

    while(!eol)
    {
        byte data;
        buffer.clear();
        final int bytesRead = sbc.read(buffer);

        if(bytesRead == -1)
        {
            return null;
        }

        buffer.flip();

        for(int i = 0; i < bytesRead && !eol; i++)
        {
            data = buffer.get();
            if(data == '\r' || data == '\n')
            {
                eol = true;
                endOffset += i;

                if(carryOver)
                {
                    final int messageSize = (int)(endOffset - startOffset);
                    sbc.position(startOffset);

                    final ByteBuffer tempBuffer = ByteBuffer.allocateDirect(messageSize);
                    sbc.read(tempBuffer);
                    tempBuffer.flip();

                    record = new byte[messageSize];
                    tempBuffer.get(record);
                }
                else
                {
                    record = new byte[i];

                    // Need to move the buffer position back since the get moved it forward
                    buffer.position(0);
                    buffer.get(record, 0, i);
                }

                // Skip past the newline characters
                if(isWindowsOS())
                {
                    startOffset = (endOffset + 2);
                }
                else
                {
                    startOffset = (endOffset + 1);
                }

                // Move the file position back
                sbc.position(startOffset);
            }
        }

        if(!eol && sbc.position() == sbc.size())
        {
            // We have hit the end of the file, just take all the bytes
            record = new byte[bytesRead];
            eol = true;
            buffer.position(0);
            buffer.get(record, 0, bytesRead);
        }
        else if(!eol)
        {
            // The EOL marker wasn't found, continue the loop
            carryOver = true;
            endOffset += bytesRead;
        }
    }

    // System.out.println(new String(record));
    return record;
}

What are the differences between the BLOB and TEXT datatypes in MySQL?

TEXT and CHAR will convert to/from the character set they have associated with time. BLOB and BINARY simply store bytes.

BLOB is used for storing binary data while Text is used to store large string.

BLOB values are treated as binary strings (byte strings). They have no character set, and sorting and comparison are based on the numeric values of the bytes in column values.

TEXT values are treated as nonbinary strings (character strings). They have a character set, and values are sorted and compared based on the collation of the character set.

http://dev.mysql.com/doc/refman/5.0/en/blob.html

How to custom switch button?

With the Material Components Library you can use the MaterialButtonToggleGroup:

        <com.google.android.material.button.MaterialButtonToggleGroup
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:checkedButton="@id/b1"
            app:selectionRequired="true"
            app:singleSelection="true">

            <Button
                style="?attr/materialButtonOutlinedStyle"
                android:id="@+id/b1"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="OPT1" />

            <Button
                style="?attr/materialButtonOutlinedStyle"
                android:id="@+id/b2"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="OPT2" />

        </com.google.android.material.button.MaterialButtonToggleGroup>

enter image description here

Switch case in C# - a constant value is expected

You can't use a switch statement for this as the case values cannot be evaluated expressions. For this you have to use an an if/else ...

public static void Output<T>(IEnumerable<T> dataSource) where T : class
{   
    dataSourceName = (typeof(T).Name);
    if(string.Compare(dataSourceName, typeof(CustomerDetails).Name.ToString(), true)==0)
    {
        var t = 123;
    }
    else if (/*case 2 conditional*/)
    {
        //blah
    }
    else
    {
        //default case
        Console.WriteLine("Test");
    }
}

I also took the liberty of tidying up your conditional statement. There is no need to cast to string after calling ToString(). This will always return a string anyway. When comparing strings for equality, bare in mind that using the == operator will result in a case sensitive comparison. Better to use string compare = 0 with the last argument to set case sensitive on/off.

Window.open and pass parameters by post method

I've used this in the past, since we typically use razor syntax for coding

@using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { target = "_blank" }))

{

// add hidden and form filed here

}

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

For me this has worked-

ALTER TABLE table_name ALTER COLUMN column_name VARCHAR(50)

Hibernate Auto Increment ID

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

and you leave it null (0) when persisting. (null if you use the Integer / Long wrappers)

In some cases the AUTO strategy is resolved to SEQUENCE rathen than to IDENTITY or TABLE, so you might want to manually set it to IDENTITY or TABLE (depending on the underlying database).

It seems SEQUENCE + specifying the sequence name worked for you.

Can I run CUDA on Intel's integrated graphics processor?

Portland group have a commercial product called CUDA x86, it is hybrid compiler which creates CUDA C/ C++ code which can either run on GPU or use SIMD on CPU, this is done fully automated without any intervention for the developer. Hope this helps.

Link: http://www.pgroup.com/products/pgiworkstation.htm

Can I hide/show asp:Menu items based on role?

This is best done in the MenuItemDataBound.

protected void NavigationMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
    if (!Page.User.IsInRole("Admin"))
    {
        if (e.Item.NavigateUrl.Equals("/admin"))
        {
            if (e.Item.Parent != null)
            {
                MenuItem menu = e.Item.Parent;

                menu.ChildItems.Remove(e.Item);
            }
            else
            {
                Menu menu = (Menu)sender;

                menu.Items.Remove(e.Item);
            }               
        }
    }
}

Because the example used the NavigateUrl it is not language specific and works on sites with localized site maps.

Can't subtract offset-naive and offset-aware datetimes

I know some people use Django specifically as an interface to abstract this type of database interaction. Django provides utilities that can be used for this:

from django.utils import timezone
now_aware = timezone.now()

You do need to set up a basic Django settings infrastructure, even if you are just using this type of interface (in settings, you need to include USE_TZ=True to get an aware datetime).

By itself, this is probably nowhere near enough to motivate you to use Django as an interface, but there are many other perks. On the other hand, if you stumbled here because you were mangling your Django app (as I did), then perhaps this helps...

Performing Inserts and Updates with Dapper

Instead of using any 3rd party library for query operations, I would rather suggest writing queries on your own. Because using any other 3rd party packages would take away the main advantage of using dapper i.e. flexibility to write queries.

Now, there is a problem with writing Insert or Update query for the entire object. For this, one can simply create helpers like below:

InsertQueryBuilder:

 public static string InsertQueryBuilder(IEnumerable < string > fields) {


  StringBuilder columns = new StringBuilder();
  StringBuilder values = new StringBuilder();


  foreach(string columnName in fields) {
   columns.Append($ "{columnName}, ");
   values.Append($ "@{columnName}, ");

  }
  string insertQuery = $ "({ columns.ToString().TrimEnd(',', ' ')}) VALUES ({ values.ToString().TrimEnd(',', ' ')}) ";

  return insertQuery;
 }

Now, by simply passing the name of the columns to insert, the whole query will be created automatically, like below:

List < string > columns = new List < string > {
 "UserName",
 "City"
}
//QueryBuilder is the class having the InsertQueryBuilder()
string insertQueryValues = QueryBuilderUtil.InsertQueryBuilder(columns);

string insertQuery = $ "INSERT INTO UserDetails {insertQueryValues} RETURNING UserId";

Guid insertedId = await _connection.ExecuteScalarAsync < Guid > (insertQuery, userObj);

You can also modify the function to return the entire INSERT statement by passing the TableName parameter.

Make sure that the Class property names match with the field names in the database. Then only you can pass the entire obj (like userObj in our case) and values will be mapped automatically.

In the same way, you can have the helper function for UPDATE query as well:

  public static string UpdateQueryBuilder(List < string > fields) {
   StringBuilder updateQueryBuilder = new StringBuilder();

   foreach(string columnName in fields) {
    updateQueryBuilder.AppendFormat("{0}=@{0}, ", columnName);
   }
   return updateQueryBuilder.ToString().TrimEnd(',', ' ');
  }

And use it like:

List < string > columns = new List < string > {
 "UserName",
 "City"
}
//QueryBuilder is the class having the UpdateQueryBuilder()
string updateQueryValues = QueryBuilderUtil.UpdateQueryBuilder(columns);

string updateQuery =  $"UPDATE UserDetails SET {updateQueryValues} WHERE UserId=@UserId";

await _connection.ExecuteAsync(updateQuery, userObj);

Though in these helper functions also, you need to pass the name of the fields you want to insert or update but at least you have full control over the query and can also include different WHERE clauses as and when required.

Through this helper functions, you will save the following lines of code:

For Insert Query:

 $ "INSERT INTO UserDetails (UserName,City) VALUES (@UserName,@City) RETURNING UserId";

For Update Query:

$"UPDATE UserDetails SET UserName=@UserName, City=@City WHERE UserId=@UserId";

There seems to be a difference of few lines of code, but when it comes to performing insert or update operation with a table having more than 10 fields, one can feel the difference.

You can use the nameof operator to pass the field name in the function to avoid typos

Instead of:

List < string > columns = new List < string > {
 "UserName",
 "City"
}

You can write:

List < string > columns = new List < string > {
nameof(UserEntity.UserName),
nameof(UserEntity.City),
}

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

In Tomcat 8.0.44 I did this: create the JNDI on Tomcat's server.xml between the tag "GlobalNamingResources" For example:

_x000D_
_x000D_
<GlobalNamingResources>_x000D_
    <!-- Editable user database that can also be used by_x000D_
         UserDatabaseRealm to authenticate users_x000D_
    -->_x000D_
  <!-- Other previus resouces -->_x000D_
    <Resource auth="Container" driverClassName="org.postgresql.Driver" global="jdbc/your_jndi" _x000D_
    maxActive="100" maxIdle="20" maxWait="1000" minIdle="5" name="jdbc/your_jndi" password="your_password" _x000D_
    type="javax.sql.DataSource" url="jdbc:postgresql://localhost:5432/your_database?user=postgres" username="database_username"/>_x000D_
  </GlobalNamingResources>
_x000D_
_x000D_
_x000D_ In your web application you need a link to that resource (ResourceLink):

project explore

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<Context reloadable="true" >_x000D_
   <ResourceLink name="jdbc/your_jndi"_x000D_
      global="jdbc/your_jndi"_x000D_
      auth="Container"_x000D_
      type="javax.sql.DataSource" />_x000D_
</Context>
_x000D_
_x000D_
_x000D_

So if you're using Hiberte with spring you can tell to him to use the JNDI in your persistence.xml

persistence.xml location

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"_x000D_
 version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">_x000D_
 <persistence-unit name="UNIT_NAME" transaction-type="RESOURCE_LOCAL">_x000D_
  <provider>org.hibernate.ejb.HibernatePersistence</provider>_x000D_
_x000D_
  <properties>_x000D_
   <property name="javax.persistence.jdbc.driver"   value="org.postgresql.Driver" />_x000D_
   <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />_x000D_
   _x000D_
   <!--  <property name="hibernate.jdbc.time_zone" value="UTC"/>-->_x000D_
   <property name="hibernate.hbm2ddl.auto" value="update" />_x000D_
   <property name="hibernate.show_sql" value="false" />_x000D_
   <property name="hibernate.format_sql" value="true"/>     _x000D_
  </properties>_x000D_
 </persistence-unit>_x000D_
</persistence>
_x000D_
_x000D_
_x000D_

So in your spring.xml you can do that:

_x000D_
_x000D_
<bean id="postGresDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">_x000D_
   <property name="jndiName" value="java:comp/env/jdbc/your_jndi" />_x000D_
  </bean>_x000D_
     _x000D_
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">_x000D_
              <property name="persistenceUnitName" value="UNIT_NAME" />_x000D_
              <property name="dataSource" ref="postGresDataSource" />_x000D_
              <property name="jpaVendorAdapter"> _x000D_
                 <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />_x000D_
              </property>_x000D_
        </bean>
_x000D_
_x000D_
_x000D_ Look above that entityManagerFactory bean refers to your UNIT_NAME configured at persistence xml and the bean postGresDataSource has a property that points to your JNDI resource in Tomcat.

_x000D_
_x000D_
<property name="jndiName" value="java:comp/env/jdbc/your_jndi" />
_x000D_
_x000D_
_x000D_

In this example I used spring with xml but you can do this programmaticaly if you prefer.

That's it, I hope helped.

Turning Sonar off for certain code

I recommend you try to suppress specific warnings by using @SuppressWarnings("squid:S2078").

For suppressing multiple warnings you can do it like this @SuppressWarnings({"squid:S2078", "squid:S2076"})

There is also the //NOSONAR comment that tells SonarQube to ignore all errors for a specific line.

Finally if you have the proper rights for the user interface you can issue a flag as a false positive directly from the interface.

The reason why I recommend suppression of specific warnings is that it's a better practice to block a specific issue instead of using //NOSONAR and risk a Sonar issue creeping in your code by accident.

You can read more about this in the FAQ

Edit: 6/30/16 SonarQube is now called SonarLint

In case you are wondering how to find the squid number. Just click on the Sonar message (ex. Remove this method to simply inherit it.) and the Sonar issue will expand.

On the bottom left it will have the squid number (ex. squid:S1185 Maintainability > Understandability)

So then you can suppress it by @SuppressWarnings("squid:S1185")

How to add parameters to an external data query in Excel which can't be displayed graphically?

YES - solution is to save workbook in to XML file (eg. 'XML Spreadsheet 2003') and edit this file as text in notepad! use "SEARCH" function of notepad to find query text and change your data to "?".

save and open in excel, try refresh data and excel will be monit about parameters.

How do I download a binary file over HTTP?

Example 3 in the Ruby's net/http documentation shows how to download a document over HTTP, and to output the file instead of just loading it into memory, substitute puts with a binary write to a file, e.g. as shown in Dejw's answer.

More complex cases are shown further down in the same document.

async at console app in C#?

In most project types, your async "up" and "down" will end at an async void event handler or returning a Task to your framework.

However, Console apps do not support this.

You can either just do a Wait on the returned task:

static void Main()
{
  MainAsync().Wait();
  // or, if you want to avoid exceptions being wrapped into AggregateException:
  //  MainAsync().GetAwaiter().GetResult();
}

static async Task MainAsync()
{
  ...
}

or you can use your own context like the one I wrote:

static void Main()
{
  AsyncContext.Run(() => MainAsync());
}

static async Task MainAsync()
{
  ...
}

More information for async Console apps is on my blog.

Install Visual Studio 2013 on Windows 7

Visual Studio Express for Windows needs Windows 8.1. Having a look at the requirements page you might want to try the Web or Windows Desktop version which are able to run under Windows 7.

Setting an int to Infinity in C++

You can also use INT_MAX:

http://www.cplusplus.com/reference/climits/

it's equivalent to using numeric_limits.

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

After adding dependencies open "Gradle" ('View'->Tool Windows->Gradle) tab and hit "refresh"

example of adding (compile 'io.reactivex:rxjava:1.1.0'):

hit refresh

If Idea still can not resolve dependency, hence it is possibly the dependency is not in mavenCentral() repository and you need add repository where this dependency located into repositories{}

OAuth2 and Google API: access token expiration time?

You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.

However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).

EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:

  1. It is a parameter in the response (expires_in)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.
  2. There is also an API that returns the remaining lifetime of the access_token:

    https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}

    This will return a json array that will contain an expires_in parameter, which is the number of seconds left in the lifetime of the token.

Reset Excel to default borders

In Excel 2016 for Mac, I clicked the Excel menu, then clicked Preferences…

I then clicked the View icon.

whereupon I found a Gridlines Checkbox next to a Color Picker.

Regardless of whether the Gridlines checkbox os checked or not, if you change the color in the Color Picker dropdown menu, your cell borders will become that color. (I believe the change took place after i quit excel and opened the document the next day to continue working on it but I can't accurately remember.)

Changing the color picker back to Automatic will return your cell borders to the default (black) color on-the-fly.

N.B. Because I'm a newbie I cannot insert the screen shots I prepared ahead of time.

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

Similar to Arnav Rao's, but with a different parent:

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="toolbarStyle">@style/MyToolbar</item>
</style>

<style name="MyToolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:background">#ff0000</item>
</style>

With this approach, the appearance of the Toolbar is entirely defined in the app styles, so you don't need to place any styling on each toolbar.

Repair all tables in one go

The command is this:

mysqlcheck -u root -p --auto-repair --check --all-databases

You must supply the password when asked,

or you can run this one but it's not recommended because the password is written in clear text:

mysqlcheck -u root --password=THEPASSWORD --auto-repair --check --all-databases

angularjs make a simple countdown

var timer_seconds_counter = 120;
$scope.countDown = function() {
      timer_seconds_counter--;
      timer_object = $timeout($scope.countDown, 1000);
      $scope.timer = parseInt(timer_seconds_counter / 60) ? parseInt(timer_seconds_counter / 60) : '00';
      if ((timer_seconds_counter % 60) < 10) {
        $scope.timer += ':' + ((timer_seconds_counter % 60) ? '0' + (timer_seconds_counter % 60) : '00');
      } else {
        $scope.timer += ':' + ((timer_seconds_counter % 60) ? (timer_seconds_counter % 60) : '00');
      }
      $scope.timer += ' minutes'
      if (timer_seconds_counter === 0) {
        timer_seconds_counter = 30;
        $timeout.cancel(timer_object);
        $scope.timer = '2:00 minutes';
      }
    }

Android: How to create a Dialog without a title?

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", 
                             "Loading. Please wait...", true);

creates a title less dialog

Shell Script Syntax Error: Unexpected End of File

in my case the issue was in the EOL Conversion. (End Of Line).

i created the file on windows and only after i converted the EOL from windows(CR LF) to unix(LF), everything went well.

I did the conversion with Notepad++ very easily from: Edit -> EOL Conversion -> Unix(LF)

How to terminate process from Python using pid?

I wanted to do the same thing as, but I wanted to do it in the one file.

So the logic would be:

  • if a script with my name is running, kill it, then exit
  • if a script with my name is not running, do stuff

I modified the answer by Bakuriu and came up with this:

from os import getpid
from sys import argv, exit
import psutil  ## pip install psutil

myname = argv[0]
mypid = getpid()
for process in psutil.process_iter():
    if process.pid != mypid:
        for path in process.cmdline():
            if myname in path:
                print "process found"
                process.terminate()
                exit()

## your program starts here...

Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.

I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.

Increment counter with loop

what led me to this page is that I set within a page then the inside of an included page I did the increment

and here is the problem

so to solve such a problem, simply use scope="request" when you declare the variable or the increment

//when you set the variale add scope="request"
<c:set var="nFilters" value="${0}" scope="request"/>
//the increment, it can be happened inside an included page
<c:set var="nFilters" value="${nFilters + 1}"  scope="request" />

hope this saves your time

ENOENT, no such file or directory

I had that issue : use path module

const path = require('path');

and also do not forget to create the uploads directory first period.

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

From back side with Spring Boot I've used custom BasicAuthenticationEntryPoint:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().authorizeRequests()
            ...
            .antMatchers(PUBLIC_AUTH).permitAll()
            .and().httpBasic()
//    https://www.baeldung.com/spring-security-basic-authentication
            .authenticationEntryPoint(authBasicAuthenticationEntryPoint())
            ...

@Bean
public BasicAuthenticationEntryPoint authBasicAuthenticationEntryPoint() {
    return new BasicAuthenticationEntryPoint() {
        {
            setRealmName("pirsApp");
        }

        @Override
        public void commence
                (HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
                throws IOException, ServletException {
            if (request.getRequestURI().equals(PUBLIC_AUTH)) {
                response.sendError(HttpStatus.PRECONDITION_FAILED.value(), "Wrong credentials");
            } else {
                super.commence(request, response, authEx);
            }
        }
    };
}

PHP: Update multiple MySQL fields in single query

Comma separate the values:

UPDATE settings SET postsPerPage = $postsPerPage, style = $style WHERE id = '1'"

Concatenate a list of pandas dataframes together

concat also works nicely with a list comprehension pulled using the "loc" command against an existing dataframe

df = pd.read_csv('./data.csv') # ie; Dataframe pulled from csv file with a "userID" column

review_ids = ['1','2','3'] # ie; ID values to grab from DataFrame

# Gets rows in df where IDs match in the userID column and combines them 

dfa = pd.concat([df.loc[df['userID'] == x] for x in review_ids])

Get generic type of java.util.List

Had the same problem, but I used instanceof instead. Did it this way:

List<Object> listCheck = (List<Object>)(Object) stringList;
    if (!listCheck.isEmpty()) {
       if (listCheck.get(0) instanceof String) {
           System.out.println("List type is String");
       }
       if (listCheck.get(0) instanceof Integer) {
           System.out.println("List type is Integer");
       }
    }
}

This involves using unchecked casts so only do this when you know it is a list, and what type it can be.

jQuery datepicker to prevent past date

Remove the quotes surrounding 0 and it will work.

Working Code Snippet:

_x000D_
_x000D_
// set minDate to 0 for today's date_x000D_
$('#datepicker').datepicker({ minDate: 0 });
_x000D_
body {_x000D_
    font-size: 12px; /* just so that it doesn't default to 16px (which is kinda huge) */_x000D_
}
_x000D_
<!-- load jQuery and jQuery UI -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>_x000D_
_x000D_
<!-- load jQuery UI CSS theme -->_x000D_
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">_x000D_
_x000D_
<!-- the datepicker input -->_x000D_
<input type='text' id='datepicker' placeholder='Select date' />
_x000D_
_x000D_
_x000D_

How to read xml file contents in jQuery and display in html elements?

I think you want like this, DEMO

var xmlDoc = $.parseXML( xml ); 

var $xml = $(xmlDoc);

var $person = $xml.find("person");

$person.each(function(){

    var name = $(this).find('name').text(),
        age = $(this).find('age').text();

    $("#ProfileList" ).append('<li>' +name+ ' - ' +age+ '</li>');

});

C#: Dynamic runtime cast

Alternatively:

public static T Cast<T>(this dynamic obj) where T:class
{
   return obj as T;
}

Module AppRegistry is not registered callable module (calling runApplication)

import { AppRegistry } from 'react-native';

AppRegistry.registerComponent('your app name',  () => point);

What characters do I need to escape in XML documents?

Only < and & are required to be escaped if they are to be treated character data and not markup:

2.4 Character Data and Markup

Creating an index on a table variable

The question is tagged SQL Server 2000 but for the benefit of people developing on the latest version I'll address that first.

SQL Server 2014

In addition to the methods of adding constraint based indexes discussed below SQL Server 2014 also allows non unique indexes to be specified directly with inline syntax on table variable declarations.

Example syntax for that is below.

/*SQL Server 2014+ compatible inline index syntax*/
DECLARE @T TABLE (
C1 INT INDEX IX1 CLUSTERED, /*Single column indexes can be declared next to the column*/
C2 INT INDEX IX2 NONCLUSTERED,
       INDEX IX3 NONCLUSTERED(C1,C2) /*Example composite index*/
);

Filtered indexes and indexes with included columns can not currently be declared with this syntax however SQL Server 2016 relaxes this a bit further. From CTP 3.1 it is now possible to declare filtered indexes for table variables. By RTM it may be the case that included columns are also allowed but the current position is that they "will likely not make it into SQL16 due to resource constraints"

/*SQL Server 2016 allows filtered indexes*/
DECLARE @T TABLE
(
c1 INT NULL INDEX ix UNIQUE WHERE c1 IS NOT NULL /*Unique ignoring nulls*/
)

SQL Server 2000 - 2012

Can I create a index on Name?

Short answer: Yes.

DECLARE @TEMPTABLE TABLE (
  [ID]   [INT] NOT NULL PRIMARY KEY,
  [Name] [NVARCHAR] (255) COLLATE DATABASE_DEFAULT NULL,
  UNIQUE NONCLUSTERED ([Name], [ID]) 
  ) 

A more detailed answer is below.

Traditional tables in SQL Server can either have a clustered index or are structured as heaps.

Clustered indexes can either be declared as unique to disallow duplicate key values or default to non unique. If not unique then SQL Server silently adds a uniqueifier to any duplicate keys to make them unique.

Non clustered indexes can also be explicitly declared as unique. Otherwise for the non unique case SQL Server adds the row locator (clustered index key or RID for a heap) to all index keys (not just duplicates) this again ensures they are unique.

In SQL Server 2000 - 2012 indexes on table variables can only be created implicitly by creating a UNIQUE or PRIMARY KEY constraint. The difference between these constraint types are that the primary key must be on non nullable column(s). The columns participating in a unique constraint may be nullable. (though SQL Server's implementation of unique constraints in the presence of NULLs is not per that specified in the SQL Standard). Also a table can only have one primary key but multiple unique constraints.

Both of these logical constraints are physically implemented with a unique index. If not explicitly specified otherwise the PRIMARY KEY will become the clustered index and unique constraints non clustered but this behavior can be overridden by specifying CLUSTERED or NONCLUSTERED explicitly with the constraint declaration (Example syntax)

DECLARE @T TABLE
(
A INT NULL UNIQUE CLUSTERED,
B INT NOT NULL PRIMARY KEY NONCLUSTERED
)

As a result of the above the following indexes can be implicitly created on table variables in SQL Server 2000 - 2012.

+-------------------------------------+-------------------------------------+
|             Index Type              | Can be created on a table variable? |
+-------------------------------------+-------------------------------------+
| Unique Clustered Index              | Yes                                 |
| Nonunique Clustered Index           |                                     |
| Unique NCI on a heap                | Yes                                 |
| Non Unique NCI on a heap            |                                     |
| Unique NCI on a clustered index     | Yes                                 |
| Non Unique NCI on a clustered index | Yes                                 |
+-------------------------------------+-------------------------------------+

The last one requires a bit of explanation. In the table variable definition at the beginning of this answer the non unique non clustered index on Name is simulated by a unique index on Name,Id (recall that SQL Server would silently add the clustered index key to the non unique NCI key anyway).

A non unique clustered index can also be achieved by manually adding an IDENTITY column to act as a uniqueifier.

DECLARE @T TABLE
(
A INT NULL,
B INT NULL,
C INT NULL,
Uniqueifier INT NOT NULL IDENTITY(1,1),
UNIQUE CLUSTERED (A,Uniqueifier)
)

But this is not an accurate simulation of how a non unique clustered index would normally actually be implemented in SQL Server as this adds the "Uniqueifier" to all rows. Not just those that require it.

Jquery - How to get the style display attribute "none / block"

this is the correct answer

$('#theid').css('display') == 'none'

You can also use following line to find if it is display block or none

$('.deal_details').is(':visible')

How do I add a simple jQuery script to WordPress?

After much searching, I finally found something that works with the latest WordPress. Here are the steps to follow:

  1. Find your theme's directory, create a folder in the directory for your custom js (custom_js in this example).
  2. Put your custom jQuery in a .js file in this directory (jquery_test.js in this example).
  3. Make sure your custom jQuery .js looks like this:

    (function($) {
    $(document).ready(function() {
    $('.your-class').addClass('do-my-bidding');
    })
    })(jQuery);
    
  4. Go to the theme's directory, open up functions.php

  5. Add some code near the top that looks like this:

    //this goes in functions.php near the top
    function my_scripts_method() {
    // register your script location, dependencies and version
       wp_register_script('custom_script',
       get_template_directory_uri() . '/custom_js/jquery_test.js',
       array('jquery'),
       '1.0' );
     // enqueue the script
      wp_enqueue_script('custom_script');
      }
    add_action('wp_enqueue_scripts', 'my_scripts_method');
    
  6. Check out your site to make sure it works!

JUnit Eclipse Plugin?

You should be able to add the Java Development Tools by selecting 'Help' -> 'Install New Software', there you select the 'Juno' update site, then 'Programming Languages' -> 'Eclipse Java Development Tools'.

After that, you will be able to run your JUnit tests with 'Right Click' -> 'Run as' -> 'JUnit test'.

How do I grep for all non-ASCII characters?

Instead of making assumptions about the byte range of non-ASCII characters, as most of the above solutions do, it's slightly better IMO to be explicit about the actual byte range of ASCII characters instead.

So the first solution for instance would become:

grep --color='auto' -P -n '[^\x00-\x7F]' file.xml

(which basically greps for any character outside of the hexadecimal ASCII range: from \x00 up to \x7F)

On Mountain Lion that won't work (due to the lack of PCRE support in BSD grep), but with pcre installed via Homebrew, the following will work just as well:

pcregrep --color='auto' -n '[^\x00-\x7F]' file.xml

Any pros or cons that anyone can think off?

Getting first and last day of the current month

Try this code it is already built in c#

int lastDay = DateTime.DaysInMonth (2014, 2);

and the first day is always 1.

Good Luck!

Angular - Can't make ng-repeat orderBy work

The orderBy only works with Arrays -- See http://docs.angularjs.org/api/ng.filter:orderBy

Also a great filter to use for Objects instead of Arrays @ Angularjs OrderBy on ng-repeat doesn't work

if var == False

Python uses not instead of ! for negation.

Try

if not var: 
    print "learnt stuff"

instead

Instantiating a generic type

You basically have two choices:

1.Require an instance:

public Navigation(T t) {     this("", "", t); } 

2.Require a class instance:

public Navigation(Class<T> c) {     this("", "", c.newInstance()); } 

You could use a factory pattern, but ultimately you'll face this same issue, but just push it elsewhere in the code.

Get the current date and time

DateTimePicker1.value = Format(Date.Now)

The static keyword and its various uses in C++

I'm not a C programmer so I can't give you information on the uses of static in a C program properly, but when it comes to Object Oriented programming static basically declares a variable, or a function or a class to be the same throughout the life of the program. Take for example.

class A
{
public:
    A();
    ~A();
    void somePublicMethod();
private:
    void somePrivateMethod();
};

When you instantiate this class in your Main you do something like this.

int main()
{
   A a1;
   //do something on a1
   A a2;
   //do something on a2
}

These two class instances are completely different from each other and operate independently from one another. But if you were to recreate the class A like this.

class A
{
public:
    A();
    ~A();
    void somePublicMethod();
    static int x;
private:
    void somePrivateMethod();
};

Lets go back to the main again.

int main()
{
   A a1;
   a1.x = 1;
   //do something on a1
   A a2;
   a2.x++;
   //do something on a2
}

Then a1 and a2 would share the same copy of int x whereby any operations on x in a1 would directly influence the operations of x in a2. So if I was to do this

int main()
{
   A a1;
   a1.x = 1;
   //do something on a1
   cout << a1.x << endl; //this would be 1
   A a2;
   a2.x++;
   cout << a2.x << endl; //this would be 2 
   //do something on a2
}

Both instances of the class A share static variables and functions. Hope this answers your question. My limited knowledge of C allows me to say that defining a function or variable as static means it is only visible to the file that the function or variable is defined as static in. But this would be better answered by a C guy and not me. C++ allows both C and C++ ways of declaring your variables as static because its completely backwards compatible with C.

How to install PyQt5 on Windows?

I found a partial solution...

Steps to install pyQt5 (with VS 2012) on Windows:

1) Install the binary file Qt 5.0.2 for Windows 64-bit (VS 2012, 500 MB) from here.

2) Get sip-4.14.7 (development snapshot) from here.

3) Extract the file and open the Developer Command Prompt for VS2012.

4) Execute these commands (in sip folder):

python configure.py
nmake
nmake install

5) Get the pyQt5 from here.

6) Extract the file and open the VS2012 x64 Native Tools Command Prompt.

7) Execute these commands:

python configure.py

UPDATE: When execute these commands below is not working:

nmake
nmake install

Solution: I will try use pyQt4 with Qt5... because pyQt5 is in development and doesn't have support/documentation yet.

Trying to add adb to PATH variable OSX

enter image description here

2nd solution is explained below. But when i close the terminal the change which i made in path variable gets lost. Thus i prefer the first way!

enter image description here

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

The code above exports data without the heading columns which is weird. Here's how to do it. You have to merge the two files later though using text a editor.

SELECT column_name FROM information_schema.columns WHERE table_schema = 'my_app_db' AND table_name = 'customers' INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 5.6/Uploads/customers_heading_cols.csv' FIELDS TERMINATED BY '' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY ',';

Initialize a string in C to empty string

To achieve this you can use:

strcpy(string, "");

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

Can I use Objective-C blocks as properties?

Here's an example of how you would accomplish such a task:

#import <Foundation/Foundation.h>
typedef int (^IntBlock)();

@interface myobj : NSObject
{
    IntBlock compare;
}

@property(readwrite, copy) IntBlock compare;

@end

@implementation myobj

@synthesize compare;

- (void)dealloc 
{
   // need to release the block since the property was declared copy. (for heap
   // allocated blocks this prevents a potential leak, for compiler-optimized 
   // stack blocks it is a no-op)
   // Note that for ARC, this is unnecessary, as with all properties, the memory management is handled for you.
   [compare release];
   [super dealloc];
}
@end

int main () {
    @autoreleasepool {
        myobj *ob = [[myobj alloc] init];
        ob.compare = ^
        {
            return rand();
        };
        NSLog(@"%i", ob.compare());
        // if not ARC
        [ob release];
    }

    return 0;
}

Now, the only thing that would need to change if you needed to change the type of compare would be the typedef int (^IntBlock)(). If you need to pass two objects to it, change it to this: typedef int (^IntBlock)(id, id), and change your block to:

^ (id obj1, id obj2)
{
    return rand();
};

I hope this helps.

EDIT March 12, 2012:

For ARC, there are no specific changes required, as ARC will manage the blocks for you as long as they are defined as copy. You do not need to set the property to nil in your destructor, either.

For more reading, please check out this document: http://clang.llvm.org/docs/AutomaticReferenceCounting.html

How to get some values from a JSON string in C#?

Your strings are JSON formatted, so you will need to parse it into a object. For that you can use JSON.NET.

Here is an example on how to parse a JSON string into a dynamic object:

string source = "{\r\n   \"id\": \"100000280905615\", \r\n \"name\": \"Jerard Jones\",  \r\n   \"first_name\": \"Jerard\", \r\n   \"last_name\": \"Jones\", \r\n   \"link\": \"https://www.facebook.com/Jerard.Jones\", \r\n   \"username\": \"Jerard.Jones\", \r\n   \"gender\": \"female\", \r\n   \"locale\": \"en_US\"\r\n}";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.id);
Console.WriteLine(data.first_name);
Console.WriteLine(data.last_name);
Console.WriteLine(data.gender);
Console.WriteLine(data.locale);

Happy coding!

Catching exceptions from Guzzle

To catch Guzzle errors you can do something like this:

try {
    $response = $client->get('/not_found.xml')->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
    echo 'Uh oh! ' . $e->getMessage();
}

... but, to be able to "log" or "resend" your request try something like this:

// Add custom error handling to any request created by this client
$client->getEventDispatcher()->addListener(
    'request.error', 
    function(Event $event) {

        //write log here ...

        if ($event['response']->getStatusCode() == 401) {

            // create new token and resend your request...
            $newRequest = $event['request']->clone();
            $newRequest->setHeader('X-Auth-Header', MyApplication::getNewAuthToken());
            $newResponse = $newRequest->send();

            // Set the response object of the request without firing more events
            $event['response'] = $newResponse;

            // You can also change the response and fire the normal chain of
            // events by calling $event['request']->setResponse($newResponse);

            // Stop other events from firing when you override 401 responses
            $event->stopPropagation();
        }

});

... or if you want to "stop event propagation" you can overridde event listener (with a higher priority than -255) and simply stop event propagation.

$client->getEventDispatcher()->addListener('request.error', function(Event $event) {
if ($event['response']->getStatusCode() != 200) {
        // Stop other events from firing when you get stytus-code != 200
        $event->stopPropagation();
    }
});

thats a good idea to prevent guzzle errors like:

request.CRITICAL: Uncaught PHP Exception Guzzle\Http\Exception\ClientErrorResponseException: "Client error response

in your application.

How can I change the remote/target repository URL on Windows?

Take a look in .git/config and make the changes you need.

Alternatively you could use

git remote rm [name of the url you sets on adding]

and

git remote add [name] [URL]

Or just

git remote set-url [URL]

Before you do anything wrong, double check with

git help remote

Resolve host name to an ip address

Windows XP has the Windows Firewall which can interfere with network traffic if not configured properly. You can turn off the Windows Firewall, if you have administrator privileges, by accessing the Windows Firewall applet through the Control Panel. If your application works with the Windows Firewall turned off then the problem is probably due to the settings of the firewall.

We have an application which runs on multiple PCs communicating using UDP/IP and we have been doing experiments so that the application can run on a PC with a user who does not have administrator privileges. In order for our application to communicate between multiple PCs we have had to use an administrator account to modify the Windows Firewall settings.

In our application, one PC is designated as the server and the others are clients in a server/client group and there may be several groups on the same subnet.

The first change was to use the functionality of the Exceptions tab of the Windows Firewall applet to create an exception for the port that we use for communication.

We are using host name lookup so that the clients can locate their assigned server by using the computer name which is composed of a mnemonic prefix with a dash followed by an assigned terminal number (for instance SERVER100-1). This allows several servers with their assigned clients to coexist on the same subnet. The client uses its prefix to generate the computer name for the assigned server and to then use host name lookup to discover the IP address of the assigned server.

What we found is that the host name lookup using the computer name (assigned through the Computer Name tab of the System Properties dialog) would not work unless the server PC's Windows Firewall had the File and Printer Sharing Service port enabled.

So we had to make two changes: (1) setup an exception for the port we used for communication and (2) enable File and Printer Service in the Exceptions tab to allow for the host name lookup.

** EDIT **

You may also find this Microsoft Knowledge Base article on helpful on Windows XP networking.

And see this article on NETBIOS name resolution in Windows.

HTML / CSS table with GRIDLINES

<table border="1"></table>

should do the trick.

How to consume a webApi from asp.net Web API to store result in database?

In this tutorial is explained how to consume a web api with C#, in this example a console application is used, but you can also use another web api to consume of course.

http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

You should have a look at the HttpClient

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost/yourwebapi");

Make sure your requests ask for the response in JSON using the Accept header like this:

client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

Now comes the part that differs from the tutorial, make sure you have the same objects as the other WEB API, if not, then you have to map the objects to your own objects. ASP.NET will convert the JSON you receive to the object you want it to be.

HttpResponseMessage response = client.GetAsync("api/yourcustomobjects").Result;
if (response.IsSuccessStatusCode)
{
    var yourcustomobjects = response.Content.ReadAsAsync<IEnumerable<YourCustomObject>>().Result;
    foreach (var x in yourcustomobjects)
    {
        //Call your store method and pass in your own object
        SaveCustomObjectToDB(x);
    }
}
else
{
    //Something has gone wrong, handle it here
}

please note that I use .Result for the case of the example. You should consider using the async await pattern here.

Difference between javacore, thread dump and heap dump in Websphere

Thread dumps are javacore show snapshot of threads running in JVM, it is useful to debug hang issues, it will provide info about java level dead locks and also IBm version of javacores provides much more useful information, such as heap usage, CPU usage of each thread and overall heap usage along with number of classes laded by the JVM.

Heapdumps, provides information about Java heap usage by an JVM, which can be used to debug memory leaks. Heapdumps are generated by IBM JVMs when a JVM is runs into outofmemoryerror, Heapdumps are only for heap leaks in java, native out of memory error may result system dumps usually with an "GPF" General protection Fault.

How to view log output using docker-compose run?

  1. use the command to start containers in detached mode: docker-compose up -d
  2. to view the containers use: docker ps
  3. to view logs for a container: docker logs <containerid>

Vue.js img src concatenate variable and text

if you handel this from dataBase try :

<img :src="baseUrl + 'path/path' + obj.key +'.png'">

How to reverse apply a stash?

How to reverse apply a stash?

Apart from what others have mentioned, easiest way is first do

git reset HEAD

and then checkout all local changes

git checkout . 

Download and save PDF file with Python requests module

In Python 3, I find pathlib is the easiest way to do this. Request's response.content marries up nicely with pathlib's write_bytes.

from pathlib import Path
import requests
filename = Path('metadata.pdf')
url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
response = requests.get(url)
filename.write_bytes(response.content)

Git Pull is Not Possible, Unmerged Files

Ryan Stewart's answer was almost there. In the case where you actually don't want to delete your local changes, there's a workflow you can use to merge:

  • Run git status. It will give you a list of unmerged files.
  • Merge them (by hand, etc.)
  • Run git commit

Git will commit just the merges into a new commit. (In my case, I had additional added files on disk, which weren't lumped into that commit.)

Git then considers the merge successful and allows you to move forward.

Using Eloquent ORM in Laravel to perform search of database using LIKE

FYI, the list of operators (containing like and all others) is in code:

/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php

protected $operators = array(
    '=', '<', '>', '<=', '>=', '<>', '!=',
    'like', 'not like', 'between', 'ilike',
    '&', '|', '^', '<<', '>>',
    'rlike', 'regexp', 'not regexp',
);

disclaimer:

Joel Larson's answer is correct. Got my upvote.

I'm hoping this answer sheds more light on what's available via the Eloquent ORM (points people in the right direct). Whilst a link to documentation would be far better, that link has proven itself elusive.

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is guaranteed to be a unsigned integer that is 16 bits large

unsigned short int is guaranteed to be a unsigned short integer, where short integer is defined by the compiler (and potentially compiler flags) you are currently using. For most compilers for x86 hardware a short integer is 16 bits large.

Also note that per the ANSI C standard only the minimum size of 16 bits is defined, the maximum size is up to the developer of the compiler

Minimum Type Limits

Any compiler conforming to the Standard must also respect the following limits with respect to the range of values any particular type may accept. Note that these are lower limits: an implementation is free to exceed any or all of these. Note also that the minimum range for a char is dependent on whether or not a char is considered to be signed or unsigned.

Type Minimum Range

signed char     -127 to +127
unsigned char      0 to 255
short int     -32767 to +32767
unsigned short int 0 to 65535

How do I set the default locale in the JVM?

In the answers here, up to now, we find two ways of changing the JRE locale setting:

  • Programatically, using Locale.setDefault() (which, in my case, was the solution, since I didn't want to require any action of the user):

    Locale.setDefault(new Locale("pt", "BR"));
    
  • Via arguments to the JVM:

    java -jar anApp.jar -Duser.language=pt-BR
    

But, just as reference, I want to note that, on Windows, there is one more way of changing the locale used by the JRE, as documented here: changing the system-wide language.

Note: You must be logged in with an account that has Administrative Privileges.

  1. Click Start > Control Panel.

  2. Windows 7 and Vista: Click Clock, Language and Region > Region and Language.

    Windows XP: Double click the Regional and Language Options icon.

    The Regional and Language Options dialog box appears.

  3. Windows 7: Click the Administrative tab.

    Windows XP and Vista: Click the Advanced tab.

    (If there is no Advanced tab, then you are not logged in with administrative privileges.)

  4. Under the Language for non-Unicode programs section, select the desired language from the drop down menu.

  5. Click OK.

    The system displays a dialog box asking whether to use existing files or to install from the operating system CD. Ensure that you have the CD ready.

  6. Follow the guided instructions to install the files.

  7. Restart the computer after the installation is complete.

Certainly on Linux the JRE also uses the system settings to determine which locale to use, but the instructions to set the system-wide language change from distro to distro.

Javascript checkbox onChange

The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.

const checkbox = $("#checkboxId");

checkbox.change(function(event) {
    var checkbox = event.target;
    if (checkbox.checked) {
        //Checkbox has been checked
    } else {
        //Checkbox has been unchecked
    }
});

Remove a CLASS for all child elements

You can also do like this :

  $("#table-filters li").parent().find('li').removeClass("active");

How can I replace the deprecated set_magic_quotes_runtime in php?

In PHP 7 we can use:

ini_set('magic_quotes_runtime', 0);

instead of set_magic_quotes_runtime(0);

Parse json string using JSON.NET

If your keys are dynamic I would suggest deserializing directly into a DataTable:

    class SampleData
    {
        [JsonProperty(PropertyName = "items")]
        public System.Data.DataTable Items { get; set; }
    }

    public void DerializeTable()
    {
        const string json = @"{items:["
            + @"{""Name"":""AAA"",""Age"":""22"",""Job"":""PPP""},"
            + @"{""Name"":""BBB"",""Age"":""25"",""Job"":""QQQ""},"
            + @"{""Name"":""CCC"",""Age"":""38"",""Job"":""RRR""}]}";
        var sampleData = JsonConvert.DeserializeObject<SampleData>(json);
        var table = sampleData.Items;

        // write tab delimited table without knowing column names
        var line = string.Empty;
        foreach (DataColumn column in table.Columns)            
            line += column.ColumnName + "\t";                       
        Console.WriteLine(line);

        foreach (DataRow row in table.Rows)
        {
            line = string.Empty;
            foreach (DataColumn column in table.Columns)                
                line += row[column] + "\t";                                   
            Console.WriteLine(line);
        }

        // Name   Age   Job    
        // AAA    22    PPP    
        // BBB    25    QQQ    
        // CCC    38    RRR    
    }

You can determine the DataTable column names and types dynamically once deserialized.

Unable to locate tools.jar

tools.jar comes with JDK, but what happens in your case it looks for it within /Java/jre6. Change JAVA_HOME env var to one of your JDK home.

Do we need to execute Commit statement after Update in SQL Server

The SQL Server Management Studio has implicit commit turned on, so all statements that are executed are implicitly commited.

This might be a scary thing if you come from an Oracle background where the default is to not have commands commited automatically, but it's not that much of a problem.

If you still want to use ad-hoc transactions, you can always execute

BEGIN TRANSACTION

within SSMS, and than the system waits for you to commit the data.

If you want to replicate the Oracle behaviour, and start an implicit transaction, whenever some DML/DDL is issued, you can set the SET IMPLICIT_TRANSACTIONS checkbox in

Tools -> Options -> Query Execution -> SQL Server -> ANSI

How can I obfuscate (protect) JavaScript?

I would suggest first minify with something like YUI Compressor, and then convert all string and numbers to HEX Values using something like http://www.javascriptobfuscator.com/

With this, the code would be rendered near impossible to understand and I think at this Stage it will take more time for a Hacker to re-enact your code than actually if he re-wrote from scratch. Rewriting and Cloning is what you cant actually stop. After all we are free-people !

dynamic_cast and static_cast in C++

A dynamic_cast performs a type checking using RTTI. If it fails it'll throw you an exception (if you gave it a reference) or NULL if you gave it a pointer.

unique object identifier in javascript

Actually, you don't need to modify the object prototype and add a function there. The following should work well for your purpose.

var __next_objid=1;
function objectId(obj) {
    if (obj==null) return null;
    if (obj.__obj_id==null) obj.__obj_id=__next_objid++;
    return obj.__obj_id;
}

how to move elasticsearch data from one server to another

I tried on ubuntu to move data from ELK 2.4.3 to ELK 5.1.1

Following are the steps

$ sudo apt-get update

$ sudo apt-get install -y python-software-properties python g++ make

$ sudo add-apt-repository ppa:chris-lea/node.js

$ sudo apt-get update

$ sudo apt-get install npm

$ sudo apt-get install nodejs

$ npm install colors

$ npm install nomnom

$ npm install elasticdump

in home directory goto

$ cd node_modules/elasticdump/

execute the command

If you need basic http auth, you can use it like this:

--input=http://name:password@localhost:9200/my_index

Copy an index from production:

$ ./bin/elasticdump --input="http://Source:9200/Sourceindex" --output="http://username:password@Destination:9200/Destination_index"  --type=data

comparing two strings in ruby

From what you printed, it seems var2 is an array containing one string. Or actually, it appears to hold the result of running .inspect on an array containing one string. It would be helpful to show how you are initializing them.

irb(main):005:0* v1 = "test"
=> "test"
irb(main):006:0> v2 = ["test"]
=> ["test"]
irb(main):007:0> v3 = v2.inspect
=> "[\"test\"]"
irb(main):008:0> puts v1,v2,v3
test
test
["test"]

Open Source Alternatives to Reflector?

Updated 13th December 2011

The following open source tools are available:

Jquery, Clear / Empty all contents of tbody element?

Without use ID (<tbody id="tbodyid">) , it is a great way to cope with this issue

$('#table1').find("tr:gt(0)").remove();

PS:To remove specific row number as following example

$('#table1 tr').eq(1).remove();

or

$('#tr:nth-child(2)').remove();

IIS - can't access page by ip address instead of localhost

Try with disabling Windows Firewall, it worked for me, but in my case, I was able to access IIS through 127.0.0.1

Reverse / invert a dictionary mapping

Assuming that the values in the dict are unique:

dict((v, k) for k, v in my_map.iteritems())