Programs & Examples On #Alternate access mappings

Using Spring MVC Test to unit test multipart POST request

If you are using Spring4/SpringBoot 1.x, then it's worth mentioning that you can add "text" (json) parts as well . This can be done via MockMvcRequestBuilders.fileUpload().file(MockMultipartFile file) (which is needed as method .multipart() is not available in this version):

@Test
public void test() throws Exception {

   mockMvc.perform( 
       MockMvcRequestBuilders.fileUpload("/files")
         // file-part
         .file(makeMultipartFile( "file-part" "some/path/to/file.bin", "application/octet-stream"))
        // text part
         .file(makeMultipartTextPart("json-part", "{ \"foo\" : \"bar\" }", "application/json"))
       .andExpect(status().isOk())));

   }

   private MockMultipartFile(String requestPartName, String filename, 
       String contentType, String pathOnClassPath) {

       return new MockMultipartFile(requestPartName, filename, 
          contentType, readResourceFile(pathOnClasspath);
   }

   // make text-part using MockMultipartFile
   private MockMultipartFile makeMultipartTextPart(String requestPartName, 
       String value, String contentType) throws Exception {

       return new MockMultipartFile(requestPartName, "", contentType,
               value.getBytes(Charset.forName("UTF-8")));   
   }


   private byte[] readResourceFile(String pathOnClassPath) throws Exception {
      return Files.readAllBytes(Paths.get(Thread.currentThread().getContextClassLoader()
         .getResource(pathOnClassPath).toUri()));
   }

}

convert float into varchar in SQL server without scientific notation

Below is an example where we can convert float value without any scientific notation.

DECLARE @Floater AS FLOAT = 100000003.141592653

SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
      ,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
      ,STR(@Floater)
      ,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)

SET @Floater = @Floater * 10

SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
      ,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
      ,STR(@Floater)
      ,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)

SET @Floater = @Floater * 100

SELECT CAST(ROUND(@Floater, 0) AS VARCHAR(30))
      ,CONVERT(VARCHAR(100), ROUND(@Floater, 0))
      ,STR(@Floater)
      ,LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)

SELECT LEFT(FORMAT(@Floater, ''), CHARINDEX('.', FORMAT(@Floater, '')) - 1)
      ,FORMAT(@Floater, '')

In the above example, we can see that the format function is useful for us. FORMAT() function returns always nvarchar.

#1062 - Duplicate entry for key 'PRIMARY'

The DB I was importing had a conflict during the import due to the presence of a column both autoincrement and primary key.

The problem was that in the .sql file the table was chopped into multiple "INSERT INTO" and during the import these queries were executed all together.

MY SOLUTION was to deselect the "Run multiple queries in each execution" on Navicat and it worked perfectly

Resize external website content to fit iFrame width

Tip for 1 website resizing the height. But you can change to 2 websites.

Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.

  • local (iframe) page: just insert a code snippet
  • remote (external) page: you need a "body onload" and a "div" that holds all contents. And body needs to be styled to "margin:0"

Local:

<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>

<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
  if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>

You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).

Remote:

You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).

<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>

So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.

The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".

Hope this helps. Sorry for my english.

Constants in Kotlin -- what's a recommended way to create them?

For primitives and Strings:

/** The empty String. */
const val EMPTY_STRING = ""

For other cases:

/** The empty array of Strings. */
@JvmField val EMPTY_STRING_ARRAY = arrayOfNulls<String>(0)

Example:

/*
 * Copyright 2018 Vorlonsoft LLC
 *
 * Licensed under The MIT License (MIT)
 */

package com.vorlonsoft.android.rate

import com.vorlonsoft.android.rate.Constants.Utils.Companion.UTILITY_CLASS_MESSAGE

/**
 * Constants Class - the constants class of the AndroidRate library.
 *
 * @constructor Constants is a utility class and it can't be instantiated.
 * @since       1.1.8
 * @version     1.2.1
 * @author      Alexander Savin
 */
internal class Constants private constructor() {
    /** Constants Class initializer block. */
    init {
        throw UnsupportedOperationException("Constants$UTILITY_CLASS_MESSAGE")
    }

    /**
     * Constants.Date Class - the date constants class of the AndroidRate library.
     *
     * @constructor Constants.Date is a utility class and it can't be instantiated.
     * @since       1.1.8
     * @version     1.2.1
     * @author      Alexander Savin
     */
    internal class Date private constructor() {
        /** Constants.Date Class initializer block. */
        init {
            throw UnsupportedOperationException("Constants.Date$UTILITY_CLASS_MESSAGE")
        }

        /** The singleton contains date constants. */
        companion object {
            /** The time unit representing one year in days. */
            const val YEAR_IN_DAYS = 365.toShort()
        }
    }

    /**
     * Constants.Utils Class - the utils constants class of the AndroidRate library.
     *
     * @constructor Constants.Utils is a utility class and it can't be instantiated.
     * @since       1.1.8
     * @version     1.2.1
     * @author      Alexander Savin
     */
    internal class Utils private constructor() {
        /** Constants.Utils Class initializer block. */
        init {
            throw UnsupportedOperationException("Constants.Utils$UTILITY_CLASS_MESSAGE")
        }

        /** The singleton contains utils constants. */
        companion object {
            /** The empty String. */
            const val EMPTY_STRING = ""
            /** The empty array of Strings. */
            @JvmField val EMPTY_STRING_ARRAY = arrayOfNulls<String>(0)
            /** The part 2 of a utility class unsupported operation exception message. */
            const val UTILITY_CLASS_MESSAGE = " is a utility class and it can't be instantiated!"
        }
    }
}

How to delete file from public folder in laravel 5.1

Using PHP unlink() function, will have the file deleted

$path = public_path()."/uploads/".$from_db->image_name;
unlink($path);

The above will delete an image returned by $from_db->image_name located at public/uploads folder

How to make a variadic macro (variable number of arguments)

__VA_ARGS__ is the standard way to do it. Don't use compiler-specific hacks if you don't have to.

I'm really annoyed that I can't comment on the original post. In any case, C++ is not a superset of C. It is really silly to compile your C code with a C++ compiler. Don't do what Donny Don't does.

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Basically, what this error is saying is that if you are going to use the GROUP BY clause, then your result is going to be a relation/table with a row for each group, so in your SELECT statement you can only "select" the column that you are grouping by and use aggregate functions on that column because the other columns will not appear in the resulting table.

How to execute a remote command over ssh with arguments?

Reviving an old thread, but this pretty clean approach was not listed.

function mycommand() {
    ssh [email protected] <<+
    cd testdir;./test.sh "$1"
+
}

how to check if string value is in the Enum list?

You can use the TryParse method that returns true if it successful:

Age age;

if(Enum.TryParse<Age>("myString", out age))
{
   //Here you can use age
}

How to refresh activity after changing language (Locale) inside application

The way we have done it was using Broadcasts:

  1. Send the broadcast every time the user changes language
  2. Register the broadcast receiver in the AppActivity.onCreate() and unregister in AppActivity.onDestroy()
  3. In BroadcastReceiver.onReceive() just restart the activity.

AppActivity is the parent activity which all other activities subclass.


Below is the snippet from my code, not tested outside the project, but should give you a nice idea.

When the user changes the language

sendBroadcast(new Intent("Language.changed"));

And in the parent activity

public class AppActivity extends Activity {

    /**
     * The receiver that will handle the change of the language.
     */
    private BroadcastReceiver mLangaugeChangedReceiver;

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

        // ...
        // Other code here
        // ...

        // Define receiver
        mLangaugeChangedReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(final Context context, final Intent intent) {
                startActivity(getIntent());
                finish();
            }
        };

        // Register receiver
        registerReceiver(mLangaugeChangedReceiver, new IntentFilter("Language.changed"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // ...
        // Other cleanup code here
        // ...

        // Unregister receiver
        if (mLangaugeChangedReceiver != null) {
            try {
                unregisterReceiver(mLangaugeChangedReceiver);
                mLangaugeChangedReceiver = null;
            } catch (final Exception e) {}
        }
    }
}

This will also refresh the activity which changed the language (if it subclasses the above activity).

This will make you lose any data, but if it is important you should already have taken care of this using Actvity.onSaveInstanceState() and Actvity.onRestoreInstanceState() (or similar).

Let me know your thoughts about this.

Cheers!

Looping through a hash, or using an array in PowerShell

A short traverse could be given too using the sub-expression operator $( ), which returns the result of one or more statements.

$hash = @{ a = 1; b = 2; c = 3}

forEach($y in $hash.Keys){
    Write-Host "$y -> $($hash[$y])"
}

Result:

a -> 1
b -> 2
c -> 3

Computed / calculated / virtual / derived columns in PostgreSQL

A lightweight solution with Check constraint:

CREATE TABLE example (
    discriminator INTEGER DEFAULT 0 NOT NULL CHECK (discriminator = 0)
);

Rename a table in MySQL

Table name change

RENAME TABLE old_table_name TO new_table_name;

How to POST a FORM from HTML to ASPX page

The Request.Form.Keys collection will be empty if none of your html inputs have NAMEs. It's easy to forget to put them there after you've been doing .NET for a while. Just name them and you'll be good to go.

Redirect to Action by parameter mvc

This should work!

[HttpPost]
public ActionResult RedirectToImages(int id)
{
    return RedirectToAction("Index", "ProductImageManeger", new  { id = id });
}

[HttpGet]
public ViewResult Index(int id)
{
    return View(_db.ProductImages.Where(rs => rs.ProductId == id).ToList());
}

Notice that you don't have to pass the name of view if you are returning the same view as implemented by the action.

Your view should inherit the model as this:

@model <Your class name>

You can then access your model in view as:

@Model.<property_name>

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

Bootstrap 3 truncate long text inside rows of a table in a responsive way

I'm using bootstrap.
I used css parameters.

.table {
  table-layout:fixed;
}

.table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

and bootstrap grid system parameters, like this.

<th class="col-sm-2">Name</th>

<td class="col-sm-2">hoge</td>

Show Image View from file path?

How To Show Images From Folder path in Android

Very First: Make Sure You Have Add Permissions into Mainfest file:

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

:Make a Class MyGallery

public class MyGallery extends Activity {


    private GridView gridView;
    private String _location;

    private String newFolder = "/IslamicGif/";
    private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    private AdView mAdView;
    private ArrayList<Bitmap> photo = new ArrayList<Bitmap>();
    public static String[] imageFileList;
    TextView gallerytxt;

    public static ImageAdapter imageAdapter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.mygallery);
        /*if (MenuClass.mInterstitialAd.isLoaded()) {
            MenuClass.mInterstitialAd.show();
        }*/

        gallerytxt = (TextView) findViewById(R.id.gallerytxt);
        /*gallerytxt.setTextSize(20);
        int[] color = {Color.YELLOW,Color.WHITE};
        float[] position = {0, 1};
        Shader.TileMode tile_mode0= Shader.TileMode.REPEAT; // or TileMode.REPEAT;
        LinearGradient lin_grad0 = new LinearGradient(0, 0, 0, 200,color,position, tile_mode0);
        Shader shader_gradient0 = lin_grad0;
        gallerytxt.getPaint().setShader(shader_gradient0);*/
        ImageButton btn_back = (ImageButton) findViewById(R.id.btn_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyGallery.this.finish();
            }
        });


        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mAdView.loadAd(adRequest);
        gridView = (GridView) findViewById(R.id.gridView);

        new MyGalleryAsy().execute();

        gridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(MyGallery.this, ImageDetail.class);
                intent.putExtra("ImgUrl", imageFileList[pos]);

                //Toast.makeText(MyGallery.this,"image detail"+pos,Toast.LENGTH_LONG).show();
                startActivity(intent);
            }
        });


    }

    protected void onStart() {
        super.onStart();
        if (ImageDetail.deleted) {
            photo = new ArrayList<Bitmap>();
            new MyGalleryAsy().execute();
            ImageDetail.deleted = false;
        }

    }

    public class MyGalleryAsy extends AsyncTask<Void, Void, Void> {
        private ProgressDialog dialog;
        Bitmap mBitmap;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(MyGallery.this, "", "Loading ...", true);
            dialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            readImage();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            dialog.dismiss();
            DisplayMetrics displayMatrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMatrics);
            int screenWidth = displayMatrics.widthPixels / 3;

            if (photo.size() > 0) {
                imageAdapter = new ImageAdapter(MyGallery.this, screenWidth);
                gridView.setAdapter(imageAdapter);
            }

        }

    }


    private void readImage() {
        // TODO Auto-generated method stub


        try {
            if (isSdPresent()) {
                _location = extStorageDirectory + newFolder;
            } else
                _location = getFilesDir() + newFolder;
            File file1 = new File(_location);

            if (file1.isDirectory()) { // sdCard == true
                imageFileList = file1.list();
                if (imageFileList != null) {
                    for (int i = 0; i < imageFileList.length; i++) {
                        try {
                            photo.add(BitmapFactory.decodeFile(_location + imageFileList[i].trim()));
                        } catch (Exception e) {
                            // TODO: handle exception
                            //Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
                        }
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public static boolean isSdPresent() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public class ImageAdapter extends BaseAdapter {

        private Context context;
        private LayoutInflater layoutInflater;
        private int width;
        private int mGalleryItemBackground;

        public ImageAdapter(Context c) {
            context = c;

        }

        public ImageAdapter(Context c, int width) {
            context = c;
            this.width = width;
        }

        public int getCount() {
            return photo.size();
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = layoutInflater.inflate(R.layout.galleryadapter, null);

            RelativeLayout layout = (RelativeLayout) v.findViewById(R.id.galleryLayout);

            ImageView imageView = new ImageView(context);
            layout.addView(imageView, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            layout.setLayoutParams(new GridView.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, width));
            imageView.setImageBitmap(photo.get(position));

            return v;

        }

        public void updateItemList(ArrayList<Bitmap> newItemList) {
            photo = newItemList;
            notifyDataSetChanged();
        }
    }


}

Now create its Xml Class

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
android:orientation="vertical">

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="56dp"
    android:background="@color/colorPrimary"
    android:minHeight="?attr/actionBarSize">

    <TextView
        android:id="@+id/gallerytxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_gravity="center"
        android:fontFamily="@string/font_fontFamily_medium"
        android:text="My Gallery"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@android:color/black"
        android:textStyle="bold" />

    <ImageButton
        android:id="@+id/btn_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="12dp"
        android:background="@drawable/ic_arrow_back_black_24dp" />
</RelativeLayout>


<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_gravity="center|bottom"
    android:visibility="gone"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_id" />

<GridView
    android:id="@+id/gridView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/adView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/relativeLayout"
    android:horizontalSpacing="5dp"
    android:numColumns="2"
    android:smoothScrollbar="true"
    android:verticalSpacing="5dp"></GridView>
## Also Make Adapter galleryadapter.xml ##
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="@+id/galleryLayout"
android:padding="2dp">
[![enter image description here][1]][1]

To see the Image in Detail create a new Class ImageDetail:##

 public class ImageDetail extends Activity implements OnClickListener {
    public static InterstitialAd mInterstitialAd;
    private ImageView mainImageView;
    private LinearLayout menuTop;
    private TableLayout menuBottom;
    private Boolean onOff = true;
    private ImageView delButton, mailButton, shareButton;

    private String imgUrl = null;
    private AdView mAdView;
    TextView titletxt;
    private String newFolder = "/IslamicGif/";
    private String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
    public static boolean deleted = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.image_detail);

        mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mAdView.loadAd(adRequest);
        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                mAdView.setVisibility(View.VISIBLE);
            }
        });
        mainImageView = (ImageView) findViewById(R.id.mainImageView);
        menuTop = (LinearLayout) findViewById(R.id.menuTop);
        menuBottom = (TableLayout) findViewById(R.id.menuBottom);
        titletxt = (TextView) findViewById(R.id.titletxt);
        titletxt.setTextSize(22);
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId(getString(R.string.interstial_id));

        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                requestNewInterstitial();

            }
        });
        requestNewInterstitial();
        delButton = (ImageView) findViewById(R.id.delButton);
        mailButton = (ImageView) findViewById(R.id.mailButton);
        shareButton = (ImageView) findViewById(R.id.shareButton);

        Bundle exBundle = getIntent().getExtras();
        if (exBundle != null) {
            imgUrl = exBundle.getString("ImgUrl");
        }
        if (isSdPresent()) {
            imgUrl = extStorageDirectory + newFolder + imgUrl;
        } else
            imgUrl = getFilesDir() + newFolder + imgUrl;

        if (imgUrl != null) {
            GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(mainImageView);
            Glide.with(this).load(imgUrl).into(imageViewTarget);

        }


        delButton.setOnClickListener(this);
        mailButton.setOnClickListener(this);
        shareButton.setOnClickListener(this);


    }

    public static boolean isSdPresent() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }


    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
            case R.id.shareButton:
                Image_Link();
                break;
            case R.id.delButton:
                deleted();
                break;
            case R.id.mailButton:
                sendemail();
                break;
            default:
                break;
        }
    }

    private void sendemail() {

        try {

            File photo = new File(imgUrl);
            Uri imageuri = Uri.fromFile(photo);


            String url = Constant.AppUrl;

            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append("Face Placer App Available here..Play Link");
            int start = builder.length();
            builder.append(url);
            int end = builder.length();

            builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
            String[] recipients2 = new String[]{"[email protected]", "",};
            emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
            emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
            emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
            emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
            emailIntent2.setType("text/html");
            emailIntent2.setType("image/JPEG");
            startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));

        } catch (Exception e) {
            // TODO: handle exception

            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
        }
    }


    private void Image_Link() {

        try {

            File photo = new File(imgUrl);
            Uri imageuri = Uri.fromFile(photo);


            String url = Constant.AppUrl;

            SpannableStringBuilder builder = new SpannableStringBuilder();
            builder.append("Face Placer App Available here..Play Link");
            int start = builder.length();
            builder.append(url);
            int end = builder.length();

            builder.setSpan(new URLSpan(url), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            Intent emailIntent2 = new Intent(Intent.ACTION_SEND);
            String[] recipients2 = new String[]{"[email protected]", "",};
            emailIntent2.putExtra(Intent.EXTRA_EMAIL, recipients2);
            emailIntent2.putExtra(Intent.EXTRA_SUBJECT, "Sample mail");
            emailIntent2.putExtra(Intent.EXTRA_STREAM, imageuri);
            emailIntent2.putExtra(Intent.EXTRA_TEXT, builder);
            emailIntent2.setType("text/html");
            emailIntent2.putExtra(Intent.EXTRA_TEXT, "Face Placer App Available here..Play Link " + url);
            emailIntent2.setType("image/JPEG");
            startActivity(Intent.createChooser(emailIntent2, "Send mail client :"));

        } catch (Exception e) {
            // TODO: handle exception

            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
        }
    }


    private void deleted() {
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(ImageDetail.this);
        builder.setTitle(getString(R.string.removeoption));
        builder.setMessage(getString(R.string.deleteimage));
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                dialog.cancel();
                File fileDel = new File(imgUrl);
                boolean isCheck1 = fileDel.delete();

                if (isCheck1) {
                    deleted = true;
                    finish();
                    MyGallery.imageAdapter.notifyDataSetChanged();

                } else {
                    Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
                }
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                dialog.cancel();

            }
        });
        Dialog dialog = builder.create();
        dialog.show();


    }


    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            // There are no active networks.
            return false;
        } else
            return true;
    }

    private void requestNewInterstitial() {
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
                .build();

        mInterstitialAd.loadAd(adRequest);
    }

}

Create its xml image_detail.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bg"
android:orientation="vertical">

<ImageView
    android:id="@+id/mainImageView"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentBottom="true"
    android:contentDescription="@string/app_name"
    android:focusable="true"
    android:focusableInTouchMode="true" />

<LinearLayout
    android:id="@+id/adlayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:orientation="horizontal"
    android:visibility="gone"></LinearLayout>

<LinearLayout
    android:id="@+id/menuTop"
    android:layout_width="fill_parent"
    android:layout_height="56dp"
    android:layout_alignWithParentIfMissing="true"
    android:layout_below="@+id/adlayout"
    android:background="@color/colorPrimary"
    android:orientation="vertical"
    android:padding="10.0dip"
    android:visibility="visible">

    <TextView
        android:id="@+id/titletxt"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Islamic Gifs"
        android:textColor="#000000"
        android:textSize="22sp"
        android:textStyle="bold" />
</LinearLayout>

<TableLayout
    android:id="@+id/menuBottom"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:background="@color/colorPrimary"
    android:padding="10.0dip"
    android:stretchColumns="*"
    android:visibility="visible">

    <TableRow>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/mailButton"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:background="@drawable/selector_shareimage"
                android:contentDescription="@string/app_name" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/shareButton"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:background="@drawable/selector_shareimage_small"
                android:contentDescription="@string/app_name" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal">

            <ImageView
                android:id="@+id/delButton"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:background="@drawable/selector_delete"
                android:contentDescription="@string/app_name" />
        </LinearLayout>
    </TableRow>
</TableLayout>

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/menuTop"
    android:layout_centerHorizontal="true"
    android:visibility="gone"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_id"></com.google.android.gms.ads.AdView>

Add your own Drawable to Selector class,and create it res>drawable>selector_shareimage.xml

<?xml version="1.0" encoding="utf-8"?>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_pressed="true"/>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_focused="true"/>
<item android:drawable="@drawable/result_bt_mail" android:state_enabled="true" android:state_selected="true"/>
<item android:drawable="@drawable/result_bt_mail_s"/>

enter image description here

Dont forget to add in application tag for sdk version 29 and 30 legacy to add this line

android:requestLegacyExternalStorage="true"

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:requestLegacyExternalStorage="true"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

What svn command would list all the files modified on a branch?

echo You must invoke st from within branch directory
SvnUrl=`svn info | grep URL | sed 's/URL: //'`
SvnVer=`svn info | grep Revision | sed 's/Revision: //'`
svn diff -r $SvnVer --summarize $SvnUrl

How to change the color of an image on hover

Use the background-color property instead of the background property in your CSS. So your code will look like this:
.fb-icon:hover {
background: blue;
}

Round to 5 (or other number) in Python

It's just a matter of scaling

>>> a=[10,11,12,13,14,15,16,17,18,19,20]
>>> for b in a:
...     int(round(b/5.0)*5.0)
... 
10
10
10
15
15
15
15
15
20
20
20

React Native: Possible unhandled promise rejection

In My case, I am running a local Django backend in IP 127.0.0.1:8000 with Expo start. Just make sure you have the server in public domain not hosted lcoally on your machine

How to configure WAMP (localhost) to send email using Gmail?

PEAR: Mail worked for me sending email messages from Gmail. Also, the instructions: How to Send Email from a PHP Script Using SMTP Authentication (Using PEAR::Mail) helped greatly. Thanks, CMS!

apache mod_rewrite is not working or not enabled

Try setting: "AllowOverride All".

How do I undo a checkout in git?

You probably want git checkout master, or git checkout [branchname].

PHP Multidimensional Array Searching (Find key by specific value)

This class method can search in array by multiple conditions:

class Stdlib_Array
{
    public static function multiSearch(array $array, array $pairs)
    {
        $found = array();
        foreach ($array as $aKey => $aVal) {
            $coincidences = 0;
            foreach ($pairs as $pKey => $pVal) {
                if (array_key_exists($pKey, $aVal) && $aVal[$pKey] == $pVal) {
                    $coincidences++;
                }
            }
            if ($coincidences == count($pairs)) {
                $found[$aKey] = $aVal;
            }
        }

        return $found;
    }    
}

// Example:

$data = array(
    array('foo' => 'test4', 'bar' => 'baz'),
    array('foo' => 'test',  'bar' => 'baz'),
    array('foo' => 'test1', 'bar' => 'baz3'),
    array('foo' => 'test',  'bar' => 'baz'),
    array('foo' => 'test',  'bar' => 'baz4'),
    array('foo' => 'test4', 'bar' => 'baz1'),
    array('foo' => 'test',  'bar' => 'baz1'),
    array('foo' => 'test3', 'bar' => 'baz2'),
    array('foo' => 'test',  'bar' => 'baz'),
    array('foo' => 'test',  'bar' => 'baz'),
    array('foo' => 'test4', 'bar' => 'baz1')
);

$result = Stdlib_Array::multiSearch($data, array('foo' => 'test4', 'bar' => 'baz1'));

var_dump($result);

Will produce:

array(2) {
  [5]=>
  array(2) {
    ["foo"]=>
    string(5) "test4"
    ["bar"]=>
    string(4) "baz1"
  }
  [10]=>
  array(2) {
    ["foo"]=>
    string(5) "test4"
    ["bar"]=>
    string(4) "baz1"
  }
}

Can I change the color of Font Awesome's icon color?

If you want to change the color of a specific icon, you can use something like this:

.fa-stop {
    color:red;
}

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

In my case I got the error simply because I had changed the Listen 80 to listen 443 in the file

/etc/httpd/conf/httpd.conf 

Since I had installed mod_ssl using the yum commands

yum -y install mod_ssl  

there was a duplicate listen 443 directive in the file ssl.conf created during mod_ssl installation.

You can verify this if you have duplicate listen 80 or 443 by running the below command in linux centos (My linux)

grep  '443' /etc/httpd/conf.d/*

below is sample output

/etc/httpd/conf.d/ssl.conf:Listen 443 https
/etc/httpd/conf.d/ssl.conf:<VirtualHost _default_:443>
/etc/httpd/conf.d/ssl.conf:#ServerName www.example.com:443

Simply reverting the listen 443 in httd.conf to listen 80 fixed my issue.

Filtering Pandas DataFrames on dates

You can use pd.Timestamp to perform a query and a local reference

import pandas as pd
import numpy as np

df = pd.DataFrame()
ts = pd.Timestamp

df['date'] = np.array(np.arange(10) + datetime.now().timestamp(), dtype='M8[s]')

print(df)
print(df.query('date > @ts("20190515T071320")')

with the output

                 date
0 2019-05-15 07:13:16
1 2019-05-15 07:13:17
2 2019-05-15 07:13:18
3 2019-05-15 07:13:19
4 2019-05-15 07:13:20
5 2019-05-15 07:13:21
6 2019-05-15 07:13:22
7 2019-05-15 07:13:23
8 2019-05-15 07:13:24
9 2019-05-15 07:13:25


                 date
5 2019-05-15 07:13:21
6 2019-05-15 07:13:22
7 2019-05-15 07:13:23
8 2019-05-15 07:13:24
9 2019-05-15 07:13:25

Have a look at the pandas documentation for DataFrame.query, specifically the mention about the local variabile referenced udsing @ prefix. In this case we reference pd.Timestamp using the local alias ts to be able to supply a timestamp string

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Implicit and Explicit Waits

Implicit Wait

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Explicit Wait + Expected Conditions

An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
        ExpectedConditions.visibilityOfElementLocated(By.id("someid")));

JPA Native Query select and cast object

The accepted answer is incorrect.

createNativeQuery will always return a Query:

public Query createNativeQuery(String sqlString, Class resultClass);

Calling getResultList on a Query returns List:

List getResultList()

When assigning (or casting) to List<MyEntity>, an unchecked assignment warning is produced.

Whereas, createQuery will return a TypedQuery:

public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);

Calling getResultList on a TypedQuery returns List<X>.

List<X> getResultList();

This is properly typed and will not give a warning.

With createNativeQuery, using ObjectMapper seems to be the only way to get rid of the warning. Personally, I choose to suppress the warning, as I see this as a deficiency in the library and not something I should have to worry about.

Is it possible to run one logrotate check manually?

Issue the following command,the way to run specified logrotate:

logrotate -vf /etc/logrotate.d/custom

Options:

-v :show the process

-f :forcing run

custom :user-defined log setting

eg: mongodb-log

# mongodb-log rotate

/data/var/log/mongodb/mongod.log {
    daily
    dateext
    rotate 30
    copytruncate
    missingok
}

How to make --no-ri --no-rdoc the default for gem install?

From RVM’s documentation:

Just add this line to your ~/.gemrc or /etc/gemrc:

gem: --no-document

Note: The original answer was:

install: --no-rdoc --no-ri 
update: --no-rdoc --no-ri 

This is no longer valid; the RVM docs have since been updated, thus the current answer to only include the gem directive is the correct one.

When should I use a List vs a LinkedList

This is adapted from Tono Nam's accepted answer correcting a few wrong measurements in it.

The test:

static void Main()
{
    LinkedListPerformance.AddFirst_List(); // 12028 ms
    LinkedListPerformance.AddFirst_LinkedList(); // 33 ms

    LinkedListPerformance.AddLast_List(); // 33 ms
    LinkedListPerformance.AddLast_LinkedList(); // 32 ms

    LinkedListPerformance.Enumerate_List(); // 1.08 ms
    LinkedListPerformance.Enumerate_LinkedList(); // 3.4 ms

    //I tried below as fun exercise - not very meaningful, see code
    //sort of equivalent to insertion when having the reference to middle node

    LinkedListPerformance.AddMiddle_List(); // 5724 ms
    LinkedListPerformance.AddMiddle_LinkedList1(); // 36 ms
    LinkedListPerformance.AddMiddle_LinkedList2(); // 32 ms
    LinkedListPerformance.AddMiddle_LinkedList3(); // 454 ms

    Environment.Exit(-1);
}

And the code:

using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace stackoverflow
{
    static class LinkedListPerformance
    {
        class Temp
        {
            public decimal A, B, C, D;

            public Temp(decimal a, decimal b, decimal c, decimal d)
            {
                A = a; B = b; C = c; D = d;
            }
        }



        static readonly int start = 0;
        static readonly int end = 123456;
        static readonly IEnumerable<Temp> query = Enumerable.Range(start, end - start).Select(temp);

        static Temp temp(int i)
        {
            return new Temp(i, i, i, i);
        }

        static void StopAndPrint(this Stopwatch watch)
        {
            watch.Stop();
            Console.WriteLine(watch.Elapsed.TotalMilliseconds);
        }

        public static void AddFirst_List()
        {
            var list = new List<Temp>();
            var watch = Stopwatch.StartNew();

            for (var i = start; i < end; i++)
                list.Insert(0, temp(i));

            watch.StopAndPrint();
        }

        public static void AddFirst_LinkedList()
        {
            var list = new LinkedList<Temp>();
            var watch = Stopwatch.StartNew();

            for (int i = start; i < end; i++)
                list.AddFirst(temp(i));

            watch.StopAndPrint();
        }

        public static void AddLast_List()
        {
            var list = new List<Temp>();
            var watch = Stopwatch.StartNew();

            for (var i = start; i < end; i++)
                list.Add(temp(i));

            watch.StopAndPrint();
        }

        public static void AddLast_LinkedList()
        {
            var list = new LinkedList<Temp>();
            var watch = Stopwatch.StartNew();

            for (int i = start; i < end; i++)
                list.AddLast(temp(i));

            watch.StopAndPrint();
        }

        public static void Enumerate_List()
        {
            var list = new List<Temp>(query);
            var watch = Stopwatch.StartNew();

            foreach (var item in list)
            {

            }

            watch.StopAndPrint();
        }

        public static void Enumerate_LinkedList()
        {
            var list = new LinkedList<Temp>(query);
            var watch = Stopwatch.StartNew();

            foreach (var item in list)
            {

            }

            watch.StopAndPrint();
        }

        //for the fun of it, I tried to time inserting to the middle of 
        //linked list - this is by no means a realistic scenario! or may be 
        //these make sense if you assume you have the reference to middle node

        //insertion to the middle of list
        public static void AddMiddle_List()
        {
            var list = new List<Temp>();
            var watch = Stopwatch.StartNew();

            for (var i = start; i < end; i++)
                list.Insert(list.Count / 2, temp(i));

            watch.StopAndPrint();
        }

        //insertion in linked list in such a fashion that 
        //it has the same effect as inserting into the middle of list
        public static void AddMiddle_LinkedList1()
        {
            var list = new LinkedList<Temp>();
            var watch = Stopwatch.StartNew();

            LinkedListNode<Temp> evenNode = null, oddNode = null;
            for (int i = start; i < end; i++)
            {
                if (list.Count == 0)
                    oddNode = evenNode = list.AddLast(temp(i));
                else
                    if (list.Count % 2 == 1)
                        oddNode = list.AddBefore(evenNode, temp(i));
                    else
                        evenNode = list.AddAfter(oddNode, temp(i));
            }

            watch.StopAndPrint();
        }

        //another hacky way
        public static void AddMiddle_LinkedList2()
        {
            var list = new LinkedList<Temp>();
            var watch = Stopwatch.StartNew();

            for (var i = start + 1; i < end; i += 2)
                list.AddLast(temp(i));
            for (int i = end - 2; i >= 0; i -= 2)
                list.AddLast(temp(i));

            watch.StopAndPrint();
        }

        //OP's original more sensible approach, but I tried to filter out
        //the intermediate iteration cost in finding the middle node.
        public static void AddMiddle_LinkedList3()
        {
            var list = new LinkedList<Temp>();
            var watch = Stopwatch.StartNew();

            for (var i = start; i < end; i++)
            {
                if (list.Count == 0)
                    list.AddLast(temp(i));
                else
                {
                    watch.Stop();
                    var curNode = list.First;
                    for (var j = 0; j < list.Count / 2; j++)
                        curNode = curNode.Next;
                    watch.Start();

                    list.AddBefore(curNode, temp(i));
                }
            }

            watch.StopAndPrint();
        }
    }
}

You can see the results are in accordance with theoretical performance others have documented here. Quite clear - LinkedList<T> gains big time in case of insertions. I haven't tested for removal from the middle of list, but the result should be the same. Of course List<T> has other areas where it performs way better like O(1) random access.

Select rows where column is null

select Column from Table where Column is null;

SQL Server principal "dbo" does not exist,

Go to the Properties - Files. The owner name must be blank. Just put "sa" in the user name and the issue will be resolved.

How to remove first and last character of a string?

SOLUTION 1

def spaceMeOut(str1):

   print(str1[1:len(str1)-1])

str1='Hello'

print(spaceMeOut(str1))

SOLUTION 2

def spaceMeOut(str1):

  res=str1[1:len(str1)-1]

  print('{}'.format(res))

str1='Hello'

print(spaceMeOut(str1))

avrdude: stk500v2_ReceiveMessage(): timeout

Open Terminal and type:

$ sudo usermod -a -G dialout 

(This command is optional)

$ **sudo chmod a+rw /dev/ttyACM0** 

(This command must succeed)

NoSql vs Relational database

Just adding to all the information given above

NoSql Advantages:

1) NoSQL is good if you want to be production ready fast due to its support for schema-less and object oriented architecture.

2) NoSql db's are eventually consistent which in simple language means they will not provide any lock on the data(documents) as in case of RDBMS and what does it mean is latest snapshot of data is always available and thus increase the latency of your application.

3) It uses MVCC (Multi view concurrency control) strategy for maintaining and creating snapshot of data(documents).

4) If you want to have indexed data you can create view which will automatically index the data by the view definition you provide.

NoSql Disadvantages:

1) Its definitely not suitable for big heavy transactional applications as it is eventually consistent and does not support ACID properties.

2) Also it creates multiple snapshots (revisions) of your data (documents) as it uses MVCC methodology for concurrency control, as a result of which space get consumed faster than before which makes compaction and hence reindexing more frequent and it will slow down your application response as the data and transaction in your application grows. To counter that you can horizontally scale the nodes but then again it will be higher cost as compare sql database.

Merge a Branch into Trunk

The syntax is wrong, it should instead be

svn merge <what(the range)> <from(your dev branch)> <to(trunk/trunk local copy)>

HTTP GET with request body

Roy Fielding's comment about including a body with a GET request.

Yes. In other words, any HTTP request message is allowed to contain a message body, and thus must parse messages with that in mind. Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request. The requirements on parsing are separate from the requirements on method semantics.

So, yes, you can send a body with GET, and no, it is never useful to do so.

This is part of the layered design of HTTP/1.1 that will become clear again once the spec is partitioned (work in progress).

....Roy

Yes, you can send a request body with GET but it should not have any meaning. If you give it meaning by parsing it on the server and changing your response based on its contents, then you are ignoring this recommendation in the HTTP/1.1 spec, section 4.3:

...if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.

And the description of the GET method in the HTTP/1.1 spec, section 9.3:

The GET method means retrieve whatever information ([...]) is identified by the Request-URI.

which states that the request-body is not part of the identification of the resource in a GET request, only the request URI.

Update

The RFC2616 referenced as "HTTP/1.1 spec" is now obsolete. In 2014 it was replaced by RFCs 7230-7237. Quote "the message-body SHOULD be ignored when handling the request" has been deleted. It's now just "Request message framing is independent of method semantics, even if the method doesn't define any use for a message body" The 2nd quote "The GET method means retrieve whatever information ... is identified by the Request-URI" was deleted. - From a comment

From the HTTP 1.1 2014 Spec:

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

#define in Java

Java Primitive Specializations Generator supports /* with */, /* define */ and /* if */ ... /* elif */ ... /* endif */ blocks which allow to do some kind of macro generation in Java code, similar to java-comment-preprocessor mentioned in this answer.

JPSG has Maven and Gradle plugins.

How to cherry-pick from a remote branch?

This can also be easily achieved with SourceTree:

  • checkout your master branch
  • open the "Log / History" tab
  • locate the xyz commit and right click on it
  • click on "Merge..."

done :)

is vs typeof

They don't do the same thing. The first one works if obj is of type ClassA or of some subclass of ClassA. The second one will only match objects of type ClassA. The second one will be faster since it doesn't have to check the class hierarchy.

For those who want to know the reason, but don't want to read the article referenced in is vs typeof.

Can I recover a branch after its deletion in Git?

First go to git batch the move to your project like :

cd android studio project
cd Myproject
then type :
git reflog

You all have a list of the changes and the reference number take the ref number then checkout
from android studio or from the git betcha. another solution take the ref number and go to android studio click on git branches down then click on checkout tag or revision past the reference number then lol you have the branches.

Can't find AVD or SDK manager in Eclipse

Try to reinstall ADT plugin on Eclipse. Check out this: Installing the Eclipse Plugin

How to remove white space characters from a string in SQL Server

In that case, it isn't space that is in prefix/suffix.
The 1st row looks OK. Do the following for the contents of 2nd row.

ASCII(RIGHT(ProductAlternateKey, 1))

and

ASCII(LEFT(ProductAlternateKey, 1))

shell-script headers (#!/bin/sh vs #!/bin/csh)

This is known as a Shebang:

http://en.wikipedia.org/wiki/Shebang_(Unix)

#!interpreter [optional-arg]

A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).

When a shell executes the script it will use the specified interpreter.

Example:

#!/bin/bash
# file: foo.sh
echo 1

$ chmod u+x foo.sh
$ ./foo.sh
  1

Youtube autoplay not working on mobile devices with embedded HTML5 player

The code below was tested on iPhone, iPad (iOS13), Safari (Catalina). It was able to autoplay the YouTube video on all devices. Make sure the video is muted and the playsinline parameter is on. Those are the magic parameters that make it work.

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
    </head>
  <body>
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      width: '100%',
      videoId: 'osz5tVY97dQ',
      playerVars: { 'autoplay': 1, 'playsinline': 1 },
      events: {
        'onReady': onPlayerReady
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
     event.target.mute();
    event.target.playVideo();
  }
</script>
  </body>
</html>

What's the best way to store Phone number in Django models

Others mentioned django-phonenumber-field. To get the display format how you want you need to set PHONENUMBER_DEFAULT_FORMAT setting to "E164", "INTERNATIONAL", "NATIONAL", or "RFC3966", however you want it displayed. See the GitHub source.

.NET Format a string with fixed spaces

You've been shown PadLeft and PadRight. This will fill in the missing PadCenter.

public static class StringUtils
{
    public static string PadCenter(this string s, int width, char c)
    {
        if (s == null || width <= s.Length) return s;

        int padding = width - s.Length;
        return s.PadLeft(s.Length + padding / 2, c).PadRight(width, c);
    }
}

Note to self: don't forget to update own CV: "One day, I even fixed Joel Coehoorn's code!" ;-D -Serge

Cleanest Way to Invoke Cross-Thread Events

I have some code for this online. It's much nicer than the other suggestions; definitely check it out.

Sample usage:

private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
    // You could use "() =>" in place of "delegate"; it's a style choice.
    this.Invoke(delegate
    {
        // Do the dirty work of my method here.
    });
}

How to add a margin to a table row <tr>

Because margin is ignored on tr, I usually use a workaround, by setting a transparent border-bottom or border-top and setting the background-clip property to padding-box so the background-color does not get painted underneath the border.

table {
   border-collapse: collapse; /* [1] */
}

th, td {
  border-bottom: 5px solid transparent; /* [2] */
  background-color: gold; /* [3] */
  background-clip: padding-box; /* [4] */
}
  1. Makes sure cells share a common border, but is completely optional. The solution works without it.
  2. The 5px value represents the margin that you want to achieve
  3. Sets the background-color of your row/cell
  4. Makes sure the background get not painted underneath the border

see a demo here: http://codepen.io/meodai/pen/MJMVNR?editors=1100

background-clip is supported in all modern browser. (And IE9+)

Alternatively you could use a border-spacing. But this will not work with border-collapse set to collapse.

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

Try something like this

var d = new Date,
    dformat = [d.getMonth()+1,
               d.getDate(),
               d.getFullYear()].join('/')+' '+
              [d.getHours(),
               d.getMinutes(),
               d.getSeconds()].join(':');

If you want leading zero's for values < 10, use this number extension

Number.prototype.padLeft = function(base,chr){
    var  len = (String(base || 10).length - String(this).length)+1;
    return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3' 

Applied to the previous code:

var d = new Date,
    dformat = [(d.getMonth()+1).padLeft(),
               d.getDate().padLeft(),
               d.getFullYear()].join('/') +' ' +
              [d.getHours().padLeft(),
               d.getMinutes().padLeft(),
               d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'

See this code in jsfiddle

[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.

_x000D_
_x000D_
var dt = new Date();_x000D_
_x000D_
console.log(`${_x000D_
    (dt.getMonth()+1).toString().padStart(2, '0')}/${_x000D_
    dt.getDate().toString().padStart(2, '0')}/${_x000D_
    dt.getFullYear().toString().padStart(4, '0')} ${_x000D_
    dt.getHours().toString().padStart(2, '0')}:${_x000D_
    dt.getMinutes().toString().padStart(2, '0')}:${_x000D_
    dt.getSeconds().toString().padStart(2, '0')}`_x000D_
);
_x000D_
_x000D_
_x000D_

See also

how to always round up to the next integer

A proper benchmark or how the number may lie

Following the argument about Math.ceil(value/10d) and (value+9)/10 I ended up coding a proper non-dead code, non-interpret mode benchmark. I've been telling that writing micro benchmark is not an easy task. The code below illustrates this:

00:21:40.109 starting up....
00:21:40.140 doubleCeil: 19444599
00:21:40.140 integerCeil: 19444599
00:21:40.140 warming up...
00:21:44.375 warmup doubleCeil: 194445990000
00:21:44.625 warmup integerCeil: 194445990000
00:22:27.437 exec doubleCeil: 1944459900000, elapsed: 42.806s
00:22:29.796 exec integerCeil: 1944459900000, elapsed: 2.363s

The benchmark is in Java since I know well how Hotspot optimizes and ensures it's a fair result. With such results, no statistics, noise or anything can taint it.

Integer ceil is insanely much faster.

The code

package t1;

import java.math.BigDecimal;

import java.util.Random;

public class Div {
    static int[] vals;

    static long doubleCeil(){
        int[] v= vals;
        long sum = 0;
        for (int i=0;i<v.length;i++){
            int value = v[i];
            sum+=Math.ceil(value/10d);
        }
        return sum;
    }

    static long integerCeil(){      
        int[] v= vals;
        long sum = 0;
        for (int i=0;i<v.length;i++){
            int value = v[i];
            sum+=(value+9)/10;
        }
        return sum;     
    }

    public static void main(String[] args) {
        vals = new  int[7000];
        Random r= new Random(77);
        for (int i = 0; i < vals.length; i++) {
            vals[i] = r.nextInt(55555);
        }
        log("starting up....");

        log("doubleCeil: %d", doubleCeil());
        log("integerCeil: %d", integerCeil());
        log("warming up...");       

        final int warmupCount = (int) 1e4;
        log("warmup doubleCeil: %d", execDoubleCeil(warmupCount));
        log("warmup integerCeil: %d", execIntegerCeil(warmupCount));

        final int execCount = (int) 1e5;

        {       
        long time = System.nanoTime();
        long s = execDoubleCeil(execCount);
        long elapsed = System.nanoTime() - time;
        log("exec doubleCeil: %d, elapsed: %.3fs",  s, BigDecimal.valueOf(elapsed, 9));
        }

        {
        long time = System.nanoTime();
        long s = execIntegerCeil(execCount);
        long elapsed = System.nanoTime() - time;
        log("exec integerCeil: %d, elapsed: %.3fs",  s, BigDecimal.valueOf(elapsed, 9));            
        }
    }

    static long execDoubleCeil(int count){
        long sum = 0;
        for(int i=0;i<count;i++){
            sum+=doubleCeil();
        }
        return sum;
    }


    static long execIntegerCeil(int count){
        long sum = 0;
        for(int i=0;i<count;i++){
            sum+=integerCeil();
        }
        return sum;
    }

    static void log(String msg, Object... params){
        String s = params.length>0?String.format(msg, params):msg;
        System.out.printf("%tH:%<tM:%<tS.%<tL %s%n", new Long(System.currentTimeMillis()), s);
    }   
}

Repeat String - Javascript

Concatenating strings based on an number.

function concatStr(str, num) {
   var arr = [];

   //Construct an array
   for (var i = 0; i < num; i++)
      arr[i] = str;

   //Join all elements
   str = arr.join('');

   return str;
}

console.log(concatStr("abc", 3));

Hope that helps!

Vue.js img src concatenate variable and text

just try

_x000D_
_x000D_
<img :src="require(`${imgPreUrl}img/logo.png`)">
_x000D_
_x000D_
_x000D_

Is there a regular expression to detect a valid regular expression?

The following example by Paul McGuire, originally from the pyparsing wiki, but now available only through the Wayback Machine, gives a grammar for parsing some regexes, for the purposes of returning the set of matching strings. As such, it rejects those re's that include unbounded repetition terms, like '+' and '*'. But it should give you an idea about how to structure a parser that would process re's.

# 
# invRegex.py
#
# Copyright 2008, Paul McGuire
#
# pyparsing script to expand a regular expression into all possible matching strings
# Supports:
# - {n} and {m,n} repetition, but not unbounded + or * repetition
# - ? optional elements
# - [] character ranges
# - () grouping
# - | alternation
#
__all__ = ["count","invert"]

from pyparsing import (Literal, oneOf, printables, ParserElement, Combine, 
    SkipTo, operatorPrecedence, ParseFatalException, Word, nums, opAssoc,
    Suppress, ParseResults, srange)

class CharacterRangeEmitter(object):
    def __init__(self,chars):
        # remove duplicate chars in character range, but preserve original order
        seen = set()
        self.charset = "".join( seen.add(c) or c for c in chars if c not in seen )
    def __str__(self):
        return '['+self.charset+']'
    def __repr__(self):
        return '['+self.charset+']'
    def makeGenerator(self):
        def genChars():
            for s in self.charset:
                yield s
        return genChars

class OptionalEmitter(object):
    def __init__(self,expr):
        self.expr = expr
    def makeGenerator(self):
        def optionalGen():
            yield ""
            for s in self.expr.makeGenerator()():
                yield s
        return optionalGen

class DotEmitter(object):
    def makeGenerator(self):
        def dotGen():
            for c in printables:
                yield c
        return dotGen

class GroupEmitter(object):
    def __init__(self,exprs):
        self.exprs = ParseResults(exprs)
    def makeGenerator(self):
        def groupGen():
            def recurseList(elist):
                if len(elist)==1:
                    for s in elist[0].makeGenerator()():
                        yield s
                else:
                    for s in elist[0].makeGenerator()():
                        for s2 in recurseList(elist[1:]):
                            yield s + s2
            if self.exprs:
                for s in recurseList(self.exprs):
                    yield s
        return groupGen

class AlternativeEmitter(object):
    def __init__(self,exprs):
        self.exprs = exprs
    def makeGenerator(self):
        def altGen():
            for e in self.exprs:
                for s in e.makeGenerator()():
                    yield s
        return altGen

class LiteralEmitter(object):
    def __init__(self,lit):
        self.lit = lit
    def __str__(self):
        return "Lit:"+self.lit
    def __repr__(self):
        return "Lit:"+self.lit
    def makeGenerator(self):
        def litGen():
            yield self.lit
        return litGen

def handleRange(toks):
    return CharacterRangeEmitter(srange(toks[0]))

def handleRepetition(toks):
    toks=toks[0]
    if toks[1] in "*+":
        raise ParseFatalException("",0,"unbounded repetition operators not supported")
    if toks[1] == "?":
        return OptionalEmitter(toks[0])
    if "count" in toks:
        return GroupEmitter([toks[0]] * int(toks.count))
    if "minCount" in toks:
        mincount = int(toks.minCount)
        maxcount = int(toks.maxCount)
        optcount = maxcount - mincount
        if optcount:
            opt = OptionalEmitter(toks[0])
            for i in range(1,optcount):
                opt = OptionalEmitter(GroupEmitter([toks[0],opt]))
            return GroupEmitter([toks[0]] * mincount + [opt])
        else:
            return [toks[0]] * mincount

def handleLiteral(toks):
    lit = ""
    for t in toks:
        if t[0] == "\\":
            if t[1] == "t":
                lit += '\t'
            else:
                lit += t[1]
        else:
            lit += t
    return LiteralEmitter(lit)    

def handleMacro(toks):
    macroChar = toks[0][1]
    if macroChar == "d":
        return CharacterRangeEmitter("0123456789")
    elif macroChar == "w":
        return CharacterRangeEmitter(srange("[A-Za-z0-9_]"))
    elif macroChar == "s":
        return LiteralEmitter(" ")
    else:
        raise ParseFatalException("",0,"unsupported macro character (" + macroChar + ")")

def handleSequence(toks):
    return GroupEmitter(toks[0])

def handleDot():
    return CharacterRangeEmitter(printables)

def handleAlternative(toks):
    return AlternativeEmitter(toks[0])


_parser = None
def parser():
    global _parser
    if _parser is None:
        ParserElement.setDefaultWhitespaceChars("")
        lbrack,rbrack,lbrace,rbrace,lparen,rparen = map(Literal,"[]{}()")

        reMacro = Combine("\\" + oneOf(list("dws")))
        escapedChar = ~reMacro + Combine("\\" + oneOf(list(printables)))
        reLiteralChar = "".join(c for c in printables if c not in r"\[]{}().*?+|") + " \t"

        reRange = Combine(lbrack + SkipTo(rbrack,ignore=escapedChar) + rbrack)
        reLiteral = ( escapedChar | oneOf(list(reLiteralChar)) )
        reDot = Literal(".")
        repetition = (
            ( lbrace + Word(nums).setResultsName("count") + rbrace ) |
            ( lbrace + Word(nums).setResultsName("minCount")+","+ Word(nums).setResultsName("maxCount") + rbrace ) |
            oneOf(list("*+?")) 
            )

        reRange.setParseAction(handleRange)
        reLiteral.setParseAction(handleLiteral)
        reMacro.setParseAction(handleMacro)
        reDot.setParseAction(handleDot)

        reTerm = ( reLiteral | reRange | reMacro | reDot )
        reExpr = operatorPrecedence( reTerm,
            [
            (repetition, 1, opAssoc.LEFT, handleRepetition),
            (None, 2, opAssoc.LEFT, handleSequence),
            (Suppress('|'), 2, opAssoc.LEFT, handleAlternative),
            ]
            )
        _parser = reExpr

    return _parser

def count(gen):
    """Simple function to count the number of elements returned by a generator."""
    i = 0
    for s in gen:
        i += 1
    return i

def invert(regex):
    """Call this routine as a generator to return all the strings that
       match the input regular expression.
           for s in invert("[A-Z]{3}\d{3}"):
               print s
    """
    invReGenerator = GroupEmitter(parser().parseString(regex)).makeGenerator()
    return invReGenerator()

def main():
    tests = r"""
    [A-EA]
    [A-D]*
    [A-D]{3}
    X[A-C]{3}Y
    X[A-C]{3}\(
    X\d
    foobar\d\d
    foobar{2}
    foobar{2,9}
    fooba[rz]{2}
    (foobar){2}
    ([01]\d)|(2[0-5])
    ([01]\d\d)|(2[0-4]\d)|(25[0-5])
    [A-C]{1,2}
    [A-C]{0,3}
    [A-C]\s[A-C]\s[A-C]
    [A-C]\s?[A-C][A-C]
    [A-C]\s([A-C][A-C])
    [A-C]\s([A-C][A-C])?
    [A-C]{2}\d{2}
    @|TH[12]
    @(@|TH[12])?
    @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))?
    @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?|30?|[4-9]))?
    (([ECMP]|HA|AK)[SD]|HS)T
    [A-CV]{2}
    A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr]
    (a|b)|(x|y)
    (a|b) (x|y)
    """.split('\n')

    for t in tests:
        t = t.strip()
        if not t: continue
        print '-'*50
        print t
        try:
            print count(invert(t))
            for s in invert(t):
                print s
        except ParseFatalException,pfe:
            print pfe.msg
            print
            continue
        print

if __name__ == "__main__":
    main()

How to create a String with carriage returns?

Thanks for your answers. I missed that my data is stored in a List<String> which is passed to the tested method. The mistake was that I put the string into the first element of the ArrayList. That's why I thought the String consists of just one single line, because the debugger showed me only one entry.

Add left/right horizontal padding to UILabel

add a space character too the string. that's poor man's padding :)

OR

I would go with a custom background view but if you don't want that, the space is the only other easy options I see...

OR write a custom label. render the text via coretext

Best way to access web camera in Java

I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)

There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):

snapshot

The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.

API is really nice and easy to learn. Example how to capture single image and save it to PNG file:

Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));

IOException: The process cannot access the file 'file path' because it is being used by another process

What is the cause?

The error message is pretty clear: you're trying to access a file, and it's not accessible because another process (or even the same process) is doing something with it (and it didn't allow any sharing).

Debugging

It may be pretty easy to solve (or pretty hard to understand), depending on your specific scenario. Let's see some.

Your process is the only one to access that file
You're sure the other process is your own process. If you know you open that file in another part of your program, then first of all you have to check that you properly close the file handle after each use. Here is an example of code with this bug:

var stream = new FileStream(path, FileAccess.Read);
var reader = new StreamReader(stream);
// Read data from this file, when I'm done I don't need it any more
File.Delete(path); // IOException: file is in use

Fortunately FileStream implements IDisposable, so it's easy to wrap all your code inside a using statement:

using (var stream = File.Open("myfile.txt", FileMode.Open)) {
    // Use stream
}

// Here stream is not accessible and it has been closed (also if
// an exception is thrown and stack unrolled

This pattern will also ensure that the file won't be left open in case of exceptions (it may be the reason the file is in use: something went wrong, and no one closed it; see this post for an example).

If everything seems fine (you're sure you always close every file you open, even in case of exceptions) and you have multiple working threads, then you have two options: rework your code to serialize file access (not always doable and not always wanted) or apply a retry pattern. It's a pretty common pattern for I/O operations: you try to do something and in case of error you wait and try again (did you ask yourself why, for example, Windows Shell takes some time to inform you that a file is in use and cannot be deleted?). In C# it's pretty easy to implement (see also better examples about disk I/O, networking and database access).

private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;

for (int i=1; i <= NumberOfRetries; ++i) {
    try {
        // Do stuff with file
        break; // When done we can break loop
    }
    catch (IOException e) when (i <= NumberOfRetries) {
        // You may check error code to filter some exceptions, not every error
        // can be recovered.
        Thread.Sleep(DelayOnRetry);
    }
}

Please note a common error we see very often on StackOverflow:

var stream = File.Open(path, FileOpen.Read);
var content = File.ReadAllText(path);

In this case ReadAllText() will fail because the file is in use (File.Open() in the line before). To open the file beforehand is not only unnecessary but also wrong. The same applies to all File functions that don't return a handle to the file you're working with: File.ReadAllText(), File.WriteAllText(), File.ReadAllLines(), File.WriteAllLines() and others (like File.AppendAllXyz() functions) will all open and close the file by themselves.

Your process is not the only one to access that file
If your process is not the only one to access that file, then interaction can be harder. A retry pattern will help (if the file shouldn't be open by anyone else but it is, then you need a utility like Process Explorer to check who is doing what).

Ways to avoid

When applicable, always use using statements to open files. As said in previous paragraph, it'll actively help you to avoid many common errors (see this post for an example on how not to use it).

If possible, try to decide who owns access to a specific file and centralize access through a few well-known methods. If, for example, you have a data file where your program reads and writes, then you should box all I/O code inside a single class. It'll make debug easier (because you can always put a breakpoint there and see who is doing what) and also it'll be a synchronization point (if required) for multiple access.

Don't forget I/O operations can always fail, a common example is this:

if (File.Exists(path))
    File.Delete(path);

If someone deletes the file after File.Exists() but before File.Delete(), then it'll throw an IOException in a place where you may wrongly feel safe.

Whenever it's possible, apply a retry pattern, and if you're using FileSystemWatcher, consider postponing action (because you'll get notified, but an application may still be working exclusively with that file).

Advanced scenarios
It's not always so easy, so you may need to share access with someone else. If, for example, you're reading from the beginning and writing to the end, you have at least two options.

1) share the same FileStream with proper synchronization functions (because it is not thread-safe). See this and this posts for an example.

2) use FileShare enumeration to instruct OS to allow other processes (or other parts of your own process) to access same file concurrently.

using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Read))
{
}

In this example I showed how to open a file for writing and share for reading; please note that when reading and writing overlaps, it results in undefined or invalid data. It's a situation that must be handled when reading. Also note that this doesn't make access to the stream thread-safe, so this object can't be shared with multiple threads unless access is synchronized somehow (see previous links). Other sharing options are available, and they open up more complex scenarios. Please refer to MSDN for more details.

In general N processes can read from same file all together but only one should write, in a controlled scenario you may even enable concurrent writings but this can't be generalized in few text paragraphs inside this answer.

Is it possible to unlock a file used by another process? It's not always safe and not so easy but yes, it's possible.

How to draw border around a UILabel?

Swift 3/4 with @IBDesignable


While almost all the above solutions work fine but I would suggest an @IBDesignable custom class for this.

@IBDesignable
class CustomLabel: UILabel {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    @IBInspectable var borderColor: UIColor = UIColor.white {
        didSet {
            layer.borderColor = borderColor.cgColor
        }
    }

    @IBInspectable var borderWidth: CGFloat = 2.0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0.0 {
        didSet {
            layer.cornerRadius = cornerRadius
        }
    }
}

What does \0 stand for?

To the C language, '\0' means exactly the same thing as the integer constant 0 (same value zero, same type int).

To someone reading the code, writing '\0' suggests that you're planning to use this particular zero as a character.

SFTP in Python? (platform independent)

Paramiko is so slow. Use subprocess and shell, here is an example:

remote_file_name = "filename"
remotedir = "/remote/dir"
localpath = "/local/file/dir"
    ftp_cmd_p = """
    #!/bin/sh
    lftp -u username,password sftp://ip:port <<EOF
    cd {remotedir}
    lcd {localpath}
    get {filename}
    EOF
    """
subprocess.call(ftp_cmd_p.format(remotedir=remotedir,
                                 localpath=localpath,
                                 filename=remote_file_name 
                                 ), 
                shell=True, stdout=sys.stdout, stderr=sys.stderr)

Using Switch Statement to Handle Button Clicks

    XML CODE FOR TWO BUTTONS  
     <Button
            android:id="@+id/btn_save"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SAVE"
            android:onClick="process"
            />
        <Button
            android:id="@+id/btn_show"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SHOW"
            android:onClick="process"/> 

  Java Code
 <pre> public void process(View view) {
            switch (view.getId()){
                case R.id.btn_save:
                  //add your own code
                    break;
                case R.id.btn_show:
                   //add your own code
                    break;
            }</pre>

How to call a shell script from python code?

The subprocess module will help you out.

Blatantly trivial example:

>>> import subprocess
>>> subprocess.call(['sh', './test.sh']) # Thanks @Jim Dennis for suggesting the []
0 
>>> 

Where test.sh is a simple shell script and 0 is its return value for this run.

Sending JSON object to Web API

I believe you need quotes around the model:

JSON.stringify({ "model": source })

base_url() function not working in codeigniter

Load url helper in controller

$this->load->helper('url');

How to redirect to another page using AngularJS?

Using location.href="./index.html"

or create scope $window

and using $window.location.href="./index.html"

CSS way to horizontally align table

style="text-align:center;" 

(i think)

or you could just ignore it, it still works

How to Install Font Awesome in Laravel Mix

This is for new users who are using Laravel 5.7(and above) and Fontawesome 5.3

npm install @fortawesome/fontawesome-free --save

and in app.scss

@import '~@fortawesome/fontawesome-free/css/all.min.css';

Run

npm run watch

Use in layout

<link href="{{ asset('css/app.css') }}" rel="stylesheet">

Get href attribute on jQuery

add a reference to this, which refers to your b_row:

$("tr.b_row").each(function(){
    var a_href = $( this ).find('div.cpt h2 a').attr('href');
    alert ("Href is: "+a_href);
});

Creating Unicode character from its number

The other answers here either only support unicode up to U+FFFF (the answers dealing with just one instance of char) or don't tell how to get to the actual symbol (the answers stopping at Character.toChars() or using incorrect method after that), so adding my answer here, too.

To support supplementary code points also, this is what needs to be done:

// this character:
// http://www.isthisthingon.org/unicode/index.php?page=1F&subpage=4&glyph=1F495
// using code points here, not U+n notation
// for equivalence with U+n, below would be 0xnnnn
int codePoint = 128149;
// converting to char[] pair
char[] charPair = Character.toChars(codePoint);
// and to String, containing the character we want
String symbol = new String(charPair);

// we now have str with the desired character as the first item
// confirm that we indeed have character with code point 128149
System.out.println("First code point: " + symbol.codePointAt(0));

I also did a quick test as to which conversion methods work and which don't

int codePoint = 128149;
char[] charPair = Character.toChars(codePoint);

System.out.println(new String(charPair, 0, 2).codePointAt(0)); // 128149, worked
System.out.println(charPair.toString().codePointAt(0));        // 91, didn't work
System.out.println(new String(charPair).codePointAt(0));       // 128149, worked
System.out.println(String.valueOf(codePoint).codePointAt(0));  // 49, didn't work
System.out.println(new String(new int[] {codePoint}, 0, 1).codePointAt(0));
                                                               // 128149, worked

Python error: AttributeError: 'module' object has no attribute

When you import lib, you're importing the package. The only file to get evaluated and run in this case is the 0 byte __init__.py in the lib directory.

If you want access to your function, you can do something like this from lib.mod1 import mod1 and then run the mod12 function like so mod1.mod12().

If you want to be able to access mod1 when you import lib, you need to put an import mod1 inside the __init__.py file inside the lib directory.

jQuery: how do I animate a div rotation?

This works for me:

function animateRotate (object,fromDeg,toDeg,duration){
    var dummy = $('<span style="margin-left:'+fromDeg+'px;">')
    $(dummy).animate({
        "margin-left":toDeg+"px"
    },{
        duration:duration,
        step: function(now,fx){
            $(object).css('transform','rotate(' + now + 'deg)');
        }
    });
};

How can I change the font-size of a select option?

select[value="value"]{
   background-color: red;
   padding: 3px;
   font-weight:bold;
}

Conditionally ignoring tests in JUnit 4

In JUnit 4, another option for you may be to create an annotation to denote that the test needs to meet your custom criteria, then extend the default runner with your own and using reflection, base your decision on the custom criteria. It may look something like this:

public class CustomRunner extends BlockJUnit4ClassRunner {
    public CTRunner(Class<?> klass) throws initializationError {
        super(klass);
    }

    @Override
    protected boolean isIgnored(FrameworkMethod child) {
        if(shouldIgnore()) {
            return true;
        }
        return super.isIgnored(child);
    }

    private boolean shouldIgnore(class) {
        /* some custom criteria */
    }
}

Android - Package Name convention

The package name is used for unique identification for your application.
Android uses the package name to determine if the application has been installed or not.
The general naming is:

com.companyname.applicationname

eg:

com.android.Camera

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

For PHP 7 in Ubuntu you can also do:

sudo apt-get install php7.0-pgsql

So, now you can do not uncomment lines in php.ini

UPD: I have a same error, so problem was not in driver. I changed my database.ini, but every time I saw an error. And I change database config in .env and errors gone.

Android LinearLayout Gradient Background

You can used a custom view to do that. With this solution, it's finished the gradient shapes of all colors in your projects:

class GradientView(context: Context, attrs: AttributeSet) : View(context, attrs) {

    // Properties
    private val paint: Paint = Paint()
    private val rect = Rect()

    //region Attributes
    var start: Int = Color.WHITE
    var end: Int = Color.WHITE
    //endregion

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        // Update Size
        val usableWidth = width - (paddingLeft + paddingRight)
        val usableHeight = height - (paddingTop + paddingBottom)
        rect.right = usableWidth
        rect.bottom = usableHeight
        // Update Color
        paint.shader = LinearGradient(0f, 0f, width.toFloat(), 0f,
                start, end, Shader.TileMode.CLAMP)
        // ReDraw
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawRect(rect, paint)
    }

}

I also create an open source project GradientView with this custom view:

https://github.com/lopspower/GradientView

implementation 'com.mikhaellopez:gradientview:1.1.0'

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

You don't specify which OS.

Under Windows (for my application - a long running risk management application) we observed that we could go no further than 1280MB on Windows 32bit. I doubt that running a 32bit JVM under 64bit would make any difference.

We ported the app to Linux and we are running a 32bit JVM on 64bit hardware and have had a 2.2GB VM running pretty easily.

The biggest problem you may have is GC depending on what you are using memory for.

laravel select where and where condition

You either need to use first() or get() to fetch the results :

$userRecord = $this->where('email', $email)->where('password', $password)->first();

You most likely need to use first() as you want only one result returned.

If the record isn't found null will be returned. If you are building this query from inside an Eloquent class you could use self .

for example :

$userRecord = self::where('email', $email)->where('password', $password)->first();

More info here

Ansible: get current target host's IP address

Plain ansible_default_ipv4.address might not be what you think in some cases, use:

ansible_default_ipv4.address|default(ansible_all_ipv4_addresses[0])

Different ways of clearing lists

another solution that works fine is to create empty list as a reference empty list.

empt_list = []

for example you have a list as a_list = [1,2,3]. To clear it just make the following:

a_list = list(empt_list)

this will make a_list an empty list just like the empt_list.

onchange event for html.dropdownlist

try this :

@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem() 
{ Text = "Newest to Oldest", Value = "0" }, new SelectListItem() 
{ Text = "Oldest to Newest", Value = "1" }},
new { onchange = "document.location.href = '/ControllerName/ActionName?id=' + this.options[this.selectedIndex].value;" })

How to put data containing double-quotes in string variable?

You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:

Dim MyVar as string = "some text ""hello"" "

This will give the MyVar variable a value of some text "hello".

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

you can make a function like this

function translateTo($language, $word) {  
   define('defaultLang','english');  
   if (isset($lang[$language][$word]) == FALSE)  
      return $lang[$language][$word];  
   else  
      return $lang[defaultLang][$word];  
}

Is there a way to ignore a single FindBugs warning?

At the time of writing this (May 2018), FindBugs seems to have been replaced by SpotBugs. Using the SuppressFBWarnings annotation requires your code to be compiled with Java 8 or later and introduces a compile time dependency on spotbugs-annotations.jar.

Using a filter file to filter SpotBugs rules has no such issues. The documentation is here.

JavaScript: client-side vs. server-side validation

I came across an interesting link that make a distinction between gross, systematic, random errors.

Client-Side validation suits perfectly for preventing gross and random errors. Typically a max length for texture and input. Do not mimic the server-side validation rule; provide your own gross, rule of thumb validation rule (ex. 200 characters on client-side; n on server-side dictated by a strong business rule).

Server-side validation suits perfectly for preventing systematic errors; it will enforce business rules.

In a project I'm involved in, the validation is done on the server through ajax requests. On the client I display error messages accordingly.

Further reading: gross, systematic, random errors:

https://answers.yahoo.com/question/index?qid=20080918203131AAEt6GO

How can I get session id in php and show it?

session_start();    
echo session_id();

Transmitting newline character "\n"

Try using %0A in the URL, just like you've used %20 instead of the space character.

Find and replace in file and overwrite file doesn't work, it empties the file

To change multiple files (and saving a backup of each as *.bak):

perl -p -i -e "s/\|/x/g" *  

will take all files in directory and replace | with x this is called a “Perl pie” (easy as a pie)

How to replace item in array?

Here is the basic answer made into a reusable function:

function arrayFindReplace(array, findValue, replaceValue){
    while(array.indexOf(findValue) !== -1){
        let index = array.indexOf(findValue);
        array[index] = replaceValue;
    }
}

Accessing a class' member variables in Python?

The answer, in a few words

In your example, itsProblem is a local variable.

Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

But if you want a true class variable, then use the class name directly:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

But be careful with this one, as theExample.itsProblem is automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

Some explanations

In Python, variables can be created dynamically. Therefore, you can do the following:

class Example(object):
    pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem 

prints

True

Therefore, that's exactly what you do with the previous examples.

Indeed, in Python we use self as this, but it's a bit more than that. self is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self or not.

Which means you can do:

class Example(object):
    def __init__(self):
        self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

or:

class Example(object):
    def __init__(my_super_self):
        my_super_self.itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

It's exactly the same. The first argument of ANY object method is the current object, we only call it self as a convention. And you add just a variable to this object, the same way you would do it from outside.

Now, about the class variables.

When you do:

class Example(object):
    itsProblem = "problem"


theExample = Example()
print(theExample.itsProblem)

You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?

Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

As a conclusion, never use class variables to set default values to object variables. Use __init__ for that.

Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.

OpenCV & Python - Image too big to display

Looks like opencv lib is pretty sensitive to parameters passed to the methods. The following code worked for me using opencv 4.3.0:

win_name = "visualization"  #  1. use var to specify window name everywhere
cv2.namedWindow(win_name, cv2.WINDOW_NORMAL)  #  2. use 'normal' flag
img = cv2.imread(filename)
h,w = img.shape[:2]  #  suits for image containing any amount of channels
h = int(h / resize_factor)  #  one must compute beforehand
w = int(w / resize_factor)  #  and convert to INT
cv2.resizeWindow(win_name, w, h)  #  use variables defined/computed BEFOREHAND
cv2.imshow(win_name, img)

Decimal precision and scale in EF Code First

Entity Framework Ver 6 (Alpha, rc1) has something called Custom Conventions. To set decimal precision:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Properties<decimal>().Configure(config => config.HasPrecision(18, 4));
}

Reference:

Cygwin Make bash command not found

I faced the same problem. Follow these steps:

  1. Goto the installer once again.
  2. Do the initial setup.
  3. Select all the libraries by clicking and selecting install (the one already installed will show reinstall, so don't install them).
  4. Click next.
  5. The installation will take some time.

Could not insert new outlet connection: Could not find any information for the class named

Here are the steps solved for me:

  1. Remove Class name reference from View(storyboard/xib) and save;
  2. Add Class name again and save;
  3. Clean and Build;

Done !

Android Studio: Default project directory

I have Android Studio version 3.1.2, it shows project full path when you click Build tab in bottom-left location of the studio.

enter image description here

Using an authorization header with Fetch in React Native

Example fetch with authorization header:

fetch('URL_GOES_HERE', { 
   method: 'post', 
   headers: new Headers({
     'Authorization': 'Basic '+btoa('username:password'), 
     'Content-Type': 'application/x-www-form-urlencoded'
   }), 
   body: 'A=1&B=2'
 });

Connect HTML page with SQL server using javascript

JavaScript is a client-side language and your MySQL database is going to be running on a server.

So you have to rename your file to index.php for example (.php is important) so you can use php code for that. It is not very difficult, but not directly possible with html.

(Somehow you can tell your server to let the html files behave like php files, but this is not the best solution.)

So after you renamed your file, go to the very top, before <html> or <!DOCTYPE html> and type:

<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        /*Creating variables*/
        $name = $_POST["name"];
        $address = $_POST["address"];
        $age = $_POST["age"];


        $dbhost = "localhost"; /*most of the time it's localhost*/
        $username = "yourusername";
        $password = "yourpassword";
        $dbname = "mydatabase";

        $mysql = mysqli_connect($dbhost, $username, $password, $dbname); //It connects
        $query = "INSERT INTO yourtable (name,address,age) VALUES $name, $address, $age";
        mysqli_query($mysql, $query);
    }
?>
<!DOCTYPE html>
<html>
<head>.......
....
    <form method="post">
        <input name="name" type="text"/>
        <input name="address" type="text"/>
        <input name="age" type="text"/>
    </form>
....

Open another application from your own (intent)

Alternatively you can also open the intent from your app in the other app with:

Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

where uri is the deeplink to the other app

iTunes Connect: How to choose a good SKU?

Might be answer is late but look at Simple Information of SKU (Stock keeping unit) number is, it's an unique tracking number (an arbi­trary num­ber) that are used in appStore for your application. You can put what­ever you want in there as long as it is unique among your appli­ca­tions. Try to fol­low a pat­tern for the SKU Num­ber of your apps so that you will be able to bet­ter orga­nize them. I sug­gest a com­bi­na­tion of the cur­rent year + month + ID for your app. So if you’re devel­op­ing your first appli­ca­tion on september 1991 (oh,, yah it's my b'day's month and year :D ), you could put your SKU Num­ber as “19910901”. Here, I am just suggesting you for this pattern but you can take/choose any pattern which easy for you.

The endpoint reference (EPR) for the Operation not found is

By removing cache wsdl-* files in /tmp folder, my problem was solved

see https://www.drupal.org/node/1132926#comment-6283348

be careful about permission to delete

I'm in ubuntu os

Purpose of "%matplotlib inline"

Provided you are running Jupyter Notebook, the %matplotlib inline command will make your plot outputs appear in the notebook, also can be stored.

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

Fluid width with equally spaced DIVs

Other posts have mentioned flexbox, but if more than one row of items is necessary, flexbox's space-between property fails (see the end of the post)

To date, the only clean solution for this is with the

CSS Grid Layout Module (Codepen demo)

Basically the relevant code necessary boils down to this:

ul {
  display: grid; /* (1) */
  grid-template-columns: repeat(auto-fit, 120px); /* (2) */
  grid-gap: 1rem; /* (3) */
  justify-content: space-between; /* (4) */
  align-content: flex-start; /* (5) */
}

1) Make the container element a grid container

2) Set the grid with an 'auto' amount of columns - as necessary. This is done for responsive layouts. The width of each column will be 120px. (Note the use of auto-fit (as apposed to auto-fill) which (for a 1-row layout) collapses empty tracks to 0 - allowing the items to expand to take up the remaining space. (check out this demo to see what I'm talking about) ).

3) Set gaps/gutters for the grid rows and columns - here, since want a 'space-between' layout - the gap will actually be a minimum gap because it will grow as necessary.

4) and 5) - Similar to flexbox.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
ul {_x000D_
  display: grid;_x000D_
  grid-template-columns: repeat(auto-fit, 120px);_x000D_
  grid-gap: 1rem;_x000D_
  justify-content: space-between;_x000D_
  align-content: flex-start;_x000D_
  _x000D_
  /* boring properties: */_x000D_
  list-style: none;_x000D_
  width: 90vw;_x000D_
  height: 90vh;_x000D_
  margin: 2vh auto;_x000D_
  border: 5px solid green;_x000D_
  padding: 0;_x000D_
  overflow: auto;_x000D_
}_x000D_
li {_x000D_
  background: tomato;_x000D_
  height: 120px;_x000D_
}
_x000D_
<ul>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Codepen demo (Resize to see the effect)


Browser Support - Caniuse

Currently supported by Chrome (Blink), Firefox, Safari and Edge! ... with partial support from IE (See this post by Rachel Andrew)


NB:

Flexbox's space-between property works great for one row of items, but when applied to a flex container which wraps it's items - (with flex-wrap: wrap) - fails, because you have no control over the alignment of the last row of items; the last row will always be justified (usually not what you want)

To demonstrate:

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
ul {_x000D_
  _x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  flex-wrap: wrap;_x000D_
  align-content: flex-start;_x000D_
  _x000D_
  list-style: none;_x000D_
  width: 90vw;_x000D_
  height: 90vh;_x000D_
  margin: 2vh auto;_x000D_
  border: 5px solid green;_x000D_
  padding: 0;_x000D_
  overflow: auto;_x000D_
  _x000D_
}_x000D_
li {_x000D_
  background: tomato;_x000D_
  width: 110px;_x000D_
  height: 80px;_x000D_
  margin-bottom: 1rem;_x000D_
}
_x000D_
<ul>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Codepen (Resize to see what i'm talking about)


Further reading on CSS grids:

Location of Django logs and errors

Add to your settings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': 'debug.log',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

And it will create a file called debug.log in the root of your. https://docs.djangoproject.com/en/1.10/topics/logging/

jQuery select2 get value of select tag?

Other answers wasn't working for me so i developed solution:

I created option with class="option-item" for easy targeting

HTML :

<select id="select-test">
<option value="5-val" id="first-id" class="option-item"> First option </option>
</select>

Then for every selected option i added display none property

CSS:

option:checked {
   display: none;
}

Now we can add change to our SelectBox to find our selected option with display none property by simple :hidden attribute

JQuery:

$('#select-test').change(function(){
//value 
    $('#select-test').find('.option-item:hidden').val();
//id
    $('#select-test').find('.option-item:hidden').attr('id');
//text
    $('#select-test').find('.option-item:hidden').text();
});

Working fiddle: https://jsfiddle.net/Friiz/2dk4003j/10/

How to implement drop down list in flutter?

place the value inside the items.then it will work,

new DropdownButton<String>(
              items:_dropitems.map((String val){
                return DropdownMenuItem<String>(
                  value: val,
                  child: new Text(val),
                );
              }).toList(),
              hint:Text(_SelectdType),
              onChanged:(String val){
                _SelectdType= val;
                setState(() {});
                })

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

Define your own parse format string to use.

string formatString = "yyyyMMddHHmmss";
string sample = "20100611221912";
DateTime dt = DateTime.ParseExact(sample,formatString,null);

In case you got a datetime having milliseconds, use the following formatString

string format = "yyyyMMddHHmmssfff"
string dateTime = "20140123205803252";
DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture);

Thanks

CSS smooth bounce animation

The long rest in between is due to your keyframe settings. Your current keyframe rules mean that the actual bounce happens only between 40% - 60% of the animation duration (that is, between 1s - 1.5s mark of the animation). Remove those rules and maybe even reduce the animation-duration to suit your needs.

_x000D_
_x000D_
.animated {_x000D_
  -webkit-animation-duration: .5s;_x000D_
  animation-duration: .5s;_x000D_
  -webkit-animation-fill-mode: both;_x000D_
  animation-fill-mode: both;_x000D_
  -webkit-animation-timing-function: linear;_x000D_
  animation-timing-function: linear;_x000D_
  animation-iteration-count: infinite;_x000D_
  -webkit-animation-iteration-count: infinite;_x000D_
}_x000D_
@-webkit-keyframes bounce {_x000D_
  0%, 100% {_x000D_
    -webkit-transform: translateY(0);_x000D_
  }_x000D_
  50% {_x000D_
    -webkit-transform: translateY(-5px);_x000D_
  }_x000D_
}_x000D_
@keyframes bounce {_x000D_
  0%, 100% {_x000D_
    transform: translateY(0);_x000D_
  }_x000D_
  50% {_x000D_
    transform: translateY(-5px);_x000D_
  }_x000D_
}_x000D_
.bounce {_x000D_
  -webkit-animation-name: bounce;_x000D_
  animation-name: bounce;_x000D_
}_x000D_
#animated-example {_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  background-color: red;_x000D_
  position: relative;_x000D_
  top: 100px;_x000D_
  left: 100px;_x000D_
  border-radius: 50%;_x000D_
}_x000D_
hr {_x000D_
  position: relative;_x000D_
  top: 92px;_x000D_
  left: -300px;_x000D_
  width: 200px;_x000D_
}
_x000D_
<div id="animated-example" class="animated bounce"></div>_x000D_
<hr>
_x000D_
_x000D_
_x000D_


Here is how your original keyframe settings would be interpreted by the browser:

  • At 0% (that is, at 0s or start of animation) - translate by 0px in Y axis.
  • At 20% (that is, at 0.5s of animation) - translate by 0px in Y axis.
  • At 40% (that is, at 1s of animation) - translate by 0px in Y axis.
  • At 50% (that is, at 1.25s of animation) - translate by 5px in Y axis. This results in a gradual upward movement.
  • At 60% (that is, at 1.5s of animation) - translate by 0px in Y axis. This results in a gradual downward movement.
  • At 80% (that is, at 2s of animation) - translate by 0px in Y axis.
  • At 100% (that is, at 2.5s or end of animation) - translate by 0px in Y axis.

How to build minified and uncompressed bundle with webpack?

I had the same issue, and had to satisfy all these requirements:

  • Minified + Non minified version (as in the question)
  • ES6
  • Cross platform (Windows + Linux).

I finally solved it as follows:

webpack.config.js:

const path = require('path');
const MinifyPlugin = require("babel-minify-webpack-plugin");

module.exports = getConfiguration;

function getConfiguration(env) {
    var outFile;
    var plugins = [];
    if (env === 'prod') {
        outFile = 'mylib.dev';
        plugins.push(new MinifyPlugin());
    } else {
        if (env !== 'dev') {
            console.log('Unknown env ' + env + '. Defaults to dev');
        }
        outFile = 'mylib.dev.debug';
    }

    var entry = {};
    entry[outFile] = './src/mylib-entry.js';

    return {
        entry: entry,
        plugins: plugins,
        output: {
            filename: '[name].js',
            path: __dirname
        }
    };
}

package.json:

{
    "name": "mylib.js",
    ...
    "scripts": {
        "build": "npm-run-all webpack-prod webpack-dev",
        "webpack-prod": "npx webpack --env=prod",
        "webpack-dev": "npx webpack --env=dev"
    },
    "devDependencies": {
        ...
        "babel-minify-webpack-plugin": "^0.2.0",
        "npm-run-all": "^4.1.2",
        "webpack": "^3.10.0"
    }
}

Then I can build by (Don't forget to npm install before):

npm run-script build

What are some uses of template template parameters?

In the solution with variadic templates provided by pfalcon, I found it difficult to actually specialize the ostream operator for std::map due to the greedy nature of the variadic specialization. Here's a slight revision which worked for me:

#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <map>

namespace containerdisplay
{
  template<typename T, template<class,class...> class C, class... Args>
  std::ostream& operator <<(std::ostream& os, const C<T,Args...>& objs)
  {
    std::cout << __PRETTY_FUNCTION__ << '\n';
    for (auto const& obj : objs)
      os << obj << ' ';
    return os;
  }  
}

template< typename K, typename V>
std::ostream& operator << ( std::ostream& os, 
                const std::map< K, V > & objs )
{  

  std::cout << __PRETTY_FUNCTION__ << '\n';
  for( auto& obj : objs )
  {    
    os << obj.first << ": " << obj.second << std::endl;
  }

  return os;
}


int main()
{

  {
    using namespace containerdisplay;
    std::vector<float> vf { 1.1, 2.2, 3.3, 4.4 };
    std::cout << vf << '\n';

    std::list<char> lc { 'a', 'b', 'c', 'd' };
    std::cout << lc << '\n';

    std::deque<int> di { 1, 2, 3, 4 };
    std::cout << di << '\n';
  }

  std::map< std::string, std::string > m1 
  {
      { "foo", "bar" },
      { "baz", "boo" }
  };

  std::cout << m1 << std::endl;

    return 0;
}

How do I access (read, write) Google Sheets spreadsheets with Python?

This thread seems to be quite old. If anyone's still looking, the steps mentioned here : https://github.com/burnash/gspread work very well.

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os

os.chdir(r'your_path')

scope = ['https://spreadsheets.google.com/feeds',
     'https://www.googleapis.com/auth/drive']

creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
gc = gspread.authorize(creds)
wks = gc.open("Trial_Sheet").sheet1
wks.update_acell('H3', "I'm here!")

Make sure to drop your credentials json file in your current directory. Rename it as client_secret.json.

You might run into errors if you don't enable Google Sheet API with your current credentials.

Counting array elements in Perl

print scalar grep { defined $_ } @a;

sed edit file in place

The -i option streams the edited content into a new file and then renames it behind the scenes, anyway.

Example:

sed -i 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename

and

sed -i '' 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename

on macOS.

What is the preferred syntax for defining enums in JavaScript?

This isn't much of an answer, but I'd say that works just fine, personally

Having said that, since it doesn't matter what the values are (you've used 0, 1, 2), I'd use a meaningful string in case you ever wanted to output the current value.

jQuery selector regular expressions

If your use of regular expression is limited to test if an attribut start with a certain string, you can use the ^ JQuery selector.

For example if your want to only select div with id starting with "abc", you can use:

$("div[id^='abc']")

A lot of very useful selectors to avoid use of regex can be find here: http://api.jquery.com/category/selectors/attribute-selectors/

How to list branches that contain a given commit?

You may run:

git log <SHA1>..HEAD --ancestry-path --merges

From comment of last commit in the output you may find original branch name

Example:

       c---e---g--- feature
      /         \
-a---b---d---f---h---j--- master

git log e..master --ancestry-path --merges

commit h
Merge: g f
Author: Eugen Konkov <>
Date:   Sat Oct 1 00:54:18 2016 +0300

    Merge branch 'feature' into master

Java2D: Increase the line width

You should use setStroke to set a stroke of the Graphics2D object.

The example at http://www.java2s.com gives you some code examples.

The following code produces the image below:

import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;

public class FrameTest {
    public static void main(String[] args) {
        JFrame jf = new JFrame("Demo");
        Container cp = jf.getContentPane();
        cp.add(new JComponent() {
            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setStroke(new BasicStroke(10));
                g2.draw(new Line2D.Float(30, 20, 80, 90));
            }
        });
        jf.setSize(300, 200);
        jf.setVisible(true);
    }
}

enter image description here

(Note that the setStroke method is not available in the Graphics object. You have to cast it to a Graphics2D object.)


This post has been rewritten as an article here.

dropdownlist set selected value in MVC3 Razor

Replace below line with new updated working code:

@Html.DropDownList("NewsCategoriesID", (SelectList)ViewBag.NewsCategoriesID)

Now Implement new updated working code:

@Html.DropDownListFor(model => model.NewsCategoriesID, ViewBag.NewsCategoriesID as List<SelectListItem>, new {name = "NewsCategoriesID", id = "NewsCategoriesID" })

How would one write object-oriented code in C?

Sure that is possible. This is what GObject, the framework that all of GTK+ and GNOME is based on, does.

Get selected element's outer HTML

node.cloneNode() hardly seems like a hack. You can clone the node and append it to any desired parent element, and also manipulate it by manipulating individual properties, rather than having to e.g. run regular expressions on it, or add it in to the DOM, then manipulate it afterwords.

That said, you could also iterate over the attributes of the element to construct an HTML string representation of it. It seems likely this is how any outerHTML function would be implemented were jQuery to add one.

How to loop through a collection that supports IEnumerable?

or even a very classic old fashion method

IEnumerable<string> collection = new List<string>() { "a", "b", "c" };

for(int i = 0; i < collection.Count(); i++) 
{
    string str1 = collection.ElementAt(i);
    // do your stuff   
}

maybe you would like this method also :-)

How to style a clicked button in CSS

Unfortunately, there is no :click pseudo selector. If you want to change styling on click, you should use Jquery/Javascript. It certainly is better than the "hack" for pure HTML / CSS. But if you insist...

_x000D_
_x000D_
input {_x000D_
display: none;_x000D_
}_x000D_
span {_x000D_
padding: 20px;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
input:checked + span {_x000D_
  background: #444;_x000D_
  color: #fff;_x000D_
}
_x000D_
  <label for="input">_x000D_
  <input id="input" type="radio" />_x000D_
  <span>NO JS styling</span>_x000D_
  </label>
_x000D_
_x000D_
_x000D_

Or, if you prefer, you can toggle the styling:

_x000D_
_x000D_
input {_x000D_
display: none;_x000D_
}_x000D_
span {_x000D_
padding: 20px;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
input:checked + span {_x000D_
  background: #444;_x000D_
  color: #fff;_x000D_
}
_x000D_
  <label for="input">_x000D_
  <input id="input" type="checkbox" />_x000D_
  <span>NO JS styling</span>_x000D_
  </label>
_x000D_
_x000D_
_x000D_

How to create a new file in unix?

Try > workdirectory/filename.txt

This would:

  • truncate the file if it exists
  • create if it doesn't exist

You can consider it equivalent to:

rm -f workdirectory/filename.txt; touch workdirectory/filename.txt

What is an opaque response, and what purpose does it serve?

Opaque responses can't be accessed by JavaScript, but you can still cache them with the Cache API and respond with them in the fetch event handler in a service worker. So they're useful for making your app offline, also for resources that you can't control (e.g. resources on a CDN that doesn't set the CORS headers).

Rename column SQL Server 2008

Or you could just slow-click twice on the column in SQL Management Studio and rename it through the UI...

Why does the program give "illegal start of type" error?

You have a misplaced closing brace before the return statement.

ggplot2 legend to bottom and horizontal

Here is how to create the desired outcome:

library(reshape2); library(tidyverse)
melt(outer(1:4, 1:4), varnames = c("X1", "X2")) %>%
ggplot() + 
  geom_tile(aes(X1, X2, fill = value)) + 
  scale_fill_continuous(guide = guide_legend()) +
  theme(legend.position="bottom",
        legend.spacing.x = unit(0, 'cm'))+
  guides(fill = guide_legend(label.position = "bottom"))

Created on 2019-12-07 by the reprex package (v0.3.0)


Edit: no need for these imperfect options anymore, but I'm leaving them here for reference.

Two imperfect options that don't give you exactly what you were asking for, but pretty close (will at least put the colours together).

library(reshape2); library(tidyverse)
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
 theme(legend.position="bottom", legend.direction="vertical")

p1 + scale_fill_continuous(guide = "colorbar") + theme(legend.position="bottom")

Created on 2019-02-28 by the reprex package (v0.2.1)

How do I "select Android SDK" in Android Studio?

The simplest solution for this problem:

First make sure your sdk path is currect. Then Please close current project and in android startup menu click on import project and choose your project from explorer. This will always solve my problem

Could not load file or assembly Exception from HRESULT: 0x80131040

If your solution contains two projects interacting with each other and both using one same reference, And if version of respective reference is different in both projects; Then also such errors occurred. Keep updating all references to latest one.

Difference between JSONObject and JSONArray

The usage of both can be depended on the structure of your data.

Simply, You can use the Nested Objects approach if you plan to give priority to a unique identifier such as a Primary Key.

eg:

  {
     "Employees" : {
           "001" : {
               "Name" : "Alan",
               "Children" : ["Walker", "Dua", "Lipa"]
                },
           "002" : {
               "Name" : "Ezio",
               "Children" : ["Kenvey", "Connor", "Edward"]
                }
      }

Or, Use the Array first approach if you intend to store a set of values with no need to identify uniquely.

eg:

 [
     {
        "Employees":[
               {
                   "Name" : "Alan",
                   "Children" : ["Walker", "Dua", "Lipa"]
               },
               {
                   "Name" : "Ezio",
                   "Children" : ["Kenvey", "Connor", "Edward"]
               }
          ]
       }
   ]

Although you could use the second method with an identifier, it can be harder or too complex to query and understand in some scenarios. Also depending on the database one may have to apply a suitable approach. Eg: MongoDB / Firebase

No connection could be made because the target machine actively refused it 127.0.0.1:3446

If you use WCF storm, can you even log-in to the WCF service endpoint? If not, and you are hosting it in a Windows service, you probably forgot to register that namespace. It's not very well advertised that this step is required, and it is actually annoying to do.

I use this tool to do this; it automates all those cumbersome steps.

Splitting a Java String by the pipe symbol using split("|")

test.split("\\|",999);

Specifing a limit or max will be accurate for examples like: "boo|||a" or "||boo|" or " |||"

But test.split("\\|"); will return different length strings arrays for the same examples.

use reference: link

Recursively looping through an object to build a property list

Here is a simple solution. This is a late answer but may be simple one-

_x000D_
_x000D_
const data = {
  city: 'foo',
  year: 2020,
  person: {
    name: {
      firstName: 'john',
      lastName: 'doe'
    },
    age: 20,
    type: {
      a: 2,
      b: 3,
      c: {
        d: 4,
        e: 5
      }
    }
  },
}

function getKey(obj, res = [], parent = '') {
  const keys = Object.keys(obj);
  
  /** Loop throw the object keys and check if there is any object there */
  keys.forEach(key => {
    if (typeof obj[key] !== 'object') {
      // Generate the heirarchy
      parent ? res.push(`${parent}.${key}`) : res.push(key);
    } else {
      // If object found then recursively call the function with updpated parent
      let newParent = parent ? `${parent}.${key}` : key;
      getKey(obj[key], res, newParent);
    }
    
  });
}

const result = [];

getKey(data, result, '');

console.log(result);
_x000D_
.as-console-wrapper{min-height: 100%!important; top: 0}
_x000D_
_x000D_
_x000D_

Get average color of image via Javascript

As pointed out in other answers, often what you really want the dominant color as opposed to the average color which tends to be brown. I wrote a script that gets the most common color and posted it on this gist

Java, How to get number of messages in a topic in apache kafka

In most recent versions of Kafka Manager, there is a column titled Summed Recent Offsets.

enter image description here

Is Google Play Store supported in avd emulators?

Starting from Android Studio 2.3.2 now you can create an AVD that has Play Store pre-installed on it. Currently, it is supported on the AVD's running

  • A device definition of Nexus 5 or 5X phone, or any Android Wear
  • A system image since Android 7.0 (API 24)

Official Source

For other emulators, you can try the solution mentioned in this answer.

Sass - Converting Hex to RGBa for background opacity

SASS has a built-in rgba() function to evaluate values.

rgba($color, $alpha)

E.g.

rgba(#00aaff, 0.5) => rgba(0, 170, 255, 0.5)

An example using your own variables:

$my-color: #00aaff;
$my-opacity: 0.5;

.my-element {
  color: rgba($my-color, $my-opacity);
}

Outputs:

.my-element {
  color: rgba(0, 170, 255, 0.5);
}

how to configuring a xampp web server for different root directory

# Possible values for the Options directive are "None", "All",
# or any combination of:
#   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important.  Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks Includes ExecCGI

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
AllowOverride All

#
# Controls who can get stuff from this server.
#
Require all granted

Write above code inside following tags < Directory "c:\projects" > < / Directory > c:(you can add any directory d: e:) is drive where you have created your project folder.

Alias /projects "c:\projects"

Now you can access the pr0jects directory on your browser :

localhost/projects/

How to change spinner text size and text color?

Simple and crisp...:

private OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

       ((TextView) parent.getChildAt(0)).setTextColor(Color.BLUE);
       ((TextView) parent.getChildAt(0)).setTextSize(5);

    }

    public void onNothingSelected(AdapterView<?> parent) {

    }
};

Uncaught TypeError: undefined is not a function on loading jquery-min.js

I had this problem recently with the jQuery Validation plug-in, using Squishit, also getting the js error:

"undefined is not a function"

I fixed it by changing the reference to the unminified jquery.validate.js file, rather than jquery.validate.min.js.

@MvcHtmlString.Create(
    @SquishIt.Framework.Bundle.JavaScript()
        .Add("~/Scripts/Libraries/jquery-1.8.2.min.js")
        .Add("~/Scripts/Libraries/jquery-ui-1.9.1.custom.min.js")
        .Add("~/Scripts/Libraries/jquery.unobtrusive-ajax.min.js")
        .Add("~/Scripts/Libraries/jquery.validate.js")
        .Add("~/Scripts/Libraries/jquery.validate.unobtrusive.js")
         ... more files

I think that the minified version of certain files, when further compressed using Squishit, for example, might in some cases not deal with missing semi-colons and the like, as @Dustin suggests, so you might have to experiment with which files you can doubly compress, and which you just leave to Squishit or whatever you're bundling with.

How do you send a Firebase Notification to all devices via CURL?

Your can send notification to all devices using "/topics/all"

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to": "/topics/all",
  "notification":{ "title":"Notification title", "body":"Notification body", "sound":"default", "click_action":"FCM_PLUGIN_ACTIVITY", "icon":"fcm_push_icon" },
  "data": {
    "message": "This is a Firebase Cloud Messaging Topic Message!",
   }
}

Exception: Can't bind to 'ngFor' since it isn't a known native property

For me, to cut a long story short, I had inadvertently downgraded to angular-beta-16.

The let ... syntax is ONLY valid in 2.0.0-beta.17+

If you try the let syntax on anything below this version. You will generate this error.

Either upgrade to angular-beta-17 or use the #item in items syntax.

Creating multiline strings in JavaScript

Just tried the Anonymous answer and found there's a little trick here, it doesn't work if there's a space after backslash \
So the following solution doesn't work -

var x = { test:'<?xml version="1.0"?>\ <-- One space here
            <?mso-application progid="Excel.Sheet"?>' 
};

But when space is removed it works -

var x = { test:'<?xml version="1.0"?>\<-- No space here now
          <?mso-application progid="Excel.Sheet"?>' 
};

alert(x.test);?

Hope it helps !!

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

Try the command

sudo mysql_secure_installation

press enter and assign a new password for root in mysql/mariadb.

If you get an error like

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

enable the service with

service mysql start

now if you re-enter with

mysql -u root -p

if you follow the problem enter with sudo su and mysql -u root -p now apply permissions to root

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '<password>';

this fixed my problem in MariaDB.

Good luck

SQLite string contains other string query

Using LIKE:

SELECT *
  FROM TABLE
 WHERE column LIKE '%cats%'  --case-insensitive

What is the Difference Between read() and recv() , and Between send() and write()?

Another thing on linux is:

send does not allow to operate on non-socket fd. Thus, for example to write on usb port, write is necessary.

How to change button color with tkinter

When you do self.button = Button(...).grid(...), what gets assigned to self.button is the result of the grid() command, not a reference to the Button object created.

You need to assign your self.button variable before packing/griding it. It should look something like this:

self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)

RecyclerView expand/collapse items

I am surprised that there's no concise answer yet, although such an expand/collapse animation is very easy to achieve with just 2 lines of code:

(recycler.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false // called once

together with

notifyItemChanged(position) // in adapter, whenever a child view in item's recycler gets hidden/shown

So for me, the explanations in the link below were really useful: https://medium.com/@nikola.jakshic/how-to-expand-collapse-items-in-recyclerview-49a648a403a6

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class

EDIT

Think it should be:

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
    ->where('c.username = :username')
    ->andWhere('p.phone = :phone');

    $qb->setParameters(array(
        'username' => $username,
        'phone' => $phone->getPhone(),
    ));

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

Javascript - check array for value

If you don't care about legacy browsers:

if ( bank_holidays.indexOf( '06/04/2012' ) > -1 )

if you do care about legacy browsers, there is a shim available on MDN. Otherwise, jQuery provides an equivalent function:

if ( $.inArray( '06/04/2012', bank_holidays ) > -1 )

How to remove new line characters from a string?

You want to use String.Replace to remove a character.

s = s.Replace("\n", String.Empty);
s = s.Replace("\r", String.Empty);
s = s.Replace("\t", String.Empty);

Note that String.Trim(params char[] trimChars) only removes leading and trailing characters in trimChars from the instance invoked on.

You could make an extension method, which avoids the performance problems of the above of making lots of temporary strings:

static string RemoveChars(this string s, params char[] removeChars) {
    Contract.Requires<ArgumentNullException>(s != null);
    Contract.Requires<ArgumentNullException>(removeChars != null);
    var sb = new StringBuilder(s.Length);
    foreach(char c in s) { 
        if(!removeChars.Contains(c)) {
            sb.Append(c);
        }
    }
    return sb.ToString();
}

Why is my method undefined for the type object?

It should be like that

public static void main(String[] args) {
        EchoServer0 e = new EchoServer0();
        // TODO Auto-generated method stub
        e.listen();
}

Your variable of type Object truly doesn't have such a method, but the type EchoServer0 you define above certainly has.

"Parse Error : There is a problem parsing the package" while installing Android application

Check whether your device supports the version you specified in minSdkVersion in AndroidManifest.xml . If not specify the lower version and try again

Using RegEX To Prefix And Append In Notepad++

Assuming alphanumeric words, you can use:

Search  = ^([A-Za-z0-9]+)$
Replace = able:"\1"

Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):

Search = ^(.+)$

^ points to the start of the line.
$ points to the end of the line.

\1 will be the source match within the parentheses.

How to define custom sort function in javascript?

or shorter

_x000D_
_x000D_
function sortBy(field) {_x000D_
  return function(a, b) {_x000D_
    return (a[field] > b[field]) - (a[field] < b[field])_x000D_
  };_x000D_
}_x000D_
_x000D_
let myArray = [_x000D_
    {tabid: 6237, url: 'https://reddit.com/r/znation'},_x000D_
    {tabid: 8430, url: 'https://reddit.com/r/soccer'},_x000D_
    {tabid: 1400, url: 'https://reddit.com/r/askreddit'},_x000D_
    {tabid: 3620, url: 'https://reddit.com/r/tacobell'},_x000D_
    {tabid: 5753, url: 'https://reddit.com/r/reddevils'},_x000D_
]_x000D_
_x000D_
myArray.sort(sortBy('url'));_x000D_
console.log(myArray);
_x000D_
_x000D_
_x000D_

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

Open the sql file in your text editor;

1. Search: utf8mb4_unicode_ci Replace: utf8_general_ci (Replace All)

2. Search: utf8mb4_unicode_520_ci Replace: utf8_general_ci (Replace All)

3. Search: utf8mb4 Replace: utf8 (Replace All)

Save and upload!

Android Google Maps API V2 Zoom to Current Location

check this out:

    fun requestMyGpsLocation(context: Context, callback: (location: Location) -> Unit) {
        val request = LocationRequest()
        //        request.interval = 10000
        //        request.fastestInterval = 5000
        request.numUpdates = 1
        request.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        val client = LocationServices.getFusedLocationProviderClient(context)

        val permission = ContextCompat.checkSelfPermission(context,
            Manifest.permission.ACCESS_FINE_LOCATION )
        if (permission == PackageManager.PERMISSION_GRANTED) {
            client.requestLocationUpdates(request, object : LocationCallback() {
                override fun onLocationResult(locationResult: LocationResult?) {
                val location = locationResult?.lastLocation
                if (location != null)
                    callback.invoke(location)
            }
         }, null)
       }
     }

and

    fun zoomOnMe() {
        requestMyGpsLocation(this) { location ->
            mMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(
                LatLng(location.latitude,location.longitude ), 13F ))
        }
    }

Django CSRF Cookie Not Set

This problem arose again recently due to a bug in Python itself.

http://bugs.python.org/issue22931

https://code.djangoproject.com/ticket/24280

Among the versions affected were 2.7.8 and 2.7.9. The cookie was not read correctly if one of the values contained a [ character.

Updating Python (2.7.10) fixes the problem.

How can I enable CORS on Django REST Framework

In case anyone is getting back to this question and deciding to write their own middleware, this is a code sample for Django's new style middleware -

class CORSMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response["Access-Control-Allow-Origin"] = "*"

        return response

How to check if a Docker image with a specific tag exist locally?

In case you are trying to search for a docker image from a docker registry, I guess the easiest way to check if a docker image is present is by using the Docker V2 REST API Tags list service

Example:-

curl $CURLOPTS -H "Authorization: Bearer $token" "https://hub.docker.com:4443/v2/your-repo-name/tags/list"

if the above result returns 200Ok with a list of image tags, then we know that image exists

{"name":"your-repo-name","tags":["1.0.0.1533677221","1.0.0.1533740305","1.0.0.1535659921","1.0.0.1535665433","latest"]}

else if you see something like

{"errors":[{"code":"NAME_UNKNOWN","message":"repository name not known to registry","detail":{"name":"your-repo-name"}}]} 

then you know for sure that image doesn't exist.

A html space is showing as %2520 instead of %20

A bit of explaining as to what that %2520 is :

The common space character is encoded as %20 as you noted yourself. The % character is encoded as %25.

The way you get %2520 is when your url already has a %20 in it, and gets urlencoded again, which transforms the %20 to %2520.

Are you (or any framework you might be using) double encoding characters?

Edit: Expanding a bit on this, especially for LOCAL links. Assuming you want to link to the resource C:\my path\my file.html:

  • if you provide a local file path only, the browser is expected to encode and protect all characters given (in the above, you should give it with spaces as shown, since % is a valid filename character and as such it will be encoded) when converting to a proper URL (see next point).
  • if you provide a URL with the file:// protocol, you are basically stating that you have taken all precautions and encoded what needs encoding, the rest should be treated as special characters. In the above example, you should thus provide file:///c:/my%20path/my%20file.html. Aside from fixing slashes, clients should not encode characters here.

NOTES:

  • Slash direction - forward slashes / are used in URLs, reverse slashes \ in Windows paths, but most clients will work with both by converting them to the proper forward slash.
  • In addition, there are 3 slashes after the protocol name, since you are silently referring to the current machine instead of a remote host ( the full unabbreviated path would be file://localhost/c:/my%20path/my%file.html ), but again most clients will work without the host part (ie two slashes only) by assuming you mean the local machine and adding the third slash.

How can I generate an MD5 hash?

I just downloaded commons-codec.jar and got perfect php like md5. Here is manual.

Just import it to your project and use

String Url = "your_url";

System.out.println( DigestUtils.md5Hex( Url ) );

and there you have it.

What is the difference between window, screen, and document in Javascript?

The window is the first thing that gets loaded into the browser. This window object has the majority of the properties like length, innerWidth, innerHeight, name, if it has been closed, its parents, and more.

The document object is your html, aspx, php, or other document that will be loaded into the browser. The document actually gets loaded inside the window object and has properties available to it like title, URL, cookie, etc. What does this really mean? That means if you want to access a property for the window it is window.property, if it is document it is window.document.property which is also available in short as document.property.

Popup window in winform c#

This is not so easy because basically popups are not supported in windows forms. Although windows forms is based on win32 and in win32 popup are supported. If you accept a few tricks, following code will set you going with a popup. You decide if you want to put it to good use :

class PopupWindow : Control
{
    private const int WM_ACTIVATE = 0x0006;
    private const int WM_MOUSEACTIVATE = 0x0021;

    private Control ownerControl;

    public PopupWindow(Control ownerControl)
        :base()
    {
        this.ownerControl = ownerControl;
        base.SetTopLevel(true);
    }

    public Control OwnerControl
    {
        get
        {
            return (this.ownerControl as Control);
        }
        set
        {
            this.ownerControl = value;
        }
    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams createParams = base.CreateParams;

            createParams.Style = WindowStyles.WS_POPUP |
                                 WindowStyles.WS_VISIBLE |
                                 WindowStyles.WS_CLIPSIBLINGS |
                                 WindowStyles.WS_CLIPCHILDREN |
                                 WindowStyles.WS_MAXIMIZEBOX |
                                 WindowStyles.WS_BORDER;
            createParams.ExStyle = WindowsExtendedStyles.WS_EX_LEFT |
                                   WindowsExtendedStyles.WS_EX_LTRREADING |
                                   WindowsExtendedStyles.WS_EX_RIGHTSCROLLBAR | 
                                   WindowsExtendedStyles.WS_EX_TOPMOST;

            createParams.Parent = (this.ownerControl != null) ? this.ownerControl.Handle : IntPtr.Zero;
            return createParams;
        }
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr SetActiveWindow(HandleRef hWnd);

    protected override void WndProc(ref Message m)
    {
        switch (m.Msg)
        {
            case WM_ACTIVATE:
                {
                    if ((int)m.WParam == 1)
                    {
                        //window is being activated
                        if (ownerControl != null)
                        {
                            SetActiveWindow(new HandleRef(this, ownerControl.FindForm().Handle));
                        }
                    }
                    break;
                }
            case WM_MOUSEACTIVATE:
                {
                    m.Result = new IntPtr(MouseActivate.MA_NOACTIVATE);
                    return;
                    //break;
                }
        }
        base.WndProc(ref m);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        e.Graphics.FillRectangle(SystemBrushes.Info, 0, 0, Width, Height);
        e.Graphics.DrawString((ownerControl as VerticalDateScrollBar).FirstVisibleDate.ToLongDateString(), this.Font, SystemBrushes.InfoText, 2, 2);
    }
}

Experiment with it a bit, you have to play around with its position and its size. Use it wrong and nothing shows.

Getting the parent of a directory in Bash

dir=/home/smith/Desktop/Test
parentdir="$(dirname "$dir")"

Works if there is a trailing slash, too.

How do you add a JToken to an JObject?

Just adding .First to your bananaToken should do it:
foodJsonObj["food"]["fruit"]["orange"].Parent.AddAfterSelf(bananaToken .First);
.First basically moves past the { to make it a JProperty instead of a JToken.

@Brian Rogers, Thanks I forgot the .Parent. Edited

How to make a div center align in HTML

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Center</title>_x000D_
  </head>_x000D_
  <body>_x000D_
_x000D_
    <div style="text-align: center;">_x000D_
      <div style="width: 500px; margin: 0 auto; background: #000; color: #fff;">This DIV is centered</div>_x000D_
    </div>_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Tested and worked in IE, Firefox, Chrome, Safari and Opera. I did not test IE6. The outer text-align is needed for IE. Other browsers (and IE9?) will work when you give the DIV margin (left and right) value of auto. Margin "0 auto" is a shorthand for margin "0 auto 0 auto" (top right bottom left).

Note: the text is also centered inside the inner DIV, if you want it to remain on the left side just specify text-align: left; for the inner DIV.

Edit: IE 6, 7, 8 and 9 running on the Standards Mode will work with margins set to auto.

Converting pfx to pem using openssl

Despite that the other answers are correct and thoroughly explained, I found some difficulties understanding them. Here is the method I used (Taken from here):

First case: To convert a PFX file to a PEM file that contains both the certificate and private key:

openssl pkcs12 -in filename.pfx -out cert.pem -nodes

Second case: To convert a PFX file to separate public and private key PEM files:

Extracts the private key form a PFX to a PEM file:

openssl pkcs12 -in filename.pfx -nocerts -out key.pem

Exports the certificate (includes the public key only):

openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem

Removes the password (paraphrase) from the extracted private key (optional):

openssl rsa -in key.pem -out server.key

php implode (101) with quotes

$array = array('lastname', 'email', 'phone');


echo "'" . implode("','", $array) . "'";

javascript regex : only english letters allowed

_x000D_
_x000D_
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
_x000D_
_x000D_

Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w covers a-zA-Z and some other word characters. It all depends on what you need specifically.

How to append a jQuery variable value inside the .html tag

See this Link

HTML

<div id="products"></div>

JS

var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
 };
 var name = $("<div/>",{"text":someone.name,"class":"name"
});

var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {   
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);

How to find longest string in the table column data

you have to do some changes by applying group by or query with in query.

"SELECT CITY,LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC LIMIT 1;"

it will return longest cityname from city.

What is a "static" function in C?

Minor nit: static functions are visible to a translation unit, which for most practical cases is the file the function is defined in. The error you are getting is commonly referred to as violation of the One Definition Rule.

The standard probably says something like:

"Every program shall contain exactly one definition of every noninline function or object that is used in that program; no diagnostic required."

That is the C way of looking at static functions. This is deprecated in C++ however.

In C++, additionally, you can declare member functions static. These are mostly metafunctions i.e. they do not describe/modify a particular object's behavior/state but act on the whole class itself. Also, this means that you do not need to create an object to call a static member function. Further, this also means, you only get access to static member variables from within such a function.

I'd add to Parrot's example the Singleton pattern which is based on this sort of a static member function to get/use a single object throughout the lifetime of a program.

Getting URL hash location, and using it in jQuery

I would suggest better cek first if the current page has a hash. Otherwise it will be undefined.

$(window).on('load', function(){        
    if( location.hash && location.hash.length ) {
       var hash = decodeURIComponent(location.hash.substr(1));
       $('ul'+hash+':first').show();;
    }       
});

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

How to do this in Laravel, subquery where in

Product::from('products as p')
->join('product_category as pc','p.id','=','pc.product_id')
->select('p.*')
->where('p.active',1)
->whereIn('pc.category_id', ['223', '15'])
->get();

onchange file input change img src and change image color

Below solution tested and its working, hope it will support in your project.
HTML code:
    <input type="file" name="asgnmnt_file" id="asgnmnt_file" class="span8" 
    style="display:none;" onchange="fileSelected(this)">
    <br><br>
    <img id="asgnmnt_file_img" src="uploads/assignments/abc.jpg" width="150" height="150" 
    onclick="passFileUrl()" style="cursor:pointer;">

JavaScript code:
    function passFileUrl(){
    document.getElementById('asgnmnt_file').click();
    }

    function fileSelected(inputData){
    document.getElementById('asgnmnt_file_img').src = window.URL.createObjectURL(inputData.files[0])
    }

AngularJS ui-router login authentication

I think you need a service that handle the authentication process (and its storage).

In this service you'll need some basic methods :

  • isAuthenticated()
  • login()
  • logout()
  • etc ...

This service should be injected in your controllers of each module :

  • In your dashboard section, use this service to check if user is authenticated (service.isAuthenticated() method) . if not, redirect to /login
  • In your login section, just use the form data to authenticate the user through your service.login() method

A good and robust example for this behavior is the project angular-app and specifically its security module which is based over the awesome HTTP Auth Interceptor Module

Hope this helps

How do I parse a URL query parameters, in Javascript?

You could get a JavaScript object containing the parameters with something like this:

var regex = /[?&]([^=#]+)=([^&#]*)/g,
    url = window.location.href,
    params = {},
    match;
while(match = regex.exec(url)) {
    params[match[1]] = match[2];
}

The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:

{v: "123", p: "hello"}

Here's a working example.

How do I define a method which takes a lambda as a parameter in Java 8?

You can use functional interfaces as mentioned above. below are some of the examples

Function<Integer, Integer> f1 = num->(num*2+1);
System.out.println(f1.apply(10));

Predicate<Integer> f2= num->(num > 10);
System.out.println(f2.test(10));
System.out.println(f2.test(11));

Supplier<Integer> f3= ()-> 100;
System.out.println(f3.get());

Hope it helps

php static function

After trying examples (PHP 5.3.5), I found that in both cases of defining functions you can't use $this operator to work on class functions. So I couldn't find a difference in them yet. :(

Java: Calling a super method which calls an overridden method

I think of it this way

+----------------+
|     super      |
+----------------+ <-----------------+
| +------------+ |                   |
| |    this    | | <-+               |
| +------------+ |   |               |
| | @method1() | |   |               |
| | @method2() | |   |               |
| +------------+ |   |               |
|    method4()   |   |               |
|    method5()   |   |               |
+----------------+   |               |
    We instantiate that class, not that one!

Let me move that subclass a little to the left to reveal what's beneath... (Man, I do love ASCII graphics)

We are here
        |
       /  +----------------+
      |   |     super      |
      v   +----------------+
+------------+             |
|    this    |             |
+------------+             |
| @method1() | method1()   |
| @method2() | method2()   |
+------------+ method3()   |
          |    method4()   |
          |    method5()   |
          +----------------+

Then we call the method
over here...
      |               +----------------+
 _____/               |     super      |
/                     +----------------+
|   +------------+    |    bar()       |
|   |    this    |    |    foo()       |
|   +------------+    |    method0()   |
+-> | @method1() |--->|    method1()   | <------------------------------+
    | @method2() | ^  |    method2()   |                                |
    +------------+ |  |    method3()   |                                |
                   |  |    method4()   |                                |
                   |  |    method5()   |                                |
                   |  +----------------+                                |
                   \______________________________________              |
                                                          \             |
                                                          |             |
...which calls super, thus calling the super's method1() here, so that that
method (the overidden one) is executed instead[of the overriding one].

Keep in mind that, in the inheritance hierarchy, since the instantiated
class is the sub one, for methods called via super.something() everything
is the same except for one thing (two, actually): "this" means "the only
this we have" (a pointer to the class we have instantiated, the
subclass), even when java syntax allows us to omit "this" (most of the
time); "super", though, is polymorphism-aware and always refers to the
superclass of the class (instantiated or not) that we're actually
executing code from ("this" is about objects [and can't be used in a
static context], super is about classes).

In other words, quoting from the Java Language Specification:

The form super.Identifier refers to the field named Identifier of the current object, but with the current object viewed as an instance of the superclass of the current class.

The form T.super.Identifier refers to the field named Identifier of the lexically enclosing instance corresponding to T, but with that instance viewed as an instance of the superclass of T.

In layman's terms, this is basically an object (*the** object; the very same object you can move around in variables), the instance of the instantiated class, a plain variable in the data domain; super is like a pointer to a borrowed block of code that you want to be executed, more like a mere function call, and it's relative to the class where it is called.

Therefore if you use super from the superclass you get code from the superduper class [the grandparent] executed), while if you use this (or if it's used implicitly) from a superclass it keeps pointing to the subclass (because nobody has changed it - and nobody could).

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

I had the same error on my Angular6 project. none of those solutions seemed to work out for me. turned out that the problem was due to an element which was specified as dropdown but it didn't have dropdown options in it. take a look at code below:

<span class="nav-link" id="navbarDropdownMenuLink" data-toggle="dropdown"
                          aria-haspopup="true" aria-expanded="false">
                        <i class="material-icons "
                           style="font-size: 2rem">notifications</i>
                        <span class="notification"></span>
                        <p>
                            <span class="d-lg-none d-md-block">Some Actions</span>
                        </p>
                    </span>
                    <div class="dropdown-menu dropdown-menu-left"
                         *ngIf="global.localStorageItem('isInSadHich')"
                         aria-labelledby="navbarDropdownMenuLink">
                                        <a class="dropdown-item" href="#">You have 5 new tasks</a>
                                        <a class="dropdown-item" href="#">You're now friend with Andrew</a>
                                        <a class="dropdown-item" href="#">Another Notification</a>
                                        <a class="dropdown-item" href="#">Another One</a>
                    </div>

removing the code data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" solved the problem.

I myself think that by each click on the first span element, the scope expected to set style for dropdown children which did not existed in the parent span, so it threw error.

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

our problem was that the hard drive was down to zero space available.

findViewByID returns null

I was facing a similar problem when I was trying to do a custom view for a ListView.

I solved it simply by doing this:

public View getView(int i, View view, ViewGroup viewGroup) {

    // Gets the inflater
    LayoutInflater inflater = LayoutInflater.from(this.contexto);

    // Inflates the layout
    ConstraintLayout cl2 = (ConstraintLayout) 
    inflater.inflate(R.layout.custom_list_view, viewGroup, false);

    //Insted of calling just findViewById, I call de cl2.findViewById method. cl2 is the layout I have just inflated. 
     TextView tv1 = (TextView)cl2.findViewById(cl2);

How to repeat a char using printf?

If you limit yourself to repeating either a 0 or a space you can do:

For spaces:

printf("%*s", count, "");

For zeros:

printf("%0*d", count, 0);

How to center a (background) image within a div?

try background-position:center;

EDIT: since this question is getting lots of views, its worth adding some extra info:

text-align: center will not work because the background image is not part of the document and is therefore not part of the flow.

background-position:center is shorthand for background-position: center center; (background-position: horizontal vertical);

Using a list as a data source for DataGridView

Set the DataGridView property

    gridView1.AutoGenerateColumns = true;

And make sure the list of objects your are binding, those object properties should be public.

How to deserialize xml to object

The comments above are correct. You're missing the decorators. If you want a generic deserializer you can use this.

public static T DeserializeXMLFileToObject<T>(string XmlFilename)
{
    T returnObject = default(T);
    if (string.IsNullOrEmpty(XmlFilename)) return default(T);

    try
    {
        StreamReader xmlStream = new StreamReader(XmlFilename);
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        returnObject = (T)serializer.Deserialize(xmlStream);
    }
    catch (Exception ex)
    {
        ExceptionLogger.WriteExceptionToConsole(ex, DateTime.Now);
    }
    return returnObject;
}

Then you'd call it like this:

MyObjType MyObj = DeserializeXMLFileToObject<MyObjType>(FilePath);

Which websocket library to use with Node.js?

Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.

  • ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.

  • websocket-node WebSocket server and client for node.js

  • websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node

  • faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs

  • socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.

  • sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks

  • faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages

  • deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response

  • socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.

  • primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.

When to use:

  • use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities

  • use the fallback libraries when you care about browser fallbacks

  • use the full featured libraries when you care about channels

  • use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.

Where to test:

Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Select Help->About

for 64 bit.. it would say version as 64 bit Edition.

I see this in IE 9.. may be true with lesser versions too..