Programs & Examples On #Decoder

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

Module 'tensorflow' has no attribute 'contrib'

I used tensorflow 1.8 to train my model and there is no problem for now. Tensorflow 2.0 alpha is not suitable with object detection API

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

You have two records in your json file, and json.loads() is not able to decode more than one. You need to do it record by record.

See Python json.loads shows ValueError: Extra data

OR you need to reformat your json to contain an array:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

would be acceptable again. But there cannot be several top level objects.

How do I get rid of the b-prefix in a string in python?

Assuming you don't want to immediately decode it again like others are suggesting here, you can parse it to a string and then just strip the leading 'b and trailing '.

>>> x = "Hi there " 
>>> x = "Hi there ".encode("utf-8") 
>>> x
b"Hi there \xef\xbf\xbd"
>>> str(x)[2:-1]
"Hi there \\xef\\xbf\\xbd"   

Python - Convert a bytes array into JSON format

Python 3.5 + Use io module

import json
import io

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

fix_bytes_value = my_bytes_value.replace(b"'", b'"')

my_json = json.load(io.BytesIO(fix_bytes_value))  

JSONDecodeError: Expecting value: line 1 column 1

in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I had similar error: "Expecting value: line 1 column 1 (char 0)"

It helped for me to add "myfile.seek(0)", move the pointer to the 0 character

with open(storage_path, 'r') as myfile:
if len(myfile.readlines()) != 0:
    myfile.seek(0)
    Bank_0 = json.load(myfile)

How to download a file using a Java REST service and a data stream

See example here: Input and Output binary streams using JERSEY?

Pseudo code would be something like this (there are a few other similar options in above mentioned post):

@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
     public void write(OutputStream output) throws IOException, WebApplicationException {
        try {
          //
          // 1. Get Stream to file from first server
          //
          while(<read stream from first server>) {
              output.write(<bytes read from first server>)
          }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
              // close input stream
        }
    }
}

How to fix Invalid AES key length?

I was facing the same issue then i made my key 16 byte and it's working properly now. Create your key exactly 16 byte. It will surely work.

How to create custom view programmatically in swift having controls text field, button etc

var customView = UIView()


@IBAction func drawView(_ sender: AnyObject) {

    customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
    customView.backgroundColor = UIColor.black     //give color to the view 
    customView.center = self.view.center  
    self.view.addSubview(customView)
       }

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

Additional to all answers, I think it could have similar problems. My Problem was caused by png.9 files. If this files, have a (in my case) too small stretching area with just a few pixels, the building failed with this error also. I have checked all these answers, but nothing helped. Giving a little bit bigger stretching area, solved the problem. I tested it many times, allways when I use small stretching areas it failed. So I am sure, it will help some poeple to make the stretch area a little bit bigger.

The second problem, but this is just an assumption, is the icon name (maybe only for png.9 files too). For examle, I used an image named folder_icon.9.png , with this one, it allways failed. Renaming it to other_folder_icon.9.png, it worked. So I think some names are used by the android system itself, maybe here is a problem too.

Base64: java.lang.IllegalArgumentException: Illegal character

Your encoded text is [B@6499375d. That is not Base64, something went wrong while encoding. That decoding code looks good.

Use this code to convert the byte[] to a String before adding it to the URL:

String encodedEmailString = new String(encodedEmail, "UTF-8");
// ...
String confirmLink = "Complete your registration by clicking on following"
    + "\n<a href='" + confirmationURL + encodedEmailString + "'>link</a>";

How to decode a QR-code image in (preferably pure) Python?

The following code works fine with me:

brew install zbar
pip install pyqrcode
pip install pyzbar

For QR code image creation:

import pyqrcode
qr = pyqrcode.create("test1")
qr.png("test1.png", scale=6)

For QR code decoding:

from PIL import Image
from pyzbar.pyzbar import decode
data = decode(Image.open('test1.png'))
print(data)

that prints the result:

[Decoded(data=b'test1', type='QRCODE', rect=Rect(left=24, top=24, width=126, height=126), polygon=[Point(x=24, y=24), Point(x=24, y=150), Point(x=150, y=150), Point(x=150, y=24)])]

How to solve java.lang.OutOfMemoryError trouble in Android

You can't increase the heap size dynamically but you can request to use more by using.

android:largeHeap="true"

in the manifest.xml,you can add in your manifest these lines it is working for some situations.

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

Whether your application's processes should be created with a large Dalvik heap. This applies to all processes created for the application. It only applies to the first application loaded into a process; if you're using a shared user ID to allow multiple applications to use a process, they all must use this option consistently or they will have unpredictable results. Most apps should not need this and should instead focus on reducing their overall memory usage for improved performance. Enabling this also does not guarantee a fixed increase in available memory, because some devices are constrained by their total available memory.


To query the available memory size at runtime, use the methods getMemoryClass() or getLargeMemoryClass().

If still facing problem then this should also work

 BitmapFactory.Options options = new BitmapFactory.Options();
 options.inSampleSize = 8;
 mBitmapInsurance = BitmapFactory.decodeFile(mCurrentPhotoPath,options);

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory.

This is the optimal use of BitmapFactory.Options.inSampleSize with regards to speed of displaying the image. The documentation mentions using values that are a power of 2, so I am working with 2, 4, 8, 16 etc.

Lets get more deeper to Image Sampling:

For example, it’s not worth loading a 1024x768 pixel image into memory if it will eventually be displayed in a 128x128 pixel thumbnail in an ImageView.

To tell the decoder to subsample the image, loading a smaller version into memory, set inSampleSize to true in your BitmapFactory.Options object. For example, an image with resolution 2100 x 1500 pixels that is decoded with an inSampleSize of 4 produces a bitmap of approximately 512x384. Loading this into memory uses 0.75MB rather than 12MB for the full image (assuming a bitmap configuration of ARGB_8888). Here’s a method to calculate a sample size value that is a power of two based on a target width and height:

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

Note: A power of two value is calculated because the decoder uses a final value by rounding down to the nearest power of two, as per the inSampleSize documentation.

To use this method, first decode with inJustDecodeBounds set to true, pass the options through and then decode again using the new inSampleSize value and inJustDecodeBounds set to false:

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
    int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

This method makes it easy to load a bitmap of arbitrarily large size into an ImageView that displays a 100x100 pixel thumbnail, as shown in the following example code:

mImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

You can follow a similar process to decode bitmaps from other sources, by substituting the appropriate BitmapFactory.decode* method as needed.


I found this code also interesting:

private Bitmap getBitmap(String path) {

Uri uri = getImageUri(path);
InputStream in = null;
try {
    final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
    in = mContentResolver.openInputStream(uri);

    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(in, null, o);
    in.close();

    int scale = 1;
    while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > 
          IMAGE_MAX_SIZE) {
       scale++;
    }
    Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth + ", 
       orig-height: " + o.outHeight);

    Bitmap bitmap = null;
    in = mContentResolver.openInputStream(uri);
    if (scale > 1) {
        scale--;
        // scale to max possible inSampleSize that still yields an image
        // larger than target
        o = new BitmapFactory.Options();
        o.inSampleSize = scale;
        bitmap = BitmapFactory.decodeStream(in, null, o);

        // resize to desired dimensions
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        Log.d(TAG, "1th scale operation dimenions - width: " + width + ",
           height: " + height);

        double y = Math.sqrt(IMAGE_MAX_SIZE
                / (((double) width) / height));
        double x = (y / height) * width;

        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, (int) x, 
           (int) y, true);
        bitmap.recycle();
        bitmap = scaledBitmap;

        System.gc();
    } else {
        bitmap = BitmapFactory.decodeStream(in);
    }
    in.close();

    Log.d(TAG, "bitmap size - width: " +bitmap.getWidth() + ", height: " + 
       bitmap.getHeight());
    return bitmap;
} catch (IOException e) {
    Log.e(TAG, e.getMessage(),e);
    return null;
}

How to Manage Your App's Memory: link


It's not a good idea to use android:largeHeap="true" here's the extract from google that explains it,

However, the ability to request a large heap is intended only for a small set of apps that can justify the need to consume more RAM (such as a large photo editing app). Never request a large heap simply because you've run out of memory and you need a quick fix—you should use it only when you know exactly where all your memory is being allocated and why it must be retained. Yet, even when you're confident your app can justify the large heap, you should avoid requesting it to whatever extent possible. Using the extra memory will increasingly be to the detriment of the overall user experience because garbage collection will take longer and system performance may be slower when task switching or performing other common operations.

After working excrutiatingly with out of memory errors i would say adding this to the manifest to avoid the oom issue is not a sin


Verifying App Behavior on the Android Runtime (ART)

The Android runtime (ART) is the default runtime for devices running Android 5.0 (API level 21) and higher. This runtime offers a number of features that improve performance and smoothness of the Android platform and apps. You can find more information about ART's new features in Introducing ART.

However, some techniques that work on Dalvik do not work on ART. This document lets you know about things to watch for when migrating an existing app to be compatible with ART. Most apps should just work when running with ART.


Addressing Garbage Collection (GC) Issues

Under Dalvik, apps frequently find it useful to explicitly call System.gc() to prompt garbage collection (GC). This should be far less necessary with ART, particularly if you're invoking garbage collection to prevent GC_FOR_ALLOC-type occurrences or to reduce fragmentation. You can verify which runtime is in use by calling System.getProperty("java.vm.version"). If ART is in use, the property's value is "2.0.0" or higher.

Furthermore, a compacting garbage collector is under development in the Android Open-Source Project (AOSP) to improve memory management. Because of this, you should avoid using techniques that are incompatible with compacting GC (such as saving pointers to object instance data). This is particularly important for apps that make use of the Java Native Interface (JNI). For more information, see Preventing JNI Issues.


Preventing JNI Issues

ART's JNI is somewhat stricter than Dalvik's. It is an especially good idea to use CheckJNI mode to catch common problems. If your app makes use of C/C++ code, you should review the following article:


Also, you can use native memory (NDK & JNI), so you actually bypass the heap size limitation.

Here are some posts made about it:

and here's a library made for it:

Custom UITableViewCell from nib in Swift

Here's my approach using Swift 2 and Xcode 7.3. This example will use a single ViewController to load two .xib files -- one for a UITableView and one for the UITableCellView.

enter image description here

For this example you can drop a UITableView right into an empty TableNib.xib file. Inside, set the file's owner to your ViewController class and use an outlet to reference the tableView.

enter image description here

and

enter image description here

Now, in your view controller, you can delegate the tableView as you normally would, like so

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    ...

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        // Table view delegate
        self.tableView.delegate = self
        self.tableView.dataSource = self

        ...

To create your Custom cell, again, drop a Table View Cell object into an empty TableCellNib.xib file. This time, in the cell .xib file you don't have to specify an "owner" but you do need to specify a Custom Class and an identifier like "TableCellId"

enter image description here enter image description here

Create your subclass with whatever outlets you need like so

class TableCell: UITableViewCell {

    @IBOutlet weak var nameLabel: UILabel!

}

Finally... back in your View Controller, you can load and display the entire thing like so

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    // First load table nib
    let bundle = NSBundle(forClass: self.dynamicType)
    let tableNib = UINib(nibName: "TableNib", bundle: bundle)
    let tableNibView = tableNib.instantiateWithOwner(self, options: nil)[0] as! UIView

    // Then delegate the TableView
    self.tableView.delegate = self
    self.tableView.dataSource = self

    // Set resizable table bounds
    self.tableView.frame = self.view.bounds
    self.tableView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

    // Register table cell class from nib
    let cellNib = UINib(nibName: "TableCellNib", bundle: bundle)
    self.tableView.registerNib(cellNib, forCellReuseIdentifier: self.tableCellId)

    // Display table with custom cells
    self.view.addSubview(tableNibView)

}

The code shows how you can simply load and display a nib file (the table), and second how to register a nib for cell use.

Hope this helps!!!

How to initialize/instantiate a custom UIView class with a XIB file in Swift

override func draw(_ rect: CGRect) 
{
    AlertView.layer.cornerRadius = 4
    AlertView.clipsToBounds = true

    btnOk.layer.cornerRadius = 4
    btnOk.clipsToBounds = true   
}

class func instanceFromNib() -> LAAlertView {
    return UINib(nibName: "LAAlertView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! LAAlertView
}

@IBAction func okBtnDidClicked(_ sender: Any) {

    removeAlertViewFromWindow()

    UIView.animate(withDuration: 0.4, delay: 0.0, options: .allowAnimatedContent, animations: {() -> Void in
        self.AlertView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)

    }, completion: {(finished: Bool) -> Void in
        self.AlertView.transform = CGAffineTransform.identity
        self.AlertView.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
        self.AlertView.isHidden = true
        self.AlertView.alpha = 0.0

        self.alpha = 0.5
    })
}


func removeAlertViewFromWindow()
{
    for subview  in (appDel.window?.subviews)! {
        if subview.tag == 500500{
            subview.removeFromSuperview()
        }
    }
}


public func openAlertView(title:String , string : String ){

    lblTital.text  = title
    txtView.text  = string

    self.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
    appDel.window!.addSubview(self)


    AlertView.alpha = 1.0
    AlertView.isHidden = false

    UIView.animate(withDuration: 0.2, animations: {() -> Void in
        self.alpha = 1.0
    })
    AlertView.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)

    UIView.animate(withDuration: 0.3, delay: 0.2, options: .allowAnimatedContent, animations: {() -> Void in
        self.AlertView.transform = CGAffineTransform(scaleX: 1.1, y: 1.1)

    }, completion: {(finished: Bool) -> Void in
        UIView.animate(withDuration: 0.2, animations: {() -> Void in
            self.AlertView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)

        })
    })


}

How to have stored properties in Swift, the same way I had on Objective-C?

With Obj-c Categories you can only add methods, not instance variables.

In you example you have used @property as a shortcut to adding getter and setter method declarations. You still need to implement those methods.

Similarly in Swift you can add use extensions to add instance methods, computed properties etc. but not stored properties.

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I encountered this problem with Java 1.6. Running under Java 1.7 fixed my particular rendition of the problem. I think the underlying cause was that the server I was connecting to must have required stronger encryption than was available under 1.6.

Python json.loads shows ValueError: Extra data

This may also happen if your JSON file is not just 1 JSON record. A JSON record looks like this:

[{"some data": value, "next key": "another value"}]

It opens and closes with a bracket [ ], within the brackets are the braces { }. There can be many pairs of braces, but it all ends with a close bracket ]. If your json file contains more than one of those:

[{"some data": value, "next key": "another value"}]
[{"2nd record data": value, "2nd record key": "another value"}]

then loads() will fail.

I verified this with my own file that was failing.

import json

guestFile = open("1_guests.json",'r')
guestData = guestFile.read()
guestFile.close()
gdfJson = json.loads(guestData)

This works because 1_guests.json has one record []. The original file I was using all_guests.json had 6 records separated by newline. I deleted 5 records, (which I already checked to be bookended by brackets) and saved the file under a new name. Then the loads statement worked.

Error was

   raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 2 column 1 - line 10 column 1 (char 261900 - 6964758)

PS. I use the word record, but that's not the official name. Also, if your file has newline characters like mine, you can loop through it to loads() one record at a time into a json variable.

Reading JSON from a file?

The problem is using with statement:

with open('strings.json') as json_data:
    d = json.load(json_data)
    pprint(d)

The file is going to be implicitly closed already. There is no need to call json_data.close() again.

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

How to add DOM element script to head section?

you could do:

var scriptTag = document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.src = "script_source_here";
(document.getElementsByTagName("head")[0] || document.documentElement ).appendChild(scriptTag);

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

Well that is Because of

you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception. and the one way is to encrypt that data Directly into the String.

look this. Try and u will be able to resolve this

public static String decrypt(String encryptedData) throws Exception {

    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, key);
    String decordedValue = new BASE64Decoder().decodeBuffer(encryptedData).toString().trim();
    System.out.println("This is Data to be Decrypted" + decordedValue);
    return decordedValue;
}

hope that will help.

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I had exactly this issue using requests. Thanks to Christophe Roussy for his explanation.

To debug, I used:

response = requests.get(url)
logger.info(type(response))

I was getting a 404 response back from the API.

How to save a bitmap on internal storage

To Save your bitmap in sdcard use the following code

Store Image

private void storeImage(Bitmap image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        Log.d(TAG,
                "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    } 
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }  
}

To Get the Path for Image Storage

/** Create a File for saving an image or video */
private  File getOutputMediaFile(){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this. 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + getApplicationContext().getPackageName()
            + "/Files"); 

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    } 
    // Create a media file name
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
    File mediaFile;
        String mImageName="MI_"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
    return mediaFile;
} 

EDIT From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.

public onClick(View v){

switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
} 
}

Displaying better error message than "No JSON object could be decoded"

I had a similar problem this was my code:

    json_file=json.dumps(pyJson)
    file = open("list.json",'w')
    file.write(json_file)  

    json_file = open("list.json","r")
    json_decoded = json.load(json_file)
    print json_decoded

the problem was i had forgotten to file.close() I did it and fixed the problem.

Base64 length calculation?

For reference, the Base64 encoder's length formula is as follows:

Base64 encoder's length formula

As you said, a Base64 encoder given n bytes of data will produce a string of 4n/3 Base64 characters. Put another way, every 3 bytes of data will result in 4 Base64 characters. EDIT: A comment correctly points out that my previous graphic did not account for padding; the correct formula is Ceiling(4n/3).

The Wikipedia article shows exactly how the ASCII string Man encoded into the Base64 string TWFu in its example. The input string is 3 bytes, or 24 bits, in size, so the formula correctly predicts the output will be 4 bytes (or 32 bits) long: TWFu. The process encodes every 6 bits of data into one of the 64 Base64 characters, so the 24-bit input divided by 6 results in 4 Base64 characters.

You ask in a comment what the size of encoding 123456 would be. Keeping in mind that every every character of that string is 1 byte, or 8 bits, in size (assuming ASCII/UTF8 encoding), we are encoding 6 bytes, or 48 bits, of data. According to the equation, we expect the output length to be (6 bytes / 3 bytes) * 4 characters = 8 characters.

Putting 123456 into a Base64 encoder creates MTIzNDU2, which is 8 characters long, just as we expected.

Encoding as Base64 in Java

Here are my two cents... Java 8 does contain its own implementation of Base64. However, I found one slightly disturbing difference. To illustrate, I will provide a code example:

My codec wrapper:

public interface MyCodec
{
  static String apacheDecode(String encodedStr)
  {
    return new String(Base64.decodeBase64(encodedStr), Charset.forName("UTF-8"));
  }

  static String apacheEncode(String decodedStr)
  {
    byte[] decodedByteArr = decodedStr.getBytes(Charset.forName("UTF-8"));
    return Base64.encodeBase64String(decodedByteArr);
  }

  static String javaDecode(String encodedStr)
  {
    return new String(java.util.Base64.getDecoder().decode(encodedStr), Charset.forName("UTF-8"));
  }

  static String javaEncode(String decodedStr)
  {
    byte[] decodedByteArr = decodedStr.getBytes(Charset.forName("UTF-8"));
    return java.util.Base64.getEncoder().encodeToString(decodedByteArr);
  }
}

Test Class:

public class CodecDemo
{
  public static void main(String[] args)
  {
    String decodedText = "Hello World!";

    String encodedApacheText = MyCodec.apacheEncode(decodedText);
    String encodedJavaText = MyCodec.javaEncode(decodedText);

    System.out.println("Apache encoded text: " + MyCodec.apacheEncode(encodedApacheText));
    System.out.println("Java encoded text: " + MyCodec.javaEncode(encodedJavaText));

    System.out.println("Encoded results equal: " + encodedApacheText.equals(encodedJavaText));

    System.out.println("Apache decode Java: " + MyCodec.apacheDecode(encodedJavaText));
    System.out.println("Java decode Java: " + MyCodec.javaDecode(encodedJavaText));

    System.out.println("Apache decode Apache: " + MyCodec.apacheDecode(encodedApacheText));
    System.out.println("Java decode Apache: " + MyCodec.javaDecode(encodedApacheText));
  }
}

OUTPUT:

Apache encoded text: U0dWc2JHOGdWMjl5YkdRaA0K

Java encoded text: U0dWc2JHOGdWMjl5YkdRaA==
Encoded results equal: false
Apache decode Java: Hello World!
Java decode Java: Hello World!
Apache decode Apache: Hello World!
Exception in thread "main" java.lang.IllegalArgumentException: Illegal base64 character d
    at java.util.Base64$Decoder.decode0(Base64.java:714)
    at java.util.Base64$Decoder.decode(Base64.java:526)
    at java.util.Base64$Decoder.decode(Base64.java:549)

Notice that the Apache encoded text contain additional line breaks (white spaces) at the end. Therefore, in order for my codec to yield the same result regardless of Base64 implementation, I had to call trim() on the Apache encoded text. In my case, I simply added the aforementioned method call to the my codec's apacheDecode() as follows:

return Base64.encodeBase64String(decodedByteArr).trim();

Once this change was made, the results are what I expected to begin with:

Apache encoded text: U0dWc2JHOGdWMjl5YkdRaA==
Java encoded text: U0dWc2JHOGdWMjl5YkdRaA==
Encoded results equal: true
Apache decode Java: Hello World!
Java decode Java: Hello World!
Apache decode Apache: Hello World!
Java decode Apache: Hello World!

CONCLUSION: If you want to switch from Apache Base64 to Java, you must:

  1. Decode encoded text with your Apache decoder.
  2. Encode resulting (plain) text with Java.

If you switch without following these steps, most likely you will run into problems. That is how I made this discovery.

The requested resource does not support HTTP method 'GET'

Resolved this issue by using http(s) when accessing the endpoint. The route I was accessing was not available over http. So I would say verify the protocols for which the route is available.

Loading and parsing a JSON file with multiple JSON objects

for those stumbling upon this question: the python jsonlines library (much younger than this question) elegantly handles files with one json document per line. see https://jsonlines.readthedocs.io/

Decoding a Base64 string in Java

If you don't want to use apache, you can use Java8:

byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw=="); 
System.out.println(new String(decodedBytes) + "\n");

Java AES encryption and decryption

If for a block cipher you're not going to use a Cipher transformation that includes a padding scheme, you need to have the number of bytes in the plaintext be an integral multiple of the block size of the cipher.

So either pad out your plaintext to a multiple of 16 bytes (which is the AES block size), or specify a padding scheme when you create your Cipher objects. For example, you could use:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

Unless you have a good reason not to, use a padding scheme that's already part of the JCE implementation. They've thought out a number of subtleties and corner cases you'll have to realize and deal with on your own otherwise.


Ok, your second problem is that you are using String to hold the ciphertext.

In general,

String s = new String(someBytes);
byte[] retrievedBytes = s.getBytes();

will not have someBytes and retrievedBytes being identical.

If you want/have to hold the ciphertext in a String, base64-encode the ciphertext bytes first and construct the String from the base64-encoded bytes. Then when you decrypt you'll getBytes() to get the base64-encoded bytes out of the String, then base64-decode them to get the real ciphertext, then decrypt that.

The reason for this problem is that most (all?) character encodings are not capable of mapping arbitrary bytes to valid characters. So when you create your String from the ciphertext, the String constructor (which applies a character encoding to turn the bytes into characters) essentially has to throw away some of the bytes because it can make no sense of them. Thus, when you get bytes out of the string, they are not the same bytes you put into the string.

In Java (and in modern programming in general), you cannot assume that one character = one byte, unless you know absolutely you're dealing with ASCII. This is why you need to use base64 (or something like it) if you want to build strings from arbitrary bytes.

Android: Rotate image in imageview by an angle

try this on a custom view

public class DrawView extends View {


    public DrawView(Context context,AttributeSet attributeSet){
        super(context, attributeSet);
    }

    @Override
    public void onDraw(Canvas canvas) {
        /*Canvas c=new Canvas(BitmapFactory.decodeResource(getResources(), R.drawable.new_minute1)    );

        c.rotate(45);*/

        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.new_minute1), 0, 0, null);
        canvas.rotate(45);
    }
}

Python Image Library fails with message "decoder JPEG not available" - PIL

On Mac OS X Mavericks (10.9.3), I solved this by doing the follows:

Install libjpeg by brew (package management system)

brew install libjpeg

reinstall pillow (I use pillow instead of PIL)

pip install -I pillow

Use ffmpeg to add text subtitles

I will provide a simple and general answer that works with any number of audios and srt subtitles and respects the metadata that may include the mkv container. So it will even add the images the matroska may include as attachments (though not another types AFAIK) and convert them to tracks; you will not be able to watch but they will be there (you can demux them). Ah, and if the mkv has chapters the mp4 too.

ffmpeg -i <mkv-input> -c copy -map 0 -c:s mov_text <mp4-output>

As you can see, it's all about the -map 0, that tells FFmpeg to add all the tracks, which includes metadata, chapters, attachments, etc. If there is an unrecognized "track" (mkv allows to attach any type of file), it will end with an error.

You can create a simple batch mkv2mp4.bat, if you usually do this, to create an mp4 with the same name as the mkv. It would be better with error control, a different output name, etc., but you get the point.

@ffmpeg -i %1 -c copy -map 0 -c:s mov_text "%~n1.mp4"

Now you can simply run

mkv2mp4 "Video with subtitles etc.mkv"

And it will create "Video with subtitles etc.mp4" with the maximum of information included.

How to convert String to DOM Document object in java?

     public static void main(String[] args) {
    final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
                            "<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
                            "<role>Developer</role><gen>Male</gen></Emp>";
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
        DocumentBuilder builder;  
        try 
        {  
            builder = factory.newDocumentBuilder();  
            Document doc = builder.parse( new InputSource( new StringReader( xmlStr )) ); 

        } catch (Exception e) {  
            e.printStackTrace();  
        } 
  }

Handle JSON Decode Error when nothing returned

There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.

Thus, try the following:

try:
    qByUser = byUsrUrlObj.read()
    qUserData = json.loads(qByUser).decode('utf-8')
    questionSubjs = qUserData["all"]["questions"]
except ValueError:  # includes simplejson.decoder.JSONDecodeError
    print 'Decoding JSON has failed'

EDIT: Since simplejson.decoder.JSONDecodeError actually inherits from ValueError (proof here), I simplified the catch statement by just using ValueError.

How to call getResources() from a class which has no context?

It can easily be done if u had declared a class that extends from Application

This class will be like a singleton, so when u need a context u can get it just like this:

I think this is the better answer and the cleaner

Here is my code from Utilities package:

 public static String getAppNAme(){
     return MyOwnApplication.getInstance().getString(R.string.app_name);
 }

how to get html content from a webview?

Android WebView is just another render engine that render HTML contents downloaded from a HTTP server, much like Chrome or FireFox. I don't know the reason why you need get the rendered page (or screenshot) from WebView. For most of situation, this is not necessary. You can always get the raw HTML content from HTTP server directly.

There are already answers posted talking about getting the raw stream using HttpUrlConnection or HttpClient. Alternatively, there is a very handy library when dealing with HTML content parse/process on Android: JSoup, it provide very simple API to get HTML contents form HTTP server, and provide an abstract representation of HTML document to help us manage HTML parsing not only in a more OO style but also much easily:

// Single line of statement to get HTML document from HTTP server.
Document doc = Jsoup.connect("http://en.wikipedia.org/").get();

It is handy when, for example, you want to download HTML document first then add some custom css or javascript to it before passing it to WebView for rendering. Much more on their official web site, worth to check it out.

Getting RSA private key from PEM BASE64 Encoded private key file

This is PKCS#1 format of a private key. Try this code. It doesn't use Bouncy Castle or other third-party crypto providers. Just java.security and sun.security for DER sequece parsing. Also it supports parsing of a private key in PKCS#8 format (PEM file that has a header "-----BEGIN PRIVATE KEY-----").

import sun.security.util.DerInputStream;
import sun.security.util.DerValue;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;

public static PrivateKey pemFileLoadPrivateKeyPkcs1OrPkcs8Encoded(File pemFileName) throws GeneralSecurityException, IOException {
        // PKCS#8 format
        final String PEM_PRIVATE_START = "-----BEGIN PRIVATE KEY-----";
        final String PEM_PRIVATE_END = "-----END PRIVATE KEY-----";

        // PKCS#1 format
        final String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----";
        final String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----";

        Path path = Paths.get(pemFileName.getAbsolutePath());

        String privateKeyPem = new String(Files.readAllBytes(path));

        if (privateKeyPem.indexOf(PEM_PRIVATE_START) != -1) { // PKCS#8 format
            privateKeyPem = privateKeyPem.replace(PEM_PRIVATE_START, "").replace(PEM_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            byte[] pkcs8EncodedKey = Base64.getDecoder().decode(privateKeyPem);

            KeyFactory factory = KeyFactory.getInstance("RSA");
            return factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));

        } else if (privateKeyPem.indexOf(PEM_RSA_PRIVATE_START) != -1) {  // PKCS#1 format

            privateKeyPem = privateKeyPem.replace(PEM_RSA_PRIVATE_START, "").replace(PEM_RSA_PRIVATE_END, "");
            privateKeyPem = privateKeyPem.replaceAll("\\s", "");

            DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(privateKeyPem));

            DerValue[] seq = derReader.getSequence(0);

            if (seq.length < 9) {
                throw new GeneralSecurityException("Could not parse a PKCS1 private key.");
            }

            // skip version seq[0];
            BigInteger modulus = seq[1].getBigInteger();
            BigInteger publicExp = seq[2].getBigInteger();
            BigInteger privateExp = seq[3].getBigInteger();
            BigInteger prime1 = seq[4].getBigInteger();
            BigInteger prime2 = seq[5].getBigInteger();
            BigInteger exp1 = seq[6].getBigInteger();
            BigInteger exp2 = seq[7].getBigInteger();
            BigInteger crtCoef = seq[8].getBigInteger();

            RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);

            KeyFactory factory = KeyFactory.getInstance("RSA");

            return factory.generatePrivate(keySpec);
        }

        throw new GeneralSecurityException("Not supported format of a private key");
    }

Java Security: Illegal key size or default parameters?

With Java 9, Java 8u161, Java 7u171 and Java 6u181 the limitation is now disabled by default. See issue in Java Bug Database.


Beginning with Java 8u151 you can disable the limitation programmatically.

In older releases, JCE jurisdiction files had to be downloaded and installed separately to allow unlimited cryptography to be used by the JDK. The download and install steps are no longer necessary.

Instead you can now invoke the following line before first use of JCE classes (i.e. preferably right after application start):

Security.setProperty("crypto.policy", "unlimited");

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

In your android_suggest.py, break up that monstrous one-liner return statement into one_step_at_a_time pieces. Log repr(string_passed_to_json.loads) somewhere so that it can be checked after an exception happens. Eye-ball the results. If the problem is not evident, edit your question to show the repr.

string decode utf-8

Try looking at decode string encoded in utf-8 format in android but it doesn't look like your string is encoded with anything particular. What do you think the output should be?

import sun.misc.BASE64Encoder results in error compiled in Eclipse

Yup, and sun.misc.BASE64Decoder is way slower: 9x slower than java.xml.bind.DatatypeConverter.parseBase64Binary() and 4x slower than org.apache.commons.codec.binary.Base64.decodeBase64(), at least for a small string on Java 6 OSX.

Below is the test program I used. With Java 1.6.0_43 on OSX:

john:password = am9objpwYXNzd29yZA==
javax.xml took 373: john:password
apache took    612: john:password
sun took       2215: john:password

Btw that's with commons-codec 1.4. With 1.7 it seems to get slower:

javax.xml took 377: john:password
apache took    1681: john:password
sun took       2197: john:password

Didn't test Java 7 or other OS.

import javax.xml.bind.DatatypeConverter;
import org.apache.commons.codec.binary.Base64;
import java.io.IOException;

public class TestBase64 {
    private static volatile String save = null;
    public static void main(String argv[]) {
        String teststr = "john:password";
        String b64 = DatatypeConverter.printBase64Binary(teststr.getBytes());
        System.out.println(teststr + " = " + b64);
        try {
            final int COUNT = 1000000;
            long start;
            start = System.currentTimeMillis();
            for (int i=0; i<COUNT; ++i) {
                save = new String(DatatypeConverter.parseBase64Binary(b64));
            }
            System.out.println("javax.xml took "+(System.currentTimeMillis()-start)+": "+save);
            start = System.currentTimeMillis();
            for (int i=0; i<COUNT; ++i) {
                save = new String(Base64.decodeBase64(b64));
            }
            System.out.println("apache took    "+(System.currentTimeMillis()-start)+": "+save);
            sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
            start = System.currentTimeMillis();
            for (int i=0; i<COUNT; ++i) {
                save = new String(dec.decodeBuffer(b64));
            }
            System.out.println("sun took       "+(System.currentTimeMillis()-start)+": "+save);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

How to set a bitmap from resource

If the resource is showing and is a view, you can also capture it. Like a screenshot:

View rootView = ((View) findViewById(R.id.yourView)).getRootView();
rootView.setDrawingCacheEnabled(true);
rootView.layout(0, 0, rootView.getWidth(), rootView.getHeight());
rootView.buildDrawingCache();

Bitmap bm = Bitmap.createBitmap(rootView.getDrawingCache());

rootView.setDrawingCacheEnabled(false);

This actually grabs the whole layout but you can alter as you wish.

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

You can just basically revert your code using some other built in methods.

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

Android center view in FrameLayout doesn't work

To center a view in Framelayout, there are some available tricks. The simplest one I used for my Webview and Progressbar(very similar to your two object layout), I just added android:layout_gravity="center"

Here is complete XML in case if someone else needs the same thing to do

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".WebviewPDFActivity"
    android:layout_gravity="center"
    >
    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        />
    <ProgressBar
        android:id="@+id/progress_circular"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:visibility="visible"
        android:layout_gravity="center"
        />


</FrameLayout>

Here is my output

screenshot

Custom ImageView with drop shadow

I manage to apply gradient border using this code..

public static Bitmap drawShadow(Bitmap bitmap, int leftRightThk, int bottomThk, int padTop) {
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int newW = w - (leftRightThk * 2);
    int newH = h - (bottomThk + padTop);

    Bitmap.Config conf = Bitmap.Config.ARGB_8888;
    Bitmap bmp = Bitmap.createBitmap(w, h, conf);
    Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas c = new Canvas(bmp);

    // Left
    int leftMargin = (leftRightThk + 7)/2;
    Shader lshader = new LinearGradient(0, 0, leftMargin, 0, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP);
    paint.setShader(lshader);
    c.drawRect(0, padTop, leftMargin, newH, paint); 

    // Right
    Shader rshader = new LinearGradient(w - leftMargin, 0, w, 0, Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
    paint.setShader(rshader);
    c.drawRect(newW, padTop, w, newH, paint);

    // Bottom
    Shader bshader = new LinearGradient(0, newH, 0, bitmap.getHeight(), Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
    paint.setShader(bshader);
    c.drawRect(leftMargin -3, newH, newW + leftMargin + 3, bitmap.getHeight(), paint);
    c.drawBitmap(sbmp, leftRightThk, 0, null);

    return bmp;
}

hope this helps !

Why can't Python parse this JSON data?

There are two types in this parsing.

  1. Parsing data from a file from a system path
  2. Parsing JSON from remote URL.

From a file, you can use the following

import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']

This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python

overlay two images in android to set an imageview

this is my solution:

    public Bitmap Blend(Bitmap topImage1, Bitmap bottomImage1, PorterDuff.Mode Type) {

        Bitmap workingBitmap = Bitmap.createBitmap(topImage1);
        Bitmap topImage = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);

        Bitmap workingBitmap2 = Bitmap.createBitmap(bottomImage1);
        Bitmap bottomImage = workingBitmap2.copy(Bitmap.Config.ARGB_8888, true);

        Rect dest = new Rect(0, 0, bottomImage.getWidth(), bottomImage.getHeight());
        new BitmapFactory.Options().inPreferredConfig = Bitmap.Config.ARGB_8888;
        bottomImage.setHasAlpha(true);
        Canvas canvas = new Canvas(bottomImage);
        Paint paint = new Paint();

        paint.setXfermode(new PorterDuffXfermode(Type));

        paint.setFilterBitmap(true);
        canvas.drawBitmap(topImage, null, dest, paint);
        return bottomImage;
    }

usage :

imageView.setImageBitmap(Blend(topBitmap, bottomBitmap, PorterDuff.Mode.SCREEN));

or

imageView.setImageBitmap(Blend(topBitmap, bottomBitmap, PorterDuff.Mode.OVERLAY));

and the results :

Overlay mode : Overlay mode

Screen mode: Screen mode

QR Code encoding and decoding using zxing

If you really need to encode UTF-8, you can try prepending the unicode byte order mark. I have no idea how widespread the support for this method is, but ZXing at least appears to support it: http://code.google.com/p/zxing/issues/detail?id=103

I've been reading up on QR Mode recently, and I think I've seen the same practice mentioned elsewhere, but I've not the foggiest where.

How to store custom objects in NSUserDefaults

I create a library RMMapper (https://github.com/roomorama/RMMapper) to help save custom object into NSUserDefaults easier and more convenient, because implementing encodeWithCoder and initWithCoder is super boring!

To mark a class as archivable, just use: #import "NSObject+RMArchivable.h"

To save a custom object into NSUserDefaults:

#import "NSUserDefaults+RMSaveCustomObject.h"
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults rm_setCustomObject:user forKey:@"SAVED_DATA"];

To get custom obj from NSUserDefaults:

user = [defaults rm_customObjectForKey:@"SAVED_DATA"]; 

Python JSON serialize a Decimal object

Based on stdOrgnlDave answer I have defined this wrapper that it can be called with optional kinds so the encoder will work only for certain kinds inside your projects. I believe the work should be done inside your code and not to use this "default" encoder since "it is better explicit than implicit", but I understand using this will save some of your time. :-)

import time
import json
import decimal
from uuid import UUID
from datetime import datetime

def JSONEncoder_newdefault(kind=['uuid', 'datetime', 'time', 'decimal']):
    '''
    JSON Encoder newdfeault is a wrapper capable of encoding several kinds
    Use it anywhere on your code to make the full system to work with this defaults:
        JSONEncoder_newdefault()  # for everything
        JSONEncoder_newdefault(['decimal'])  # only for Decimal
    '''
    JSONEncoder_olddefault = json.JSONEncoder.default

    def JSONEncoder_wrapped(self, o):
        '''
        json.JSONEncoder.default = JSONEncoder_newdefault
        '''
        if ('uuid' in kind) and isinstance(o, uuid.UUID):
            return str(o)
        if ('datetime' in kind) and isinstance(o, datetime):
            return str(o)
        if ('time' in kind) and isinstance(o, time.struct_time):
            return datetime.fromtimestamp(time.mktime(o))
        if ('decimal' in kind) and isinstance(o, decimal.Decimal):
            return str(o)
        return JSONEncoder_olddefault(self, o)
    json.JSONEncoder.default = JSONEncoder_wrapped

# Example
if __name__ == '__main__':
    JSONEncoder_newdefault()

Can we convert a byte array into an InputStream in Java?

Use ByteArrayInputStream:

InputStream is = new ByteArrayInputStream(decodedBytes);

Java: Converting String to and from ByteBuffer and associated problems

Check out the CharsetEncoder and CharsetDecoder API descriptions - You should follow a specific sequence of method calls to avoid this problem. For example, for CharsetEncoder:

  1. Reset the encoder via the reset method, unless it has not been used before;
  2. Invoke the encode method zero or more times, as long as additional input may be available, passing false for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations;
  3. Invoke the encode method one final time, passing true for the endOfInput argument; and then
  4. Invoke the flush method so that the encoder can flush any internal state to the output buffer.

By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.

How to get image height and width using java?

So unfortunately, after trying all the answers from above, I did not get them to work after tireless times of trying. So I decided to do the real hack myself and I go this to work for me. I trust it would work perfectly for you too.

I am using this simple method to get the width of an image generated by the app and yet to be upload later for verification :

Pls. take note : you would have to enable permissions in manifest for access storage.

/I made it static and put in my Global class so I can reference or access it from just one source and if there is any modification, it would all have to be done at just one place. Just maintaining a DRY concept in java. (anyway) :)/

public static int getImageWidthOrHeight(String imgFilePath) {

            Log.d("img path : "+imgFilePath);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(imgFilePath, o);

            int width_tmp = o.outWidth, height_tmp = o.outHeight;

            Log.d("Image width : ", Integer.toString(width_tmp) );

            //you can decide to rather return height_tmp to get the height.

            return width_tmp;

}

Convert HTML Character Back to Text Using Java Standard Library

Or you can use unescapeHtml4:

    String miCadena="GU&#205;A TELEF&#211;NICA";
    System.out.println(StringEscapeUtils.unescapeHtml4(miCadena));

This code print the line: GUÍA TELEFÓNICA

RegEx to parse or validate Base64 data

Neither a ":" nor a "." will show up in valid Base64, so I think you can unambiguously throw away the http://www.stackoverflow.com line. In Perl, say, something like

my $sanitized_str = join q{}, grep {!/[^A-Za-z0-9+\/=]/} split /\n/, $str;

say decode_base64($sanitized_str);

might be what you want. It produces

This is simple ASCII Base64 for StackOverflow exmaple.

Setting WPF image source in code

You can also reduce this to one line. This is the code I used to set the Icon for my main window. It assumes the .ico file is marked as Content and is being copied to the output directory.

 this.Icon = new BitmapImage(new Uri("Icon.ico", UriKind.Relative));

How to decode viewstate

Here's another decoder that works well as of 2014: http://viewstatedecoder.azurewebsites.net/

This worked on an input on which the Ignatu decoder failed with "The serialized data is invalid" (although it leaves the BinaryFormatter-serialized data undecoded, showing only its length).

How do I use 3DES encryption/decryption in Java?

This example worked for me. Both encryption and decryption work without any issue.

package com.test.encodedecode;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class ThreeDesHandler {
    public static void main(String[] args) {
        String encodetext = null;
        String decodetext = null;
        ThreeDesHandler handler = new ThreeDesHandler();
        String key = "secret key";//Need to change with your value
        String plaintxt = "String for encode";//Need to change with your value
        encodetext = handler.encode3Des(key, plaintxt);
        System.out.println(encodetext);
        decodetext = handler.decode3Des(key, encodetext);
        System.out.println(decodetext);
    }

    public String encode3Des(String key, String plaintxt) {
        try {
            byte[] seed_key = (new String(key)).getBytes();
            SecretKeySpec keySpec = new SecretKeySpec(seed_key, "TripleDES");
            Cipher nCipher = Cipher.getInstance("TripleDES");
            nCipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] cipherbyte = nCipher.doFinal(plaintxt.getBytes());
            String encodeTxt = new String(Base64.encodeBase64(cipherbyte));
            return encodeTxt;
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    public String decode3Des(String key, String desStr) {
        try {
            Base64 base64 = new Base64();
            byte[] seed_key = (new String(key)).getBytes();
            SecretKeySpec keySpec = new SecretKeySpec(seed_key, "TripleDES");
            Cipher nCipher = Cipher.getInstance("TripleDES");
            nCipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] src = base64.decode(desStr);
            String returnstring = new String(nCipher.doFinal(src));
            return returnstring;
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

}

How can I force component to re-render with hooks in React?

You should preferably only have your component depend on state and props and it will work as expected, but if you really need a function to force the component to re-render, you could use the useState hook and call the function when needed.

Example

_x000D_
_x000D_
const { useState, useEffect } = React;_x000D_
_x000D_
function Foo() {_x000D_
  const [, forceUpdate] = useState();_x000D_
_x000D_
  useEffect(() => {_x000D_
    setTimeout(forceUpdate, 2000);_x000D_
  }, []);_x000D_
_x000D_
  return <div>{Date.now()}</div>;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Foo />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

Hide Show content-list with only CSS, no javascript used

I used a hidden checkbox to persistent view of some message. The checkbox could be hidden (display:none) or not. This is a tiny code that I could write.

You can see and test the demo on JSFiddle

HTML:

<input type=checkbox id="show">
<label for="show">Help?</label>
<span id="content">Do you need some help?</span>

CSS:

#show,#content{display:none;}
#show:checked~#content{display:block;}

Run code snippet:

_x000D_
_x000D_
#show,#content{display:none;}_x000D_
#show:checked~#content{display:block;}
_x000D_
<input id="show" type=checkbox>_x000D_
<label for="show">Click for Help</label>_x000D_
<span  id="content">Do you need some help?</span>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/9s8scbL7/

Xcode stuck on Indexing

I had this exact problem, it was caused by a 20 item array literal. Had to switch to different syntax. Pretty silly.

How to convert HTML to PDF using iText

You can do it with the HTMLWorker class (deprecated) like this:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

or using the XMLWorker, (download from this jar) using this code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);
    document.open();
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

Eclipse change project files location

I moved my default git repository folder and therefore had the same problem. I wrote my own Class to manage eclipse location and used it to change the location file.

        File locationfile 
            = new File("<workspace>"
                    +"/.metadata/.plugins/org.eclipse.core.resources/.projects/"
                    +"<project>/"
                    +".location");

        byte data[] = Files.readAllBytes(locationfile.toPath());

        EclipseLocation eclipseLocation = new EclipseLocation(data);

        eclipseLocation.changeUri("<new path to project>");

        byte newData[] = eclipseLocation.getData();

        Files.write(locationfile.toPath(),newData);

Here my EclipseLocation Class:

public class EclipseLocation {

    private byte[] data;
    private int length;
    private String uri;


    public EclipseLocation(byte[] data) {
        init(data);
    }

    public String getUri() {
        return uri;
    }

    public byte[] getData() {
        return data;
    }


    private void init(byte[] data) {

        this.data = data;   
        this.length = (data[16] * 256) + data[17];
        this.uri = new String(data,18,length);  
    }


    public void changeUri(String newUri) {

        int newLength = newUri.length();
        byte[] newdata = new byte[data.length + newLength - length];        


        int y = 0;
        int x = 0;

        //header
        while(y < 16) newdata[y++] = data[x++];

        //length
        newdata[16] = (byte) (newLength / 256);
        newdata[17] = (byte) (newLength % 256);

        y += 2;
        x += 2;

        //Uri
        for(int i = 0;i < newLength;i++)
        {
            newdata[y++] = (byte) newUri.charAt(i);
        }
        x += length;

        //footer
        while(y < newdata.length) newdata[y++] = data[x++];

        if(y != newdata.length)
            throw new IndexOutOfBoundsException();

        if(x != data.length)
            throw new IndexOutOfBoundsException();

        init(newdata);
    }


}

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

Complementing the above answers and also "Parroting" from the Windows Dev Center documentation,

The Winsock2.h header file internally includes core elements from the Windows.h header file, so there is not usually an #include line for the Windows.h header file in Winsock applications. If an #include line is needed for the Windows.h header file, this should be preceded with the #define WIN32_LEAN_AND_MEAN macro. For historical reasons, the Windows.h header defaults to including the Winsock.h header file for Windows Sockets 1.1. The declarations in the Winsock.h header file will conflict with the declarations in the Winsock2.h header file required by Windows Sockets 2.0. The WIN32_LEAN_AND_MEAN macro prevents the Winsock.h from being included by the Windows.h header ..

Webfont Smoothing and Antialiasing in Firefox and Opera

As Opera is powered by Blink since Version 15.0 -webkit-font-smoothing: antialiased does also work on Opera.

Firefox has finally added a property to enable grayscaled antialiasing. After a long discussion it will be available in Version 25 with another syntax, which points out that this property only works on OS X.

-moz-osx-font-smoothing: grayscale;

This should fix blurry icon fonts or light text on dark backgrounds.

.font-smoothing {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

You may read my post about font rendering on OSX which includes a Sass mixin to handle both properties.

Where is the application.properties file in a Spring Boot project?

You can also create the application.properties file manually.

SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:

  • A /config subdirectory of the current directory.
  • The current directory
  • A classpath /config package
  • The classpath root

The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations). (From the Spring boot features external configuration doc page)

So just go ahead and create it

What is the use of the %n format specifier in C?

The argument associated with the %n will be treated as an int* and is filled with the number of total characters printed at that point in the printf.

Why did I get the compile error "Use of unassigned local variable"?

IEnumerable<DateTime?> _getCurrentHolidayList; //this will not initailize

Assign value(_getCurrentHolidayList) inside the loop

foreach (HolidaySummaryList _holidayItem in _holidayDetailsList)
{
                            if (_holidayItem.CountryId == Countryid)
                                _getCurrentHolidayList = _holidayItem.Holiday;                                                   
}

After your are passing the local varibale to another method like below. It throw error(use of unassigned variable). eventhough nullable mentioned in time of decalration.

var cancelRescheduleCondition = GetHolidayDays(_item.ServiceDateFrom, _getCurrentHolidayList);

if you mentioned like below, It will not throw any error.

IEnumerable<DateTime?> _getCurrentHolidayList =null;

Sound effects in JavaScript / HTML5

Web Audio API is right tool for this job. There is little bit of work involved in loading sounds files and playing it. Luckily there are plenty of libraries out there that simplify the job. Being interested in sounds I also created a library called musquito you can check out that as well.

Currently it supports only fading sound effect and I'm working on other things like 3D spatialization.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

In my case I used google play services...I increase library service it solved

implementation 'com.google.android.gms:play-services-auth:16.0.0'

Google play service must be same in library and app modules

Reference

How do I determine if a checkbox is checked?

<!DOCTYPE html>
<html>
<body>
    <input type="checkbox" id="isSelected"/>
    <div id="myDiv" style="display:none">Is Checked</div>
</body>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>
        $('#isSelected').click(function() {
            $("#myDiv").toggle(this.checked);
        });
    </script>
</html>

Remove Top Line of Text File with PowerShell

I just had to do the same task, and gc | select ... | sc took over 4 GB of RAM on my machine while reading a 1.6 GB file. It didn't finish for at least 20 minutes after reading the whole file in (as reported by Read Bytes in Process Explorer), at which point I had to kill it.

My solution was to use a more .NET approach: StreamReader + StreamWriter. See this answer for a great answer discussing the perf: In Powershell, what's the most efficient way to split a large text file by record type?

Below is my solution. Yes, it uses a temporary file, but in my case, it didn't matter (it was a freaking huge SQL table creation and insert statements file):

PS> (measure-command{
    $i = 0
    $ins = New-Object System.IO.StreamReader "in/file/pa.th"
    $outs = New-Object System.IO.StreamWriter "out/file/pa.th"
    while( !$ins.EndOfStream ) {
        $line = $ins.ReadLine();
        if( $i -ne 0 ) {
            $outs.WriteLine($line);
        }
        $i = $i+1;
    }
    $outs.Close();
    $ins.Close();
}).TotalSeconds

It returned:

188.1224443

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

EditText edit = new EditText(this);

edit.setHorizontallyScrolling(true);
edit.setInputType(EditorInfo.TYPE_NUMBER_FLAG_SIGNED|EditorInfo.TYPE_CLASS_NUMBER);

Passing multiple argument through CommandArgument of Button in Asp.net

You can pass semicolon separated values as command argument and then split the string and use it.

<asp:TemplateField ShowHeader="false">
    <ItemTemplate>
       <asp:LinkButton ID="lnkCustomize" Text="Customize"  CommandName="Customize"  CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>'  runat="server"> 
       </asp:LinkButton>   
    </ItemTemplate>   
</asp:TemplateField>

at server side

protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
      string[] arg = new string[2];
      arg = e.CommandArgument.ToString().Split(';');
      Session["IdTemplate"] = arg[0];
      Session["IdEntity"] = arg[1];
      Response.Redirect("Samplepage.aspx");
}

Hope it helps!!!!

Get integer value from string in swift

8:1 Odds(*)

var stringNumb: String = "1357"
var someNumb = Int(stringNumb)

or

var stringNumb: String = "1357"
var someNumb:Int? = Int(stringNumb)

Int(String) returns an optional Int?, not an Int.


Safe use: do not explicitly unwrap

let unwrapped:Int = Int(stringNumb) ?? 0

or

if let stringNumb:Int = stringNumb { ... }

(*) None of the answers actually addressed why var someNumb: Int = Int(stringNumb) was not working.

String, StringBuffer, and StringBuilder

String Family

String

The String class represents character strings. All string literals in Java program, such as "abc" are implemented as instances of this class.

String objects are immutable once they are created we can't change. (Strings are constants)

  • If a String is created using constructor or method then those strings will be stored in Heap Memory as well as SringConstantPool. But before saving in pool it invokes intern() method to check object availability with same content in pool using equals method. If String-copy is available in the Pool then returns the reference. Otherwise, String object is added to the pool and returns the reference.

    • The Java language provides special support for the string concatenation operator (+), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.

    String heapSCP = new String("Yash");
    heapSCP.concat(".");
    heapSCP = heapSCP + "M";
    heapSCP = heapSCP + 777;
    
    // For Example: String Source Code 
    public String concat(String str) {
        int otherLen = str.length();
        if (otherLen == 0) {
            return this;
        }
        int len = value.length;
        char buf[] = Arrays.copyOf(value, len + otherLen);
        str.getChars(buf, len);
        return new String(buf, true);
    }
    
  • String literals are stored in StringConstantPool.

    String onlyPool = "Yash";
    

StringBuilder and StringBuffer are mutable sequence of characters. That means one can change the value of these object's. StringBuffer has the same methods as the StringBuilder, but each method in StringBuffer is synchronized so it is thread safe.

  • StringBuffer and StringBuilder data can only be created using new operator. So, they get stored in Heap memory.

  • Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

    StringBuffer threadSafe = new StringBuffer("Yash");
    threadSafe.append(".M");
    threadSafe.toString();
    
    StringBuilder nonSync = new StringBuilder("Yash");
    nonSync.append(".M");
    nonSync.toString();
    
  • StringBuffer and StringBuilder are having a Special methods like., replace(int start, int end, String str) and reverse().

    NOTE: StringBuffer and SringBuilder are mutable as they provides the implementation of Appendable Interface.


When to use which one.

  • If a you are not going to change the value every time then its better to Use String Class. As part of Generics if you want to Sort Comparable<T> or compare a values then go for String Class.

    //ClassCastException: java.lang.StringBuffer cannot be cast to java.lang.Comparable
    Set<StringBuffer> set = new TreeSet<StringBuffer>();
    set.add( threadSafe );
    System.out.println("Set : "+ set);
    
  • If you are going to modify the value every time the go for StringBuilder which is faster than StringBuffer. If multiple threads are modifying the value the go for StringBuffer.

What's a concise way to check that environment variables are set in a Unix shell script?

Parameter Expansion

The obvious answer is to use one of the special forms of parameter expansion:

: ${STATE?"Need to set STATE"}
: ${DEST:?"Need to set DEST non-empty"}

Or, better (see section on 'Position of double quotes' below):

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

The first variant (using just ?) requires STATE to be set, but STATE="" (an empty string) is OK — not exactly what you want, but the alternative and older notation.

The second variant (using :?) requires DEST to be set and non-empty.

If you supply no message, the shell provides a default message.

The ${var?} construct is portable back to Version 7 UNIX and the Bourne Shell (1978 or thereabouts). The ${var:?} construct is slightly more recent: I think it was in System III UNIX circa 1981, but it may have been in PWB UNIX before that. It is therefore in the Korn Shell, and in the POSIX shells, including specifically Bash.

It is usually documented in the shell's man page in a section called Parameter Expansion. For example, the bash manual says:

${parameter:?word}

Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

The Colon Command

I should probably add that the colon command simply has its arguments evaluated and then succeeds. It is the original shell comment notation (before '#' to end of line). For a long time, Bourne shell scripts had a colon as the first character. The C Shell would read a script and use the first character to determine whether it was for the C Shell (a '#' hash) or the Bourne shell (a ':' colon). Then the kernel got in on the act and added support for '#!/path/to/program' and the Bourne shell got '#' comments, and the colon convention went by the wayside. But if you come across a script that starts with a colon, now you will know why.


Position of double quotes

blong asked in a comment:

Any thoughts on this discussion? https://github.com/koalaman/shellcheck/issues/380#issuecomment-145872749

The gist of the discussion is:

… However, when I shellcheck it (with version 0.4.1), I get this message:

In script.sh line 13:
: ${FOO:?"The environment variable 'FOO' must be set and non-empty"}
  ^-- SC2086: Double quote to prevent globbing and word splitting.

Any advice on what I should do in this case?

The short answer is "do as shellcheck suggests":

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

To illustrate why, study the following. Note that the : command doesn't echo its arguments (but the shell does evaluate the arguments). We want to see the arguments, so the code below uses printf "%s\n" in place of :.

$ mkdir junk
$ cd junk
$ > abc
$ > def
$ > ghi
$ 
$ x="*"
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
abc
def
ghi
$ unset x
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
bash: x: You must set x
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
bash: x: You must set x
$ x="*"
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
*
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
abc
def
ghi
$ x=
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ unset x
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ 

Note how the value in $x is expanded to first * and then a list of file names when the overall expression is not in double quotes. This is what shellcheck is recommending should be fixed. I have not verified that it doesn't object to the form where the expression is enclosed in double quotes, but it is a reasonable assumption that it would be OK.

How can I undo git reset --hard HEAD~1?

In most cases, yes.

Depending on the state your repository was in when you ran the command, the effects of git reset --hard can range from trivial to undo, to basically impossible.

Below I have listed a range of different possible scenarios, and how you might recover from them.

All my changes were committed, but now the commits are gone!

This situation usually occurs when you run git reset with an argument, as in git reset --hard HEAD~. Don't worry, this is easy to recover from!

If you just ran git reset and haven't done anything else since, you can get back to where you were with this one-liner:

git reset --hard @{1}

This resets your current branch whatever state it was in before the last time it was modified (in your case, the most recent modification to the branch would be the hard reset you are trying to undo).

If, however, you have made other modifications to your branch since the reset, the one-liner above won't work. Instead, you should run git reflog <branchname> to see a list of all recent changes made to your branch (including resets). That list will look something like this:

7c169bd master@{0}: reset: moving to HEAD~
3ae5027 master@{1}: commit: Changed file2
7c169bd master@{2}: commit: Some change
5eb37ca master@{3}: commit (initial): Initial commit

Find the operation in this list that you want to "undo". In the example above, it would be the first line, the one that says "reset: moving to HEAD~". Then copy the representation of the commit before (below) that operation. In our case, that would be master@{1} (or 3ae5027, they both represent the same commit), and run git reset --hard <commit> to reset your current branch back to that commit.

I staged my changes with git add, but never committed. Now my changes are gone!

This is a bit trickier to recover from. git does have copies of the files you added, but since these copies were never tied to any particular commit you can't restore the changes all at once. Instead, you have to locate the individual files in git's database and restore them manually. You can do this using git fsck.

For details on this, see Undo git reset --hard with uncommitted files in the staging area.

I had changes to files in my working directory that I never staged with git add, and never committed. Now my changes are gone!

Uh oh. I hate to tell you this, but you're probably out of luck. git doesn't store changes that you don't add or commit to it, and according to the documentation for git reset:

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

It's possible that you might be able to recover your changes with some sort of disk recovery utility or a professional data recovery service, but at this point that's probably more trouble than it's worth.

How to remove the first character of string in PHP?

Exec time for the 3 answers :

Remove the first letter by replacing the case

$str = "hello";
$str[0] = "";
// $str[0] = false;
// $str[0] = null;
// replaced by ?, but ok for echo

Exec time for 1.000.000 tests : 0.39602184295654 sec


Remove the first letter with substr()

$str = "hello";
$str = substr($str, 1);

Exec time for 1.000.000 tests : 5.153294801712 sec


Remove the first letter with ltrim()

$str = "hello";
$str= ltrim ($str,'h');

Exec time for 1.000.000 tests : 5.2393000125885 sec


Remove the first letter with preg_replace()

$str = "hello";
$str = preg_replace('/^./', '', $str);

Exec time for 1.000.000 tests : 6.8543920516968 sec

Java: using switch statement with enum under subclass

This is how I am using it. And it is working fantastically -

public enum Button {
        REPORT_ISSUES(0),
        CANCEL_ORDER(1),
        RETURN_ORDER(2);

        private int value;

        Button(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }

And the switch-case as shown below

@Override
public void onClick(MyOrderDetailDelgate.Button button, int position) {
    switch (button) {
        case REPORT_ISSUES: {
            break;
        }
        case CANCEL_ORDER: {
            break;
        }
        case RETURN_ORDER: {
            break;
        }
    }
}

Package signatures do not match the previously installed version

You need to uninstall it because you are using a different signature than the original. If it is not working it might be because it is still installed for another user on the device. To completely uninstall, go to Settings -> Apps -> HAgnostic News -> Options (the three dots on top right) -> Uninstall for all users

Why doesn't git recognize that my file has been changed, therefore git add not working

Make sure not to create symlinks (ln -s source dest) from inside of Git Bash for Windows.

It does NOT make symlinks, but does a DEEP copy of the source to the dest

I experienced same behavior as OP on a MINGW64 terminal from Git Bash for Windows (version 2.16.2) to realize that my 'edited' changes actually were in the original directory, and my git bash commands were from within a deep copy that had remained unchanged.

Angular get object from array by Id

You can use .filter() or .find(). One difference that filter will iterate over all items and returns any which passes the condition as array while find will return the first matched item and break the iteration.

Example

_x000D_
_x000D_
var questions = [_x000D_
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},_x000D_
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},_x000D_
      {id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},_x000D_
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},_x000D_
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},_x000D_
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},_x000D_
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},_x000D_
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},_x000D_
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},_x000D_
      {id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},_x000D_
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},_x000D_
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},_x000D_
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},_x000D_
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},_x000D_
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}_x000D_
];_x000D_
_x000D_
function getDimensionsByFilter(id){_x000D_
  return questions.filter(x => x.id === id);_x000D_
}_x000D_
_x000D_
function getDimensionsByFind(id){_x000D_
  return questions.find(x => x.id === id);_x000D_
}_x000D_
_x000D_
var test = getDimensionsByFilter(10);_x000D_
console.log(test);_x000D_
_x000D_
test = getDimensionsByFind(10);_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

How to tell if a connection is dead in python

From the link Jweede posted:

exception socket.timeout:

This exception is raised when a timeout occurs on a socket
which has had timeouts enabled via a prior call to settimeout().
The accompanying value is a string whose value is currently
always “timed out”.

Here are the demo server and client programs for the socket module from the python docs

# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.send(data)
conn.close()

And the client:

# Echo client program
import socket

HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

On the docs example page I pulled these from, there are more complex examples that employ this idea, but here is the simple answer:

Assuming you're writing the client program, just put all your code that uses the socket when it is at risk of being dropped, inside a try block...

try:
    s.connect((HOST, PORT))
    s.send("Hello, World!")
    ...
except socket.timeout:
    # whatever you need to do when the connection is dropped

Counting the number of non-NaN elements in a numpy ndarray in Python

np.count_nonzero(~np.isnan(data))

~ inverts the boolean matrix returned from np.isnan.

np.count_nonzero counts values that is not 0\false. .sum should give the same result. But maybe more clearly to use count_nonzero

Testing speed:

In [23]: data = np.random.random((10000,10000))

In [24]: data[[np.random.random_integers(0,10000, 100)],:][:, [np.random.random_integers(0,99, 100)]] = np.nan

In [25]: %timeit data.size - np.count_nonzero(np.isnan(data))
1 loops, best of 3: 309 ms per loop

In [26]: %timeit np.count_nonzero(~np.isnan(data))
1 loops, best of 3: 345 ms per loop

In [27]: %timeit data.size - np.isnan(data).sum()
1 loops, best of 3: 339 ms per loop

data.size - np.count_nonzero(np.isnan(data)) seems to barely be the fastest here. other data might give different relative speed results.

Why is my CSS bundling not working with a bin deployed MVC4 app?

This solved my issue. I have added these lines in _layout.cshtml

@*@Scripts.Render("~/bundles/plugins")*@
<script src="/Content/plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Kendo JS -->
<script src="/Content/kendo/js/kendo.all.min.js" type="text/javascript"></script>
<script src="/Content/kendo/js/kendo.web.min.js" type="text/javascript"></script>
<script src="/Content/kendo/js/kendo.aspnetmvc.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="/Content/bootstrap/js/bootstrap.min.js"></script>
<!-- Morris.js charts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="/Content/plugins/morris/morris.min.js"></script>
<!-- Sparkline -->
<script src="/Content/plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<script src="/Content/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="/Content/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- jQuery Knob Chart -->
<script src="/Content/plugins/knob/jquery.knob.js"></script>
<!-- daterangepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
<script src="/Content/plugins/daterangepicker/daterangepicker.js"></script>
<!-- datepicker -->
<script src="/Content/plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="/Content/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<!-- Slimscroll -->
<script src="/Content/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="/Content/plugins/fastclick/fastclick.min.js"></script>
<!-- AdminLTE App -->
<script src="/Content/dist/js/app.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="/Content/dist/js/demo.js"></script>
<!-- Common -->
<script src="/Scripts/common/common.js"></script>
<!-- Render Sections -->

Turning error reporting off php

Does this work?

display_errors = Off

Also, what version of php are you using?

CSS filter: make color image with transparency white

To my knowledge, there is sadly no CSS filter to colorise an element (perhaps with the use of some SVG filter magic, but I'm somewhat unfamiliar with that) and even if that wasn't the case, filters are basically only supported by webkit browsers.

With that said, you could still work around this and use a canvas to modify your image. Basically, you can draw an image element onto a canvas and then loop through the pixels, modifying the respective RGBA values to the colour you want.

However, canvases do come with some restrictions. Most importantly, you have to make sure that the image src comes from the same domain as the page. Otherwise the browser won't allow you to read or modify the pixel data of the canvas.

Here's a JSFiddle changing the colour of the JSFiddle logo.

_x000D_
_x000D_
//Base64 source, but any local source will work_x000D_
var src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAgCAYAAACGhPFEAAAABGdBTUEAALGPC/xhBQAABzhJREFUWAnNWAtwXFUZ/v9zs4GUJJu+k7tb5DFAGWO1aal1sJUiY3FQQaWidqgPLAMqYzd9CB073VodhCa7KziiFgWhzvAYQCiCD5yK4gOTDnZK2ymdZoruppu0afbu0pBs7p7f7yy96W662aw2QO/Mzj2P//Gd/5z/+89dprfzubnTN332Re+xiKawllxWucm+9O4eCi9xT8ctn45yKd3AXX1BPsu3XIiuY+K5kDmrUA7jORb5m2baLm7uscNrJr9eOF9Je8JAz9ySnFHlq9nEpG6CYx+RdJDQDtKymxT1iWZLFDUy0/kkfDUxzYVzV0hvHZLs946Gph+uBLCRmRDQdjTVwmw9DZCNMPi4KzqWbPX/sxwIu71vlrKq10HnZizwTSFZngj5f1NOx5s7bdB2LHWDEusBOD487LrX9qyd8qpnvJL3zGjqAh+pR4W4RVhu715Vv2U8PTWeQLn5YHvms4qsR4TpH/ImLfhfARvbPaGGrrjTtwjH5hFFfHcgkv5SOZ9mbvxIgwGaZl+8ULGcJ8zOsJa9R1r9B2d8v2eGb1KNieqBhLNz8ekyAoV3VAX985+FvSXEenF8lf9lA7DUUxa0HUl/RTG1EfOUQmUwwCtggDewiHmc1R+Ir/MfKJz/f9tTwn31Nf7qVxlHLR6qXwg7cHXqU/p4hPdUB6Lp55TiXwDYTsrpG12dbdY5t0WLrCSRSVjIItG0dqIAG2jHwlPTmvQdsL3Ajjg3nAq3zIgdS98ZiGV0MJZeWVJs2WNWIJK5hcLh0osuqVTxIAdi6X3w/0LFGoa+AtFMzo5kflix0gQLBiLOZmAYro84RcfSc3NKpFAcliM9eYDdjZ7QO/1mRc+CTapqFX+4lO9TQEPoUpz//anQ5FQphXdizB1QXXk/moOl/JUC7aLMDpQSHj02PdxbG9xybM60u47UjZ4bq290Zm451ky3HSi6kxTKJ9fXHQVvZJm1XTjutYsozw53T1L+2ufBGPMTe/c30M/mD3uChW+c+6tQttthuBnbqMBLKGbydI54/eFQ3b5CWa/dGMl8xFJ0D/rvg1Pjdxil+2XK5b6ZWD15lyfnvYOxTBYs9TrY5NbuUENRUo5EGtGyVUNtBwBfDjA/IDtTkiNRsdYD8O+NcVN2KUfXo3UnukvA6Z3I+mWeY++NpNoAwDvAv1Uiss7oiNBmYD+XraoO0NvnPVnvrbUsA4CcYusPgajzY2/cvN+KtOFl/6w/IWrvdTV/Ktla92KhkNcOxpwPCqm/IgLbEvteW1m4E2/d8iY9AZOXQ/7WxKq6nxq9YNT5OLF6DmAfTHT13EL3XjTk2csXk4bqX2OXWiQ73Jz49tS4N5d/oxoHLr14EzPfAf1IIlS/2oznIx1omLURhL5Qa1oxFuC8EeHb8U6I88bXCwGbuZ61jb2Jgz1XYUHb0b0vEHNWmHE9lNsjWrcmnMhNhYDNnCkmNJSFHFdzte82M1b04HgC6HrYbAPw1pFdNOc4GE334wz9qkihRAdK/0HBub/E1MkhJBiq6V8gq7Htm05OjN2C/z/jCP1xbAlCwcnsAsbdkGHF/trPIcoNrtbjFRNmoama6EgZ42SimRG5FjLHWakNwWjmirLyZpLpKH7TysghZ00OUHNTxFmK2yDNQSKlx7u0Q0GQeLtQdy4rY5zMzqVb/ccoJ/OQMEmoPWW3988to4NY8DxYf6WMDCW6ktuRvFqxmqewgguhdLCcwsic0DMA8lE7kvrYyFhBw446X2B/nRNo739/YnX9azKUXYCg9CtlvdAUyywuEB1p4gh9AzbPZc0mF8Z+sINgn0MIwiVgKcAG6rGlT86AMdqw2n8ppR63o+mveQXCFAxzX2BWD0P6pcT+g3uNlmEDV3JX4iOh1xICdWU2gGXOMXN5HfRhK4IoPxlfXQfmKf+Ajh1I+MEeHMcKzqvoxoZsHsoOXgP+fEkxbw1e2JhB0h2q9tc4OL/fAVdsdd3jnyhklmRo8qGBQXchIvMMKPW7Pt85/SM66CNmDw1mh75cHu6JWZFZxNLNSJTPIM5PuJquKEt3o6zmqyJZH4LTC7CIfTonO5Jr/B2jxIq6jW3OZVYVX4edDSD6e1BAXqwgl/I2miKp+ZayOkT0CjaJww21/2bhznio7uoiL2dQB8HdhoV++ri4AdUdtgfw789mRHspzulXzyCcI1BMVQXgL5LodnP7zFfE+N9/9yOUyedxTn/SFHWWj0ifAY1ANHUleOJRlPqdCUmbO85J1jjxUfkUkgVCsg1/uGw0n/fvFm67LT2NLTLfi98Cke8dpMGl3r9QxVRnPuPrWzaIUmsAtgas0okd6ETh7AYt5d7+BeCbhfKVcQ6CtwgJjjoiP3fdgVbcbY57/otBnxidfndvo6/67BtxUf4kztJsbMg0CJaU9QxN2FskhePQBWr7La6wvzRFarTtyoBgB4hm5M//aAMT2+/Vlfzp81/vywLMWSBN1QAAAABJRU5ErkJggg==";_x000D_
var canvas = document.getElementById("theCanvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image;_x000D_
_x000D_
//wait for the image to load_x000D_
img.onload = function() {_x000D_
    //Draw the original image so that you can fetch the colour data_x000D_
    ctx.drawImage(img,0,0);_x000D_
    var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);_x000D_
    _x000D_
    /*_x000D_
    imgData.data is a one-dimensional array which contains _x000D_
    the respective RGBA values for every pixel _x000D_
    in the selected region of the context _x000D_
    (note i+=4 in the loop)_x000D_
    */_x000D_
    _x000D_
    for (var i = 0; i < imgData.data.length; i+=4) {_x000D_
   imgData.data[i] = 255; //Red, 0-255_x000D_
   imgData.data[i+1] = 255; //Green, 0-255_x000D_
   imgData.data[i+2] = 255; //Blue, 0-255_x000D_
   /* _x000D_
   imgData.data[i+3] contains the alpha value_x000D_
   which we are going to ignore and leave_x000D_
   alone with its original value_x000D_
   */_x000D_
    }_x000D_
    ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the original image_x000D_
    ctx.putImageData(imgData, 0, 0); //paint the new colorised image_x000D_
}_x000D_
_x000D_
//Load the image!_x000D_
img.src = src;
_x000D_
body {_x000D_
    background: green;_x000D_
}
_x000D_
<canvas id="theCanvas"></canvas>
_x000D_
_x000D_
_x000D_

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

I had the same error message. For me it was happening because I was trying to run the installer from the DVD rather than running the installer from Add/Remove programs.

How do you use global variables or constant values in Ruby?

Variable scope in Ruby is controlled by sigils to some degree. Variables starting with $ are global, variables with @ are instance variables, @@ means class variables, and names starting with a capital letter are constants. All other variables are locals. When you open a class or method, that's a new scope, and locals available in the previous scope aren't available.

I generally prefer to avoid creating global variables. There are two techniques that generally achieve the same purpose that I consider cleaner:

  1. Create a constant in a module. So in this case, you would put all the classes that need the offset in the module Foo and create a constant Offset, so then all the classes could access Foo::Offset.

  2. Define a method to access the value. You can define the method globally, but again, I think it's better to encapsulate it in a module or class. This way the data is available where you need it and you can even alter it if you need to, but the structure of your program and the ownership of the data will be clearer. This is more in line with OO design principles.

Occurrences of substring in a string

If you need the index of each substring within the original string, you can do something with indexOf like this:

 private static List<Integer> getAllIndexesOfSubstringInString(String fullString, String substring) {
    int pointIndex = 0;
    List<Integer> allOccurences = new ArrayList<Integer>();
    while(fullPdfText.indexOf(substring,pointIndex) >= 0){
       allOccurences.add(fullPdfText.indexOf(substring, pointIndex));
       pointIndex = fullPdfText.indexOf(substring, pointIndex) + substring.length();
    }
    return allOccurences;
}

Should Jquery code go in header or footer?

Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.

AngularJS ui-router login authentication

I have another solution: that solution works perfectly when you have only content you want to show when you are logged in. Define a rule where you checking if you are logged in and its not path of whitelist routes.

$urlRouterProvider.rule(function ($injector, $location) {
   var UserService = $injector.get('UserService');
   var path = $location.path(), normalized = path.toLowerCase();

   if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
     $location.path('/login/signin');
   }
});

In my example i ask if i am not logged in and the current route i want to route is not part of `/login', because my whitelist routes are the following

/login/signup // registering new user
/login/signin // login to app

so i have instant access to this two routes and every other route will be checked if you are online.

Here is my whole routing file for the login module

export default (
  $stateProvider,
  $locationProvider,
  $urlRouterProvider
) => {

  $stateProvider.state('login', {
    parent: 'app',
    url: '/login',
    abstract: true,
    template: '<ui-view></ui-view>'
  })

  $stateProvider.state('signin', {
    parent: 'login',
    url: '/signin',
    template: '<login-signin-directive></login-signin-directive>'
  });

  $stateProvider.state('lock', {
    parent: 'login',
    url: '/lock',
    template: '<login-lock-directive></login-lock-directive>'
  });

  $stateProvider.state('signup', {
    parent: 'login',
    url: '/signup',
    template: '<login-signup-directive></login-signup-directive>'
  });

  $urlRouterProvider.rule(function ($injector, $location) {
    var UserService = $injector.get('UserService');
    var path = $location.path();

    if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
         $location.path('/login/signin');
    }
  });

  $urlRouterProvider.otherwise('/error/not-found');
}

() => { /* code */ } is ES6 syntax, use instead function() { /* code */ }

How can I get the data type of a variable in C#?

Its Very simple

variable.GetType().Name

it will return your datatype of your variable

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

I was getting this error

Error:Execution failed for task ':app:preDebugAndroidTestBuild'. Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.

I was having following dependencies in my build.gradle file under Gradle Scripts

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

So, I resolved it by commenting the following dependencies

testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

So my dependencies look like this

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
//testImplementation 'junit:junit:4.12'
//androidTestImplementation 'com.android.support.test:runner:1.0.2'
//androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Hope it helps!

Writing a dictionary to a csv file with one line for every 'key: value'

outfile = open( 'dict.txt', 'w' )
for key, value in sorted( mydict.items() ):
    outfile.write( str(key) + '\t' + str(value) + '\n' )

How do I remove the horizontal scrollbar in a div?

No scroll (without specifying x or y):

.your-class {
   overflow: hidden;
}

Remove horizontal scroll:

.your-class {
   overflow-x: hidden;
}

Remove vertical scroll:

.your-class {
   overflow-y: hidden;
}

How do I pass a method as a parameter in Python

Here is your example re-written to show a stand-alone working example:

class Test:
    def method1(self):
        return 'hello world'

    def method2(self, methodToRun):
        result = methodToRun()
        return result

    def method3(self):
        return self.method2(self.method1)

test = Test()

print test.method3()

How can I render inline JavaScript with Jade / Pug?

script(nonce="some-nonce").
  console.log("test");

//- Workaround
<script nonce="some-nonce">console.log("test");</script>

Move branch pointer to different commit without checkout

In gitk --all:

  • right click on the commit you want
  • -> create new branch
  • enter the name of an existing branch
  • press return on the dialog that confirms replacing the old branch of that name.

Beware that re-creating instead of modifying the existing branch will lose tracking-branch information. (This is generally not a problem for simple use-cases where there's only one remote and your local branch has the same name as the corresponding branch in the remote. See comments for more details, thanks @mbdevpl for pointing out this downside.)

It would be cool if gitk had a feature where the dialog box had 3 options: overwrite, modify existing, or cancel.


Even if you're normally a command-line junkie like myself, git gui and gitk are quite nicely designed for the subset of git usage they allow. I highly recommend using them for what they're good at (i.e. selectively staging hunks into/out of the index in git gui, and also just committing. (ctrl-s to add a signed-off: line, ctrl-enter to commit.)

gitk is great for keeping track of a few branches while you sort out your changes into a nice patch series to submit upstream, or anything else where you need to keep track of what you're in the middle of with multiple branches.

I don't even have a graphical file browser open, but I love gitk/git gui.

Backup a single table with its data from a database in sql server 2008

Another approach you can take if you need to back up a single table out of multiple tables in a database is:

  1. Generate script of specific table(s) from a database (Right-click database, click Task > Generate Scripts...

  2. Run the script in the query editor. You must change/add the first line (USE DatabaseName) in the script to a new database, to avoid getting the "Database already exists" error.

  3. Right-click on the newly created database, and click on Task > Back Up... The backup will contain the selected table(s) from the original database.

What does a just-in-time (JIT) compiler do?

JIT refers to execution engine in few of JVM implementations, one that is faster but requires more memory,is a just-in-time compiler. In this scheme, the bytecodes of a method are compiled to native machine code the first time the method is invoked. The native machine code for the method is then cached, so it can be re-used the next time that same method is invoked.

Flutter: RenderBox was not laid out

Reading answers here, it seems that the error "RenderBox was not laid out" is caused when somehow the ListView size is limitless and this can happen in different scenarios.

Just aiming to help who may have the same case as mine. In my case, I was getting this error because my ListView was inside a a column whose parent was a SingleChildScrollView. I remove this parent and it worked.

Here is my working code:

 List _todoList = ["AAA", "BBB"];

 ...

    body: Column(
      children: [
        Container(...),
        Expanded(
            child: ListView.builder(
                itemCount: _todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(_todoList[index]));
                }))
      ],
    ));

Here how it was when I was getting the "not laid out" error:

     List _todoList = ["AAA", "BBB"];

     ...


     body: SingleChildScrollView(child: Column(
      children: [
        Container(...),
        Expanded(
            child: ListView.builder(
                itemCount: _todoList.length,
                itemBuilder: (context, index) {
                  return ListTile(title: Text(_todoList[index]));
                }))
      ],
    )));

I hope this may be useful for someone.

What is a wrapper class?

There are several design patterns that can be called wrapper classes.

See my answer to "How do the Proxy, Decorator, Adaptor, and Bridge Patterns differ?"

what's the easiest way to put space between 2 side-by-side buttons in asp.net

Add a space &nbsp; between them (or more depending on your preference)

    <div style="text-align: center">         
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="89px" OnClick="btnSubmit_Click" />
        &nbsp;
        <asp:Button ID="btnClear" runat="server" Text="Clear" Width="89px" OnClick="btnClear_Click" />
    </div>

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

To top up on @Tim Schmelter, in which to get back the List<int> instead,

List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
   .Where(li => li.Selected)
   .Select(li => li.Value)
   .Select(int.Parse)
   .ToList();

Android set height and width of Custom view programmatically

If you know the exact size of the view, just use setLayoutParams():

graphView.setLayoutParams(new LayoutParams(width, height));

Or in Kotlin:

graphView.layoutParams = LayoutParams(width, height)

However, if you need a more flexible approach you can override onMeasure() to measure the view more precisely depending on the space available and layout constraints (wrap_content, match_parent, or a fixed size). You can find more details about onMeasure() in the android docs.

Load content of a div on another page

You just need to add a jquery selector after the url.

See: http://api.jquery.com/load/

Example straight from the API:

$('#result').load('ajax/test.html #container');

So what that does is it loads the #container element from the specified url.

Scala check if element is present in a list

this should work also with different predicate

myFunction(strings.find( _ == mystring ).isDefined)

How to get access to raw resources that I put in res folder?

InputStream in = getResources().openRawResource(resourceName);

This will work correctly. Before that you have to create the xml file / text file in raw resource. Then it will be accessible.

Edit
Some times com.andriod.R will be imported if there is any error in layout file or image names. So You have to import package correctly, then only the raw file will be accessible.

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

What I would do is use this tool and step through where you are getting the exception

http://www.reflector.net/

Read this it will tell you how to create PDB's so you do not have to have all your references setup.

http://www.cplotts.com/2011/01/14/net-reflector-pro-debugging-the-net-framework-source-code/

It is a trial and I am not related to redgate at all I just use there software.

Using getopts to process long and short command line options

Here's an example that actually uses getopt with long options:

aflag=no
bflag=no
cargument=none

# options may be followed by one colon to indicate they have a required argument
if ! options=$(getopt -o abc: -l along,blong,clong: -- "$@")
then
    # something went wrong, getopt will put out an error message for us
    exit 1
fi

set -- $options

while [ $# -gt 0 ]
do
    case $1 in
    -a|--along) aflag="yes" ;;
    -b|--blong) bflag="yes" ;;
    # for options with required arguments, an additional shift is required
    -c|--clong) cargument="$2" ; shift;;
    (--) shift; break;;
    (-*) echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
    (*) break;;
    esac
    shift
done

Using DateTime in a SqlParameter for Stored Procedure, format error

Just use:

 param.AddWithValue("@Date_Of_Birth",DOB);

That will take care of all your problems.

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

I think this represents a good answer.

APK Signature Scheme v2 verification

  1. Locate the APK Signing Block and verify that:
    1. Two size fields of APK Signing Block contain the same value.
    2. ZIP Central Directory is immediately followed by ZIP End of Central Directory record.
    3. ZIP End of Central Directory is not followed by more data.
  2. Locate the first APK Signature Scheme v2 Block inside the APK Signing Block. If the v2 Block if present, proceed to step 3. Otherwise, fall back to verifying the APK using v1 scheme.
  3. For each signer in the APK Signature Scheme v2 Block:
    1. Choose the strongest supported signature algorithm ID from signatures. The strength ordering is up to each implementation/platform version.
    2. Verify the corresponding signature from signatures against signed data using public key. (It is now safe to parse signed data.)
    3. Verify that the ordered list of signature algorithm IDs in digests and signatures is identical. (This is to prevent signature stripping/addition.)
    4. Compute the digest of APK contents using the same digest algorithm as the digest algorithm used by the signature algorithm.
    5. Verify that the computed digest is identical to the corresponding digest from digests.
    6. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical to public key.
  4. Verification succeeds if at least one signer was found and step 3 succeeded for each found signer.

Note: APK must not be verified using the v1 scheme if a failure occurs in step 3 or 4.

JAR-signed APK verification (v1 scheme)

The JAR-signed APK is a standard signed JAR, which must contain exactly the entries listed in META-INF/MANIFEST.MF and where all entries must be signed by the same set of signers. Its integrity is verified as follows:

  1. Each signer is represented by a META-INF/<signer>.SF and META-INF/<signer>.(RSA|DSA|EC) JAR entry.
  2. <signer>.(RSA|DSA|EC) is a PKCS #7 CMS ContentInfo with SignedData structure whose signature is verified over the <signer>.SF file.
  3. <signer>.SF file contains a whole-file digest of the META-INF/MANIFEST.MF and digests of each section of META-INF/MANIFEST.MF. The whole-file digest of the MANIFEST.MF is verified. If that fails, the digest of each MANIFEST.MF section is verified instead.
  4. META-INF/MANIFEST.MF contains, for each integrity-protected JAR entry, a correspondingly named section containing the digest of the entry’s uncompressed contents. All these digests are verified.
  5. APK verification fails if the APK contains JAR entries which are not listed in the MANIFEST.MF and are not part of JAR signature. The protection chain is thus <signer>.(RSA|DSA|EC) ? <signer>.SF ? MANIFEST.MF ? contents of each integrity-protected JAR entry.

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

How to indent HTML tags in Notepad++

On Notepadd++ v7.5.9 (32-bits), "Indent by fold" plugin is working fine with html content.

  1. Search and install in plugin manager
  2. Use "Plugins" > "Indent by fold" > "Reindent file"

https://www.fesevur.com/indentbyfold/

How to set date format in HTML date input tag?

$('input[type="date"]').change(function(){
   alert(this.value.split("-").reverse().join("-")); 
});

Jquery click event not working after append method

This problem could be solved as mentioned using the .on on jQuery 1.7+ versions.

Unfortunately, this didn't work within my code (and I have 1.11) so I used:

$('body').delegate('.logout-link','click',function() {

http://api.jquery.com/delegate/

As of jQuery 3.0, .delegate() has been deprecated. It was superseded by the .on() method since jQuery 1.7, so its use was already discouraged. For earlier versions, however, it remains the most effective means to use event delegation. More information on event binding and delegation is in the .on() method. In general, these are the equivalent templates for the two methods:

// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );

This comment might help others :) !

Android Studio: Application Installation Failed

Step 1: Go to "Setting" ? find "Developer options" in System, and click.

Step 2: TURN ON "Verify apps over USB" in Debugging section.

Step 3: Try "Run app" in Android Studio again!

            and you should also TURN ON following fields inside "Developer option" .....

1: TURN ON ->"Install via USB" field

Goal Seek Macro with Goal as a Formula

I think your issue is that Range("H18") doesn't contain a formula. Also, you could make your code more efficient by eliminating x. Instead, change your code to

Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")

Is there a way to get rid of accents and convert a whole string to regular letters?

I suggest Junidecode . It will handle not only 'L' and 'Ø', but it also works well for transcribing from other alphabets, such as Chinese, into Latin alphabet.

How to install python developer package?

yum install python-devel will work.

If yum doesn't work then use

apt-get install python-dev

What is a Subclass

A subclass is something that extends the functionality of your existing class. I.e.

Superclass - describes the catagory of objects:

public abstract class Fruit {

    public abstract Color color;

}

Subclass1 - describes attributes of the individual Fruit objects:

public class Apple extends Fruit {

    Color color = red;

}

Subclass2 - describes attributes of the individual Fruit objects:

public class Banana extends Fruit {

    Color color = yellow;

}

The 'abstract' keyword in the superclass means that the class will only define the mandatory information that each subclass must have i.e. A piece of fruit must have a color so it is defines in the super class and all subclasses must 'inherit' that attribute and define the value that describes the specific object.

Does that make sense?

RecyclerView expand/collapse items

After using the recommended way of implementing expandable/collapsible items residing in a RecyclerView on RecyclerView expand/collapse items answered by HeisenBerg, I've seen some noticeable artifacts whenever the RecyclerView is refreshed by invoking TransitionManager.beginDelayedTransition(ViewGroup) and subsequently notifyDatasetChanged().

His original answer:

final boolean isExpanded = position==mExpandedPosition;
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mExpandedPosition = isExpanded ? -1 : position;
        TransitionManager.beginDelayedTransition(recyclerView);
        notifyDataSetChanged();
    }
});

Modified:

final boolean isExpanded = position == mExpandedPosition;
holder.details.setVisibility(isExpanded ? View.VISIBLE : View.GONE);
holder.view.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (mExpandedHolder != null) {
            mExpandedHolder.details.setVisibility(View.GONE);
            notifyItemChanged(mExpandedPosition);
        }
        mExpandedPosition = isExpanded ? -1 : holder.getAdapterPosition();
        mExpandedHolder = isExpanded ? null : holder;
        notifyItemChanged(holder.getAdapterPosition());
    }
}
  • details is view that you want to show/hide during item expand/collapse
  • mExpandedPosition is an int that keeps track of expanded item
  • mExpandedHolder is a ViewHolder used during item collapse

Notice that the method TransitionManager.beginDelayedTransition(ViewGroup) and notifyDataSetChanged() are replaced by notifyItemChanged(int) to target specific item and some little tweaks.

After the modification, the previous unwanted effects should be gone. However, this may not be the perfect solution. It only did what I wanted, eliminating the eyesores.

::EDIT::

For clarification, both mExpandedPosition and mExpandedHolder are globals.

ObjectiveC Parse Integer from String

Keep in mind that international users may be using a decimal separator other than . in which case values can get mixed up or just become nil when using intValue on a string.

For example, in the UK 1.23 is written 1,23, so the number 1.777 would be input by user as 1,777, which, as .intValue, will be 1777 not 1 (truncated).


I've made a macro that will convert input text to an NSNumber based on a locale argument which can be nil (if nil it uses device current locale).

#define stringToNumber(__string, __nullable_locale) (\
(^NSNumber *(void){\
NSLocale *__locale = __nullable_locale;\
if (!__locale) {\
__locale = [NSLocale currentLocale];\
}\
NSString *__string_copy = [__string stringByReplacingOccurrencesOfString:__locale.groupingSeparator withString:@""];\
__string_copy = [__string_copy stringByReplacingOccurrencesOfString:__locale.decimalSeparator withString:@"."];\
return @([__string_copy doubleValue]);\
})()\
)

Vue Js - Loop via v-for X times (in a range)

You can use an index in a range and then access the array via its index:

<ul>
  <li v-for="index in 10" :key="index">
    {{ shoppingItems[index].name }} - {{ shoppingItems[index].price }}
  </li>
</ul>

You can also check the Official Documentation for more information.

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['auth_type'] = 'cookie';

should work.

From the manual:

auth_type = 'cookie' prompts for a MySQL username and password in a friendly HTML form. This is also the only way by which one can log in to an arbitrary server (if $cfg['AllowArbitraryServer'] is enabled). Cookie is good for most installations (default in pma 3.1+), it provides security over config and allows multiple users to use the same phpMyAdmin installation. For IIS users, cookie is often easier to configure than http.

Convert JSONObject to Map

org.json.JSONObject#toMap() will do to work

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

First install your targeted version

npm i [email protected] --save-dev --save-exact

Then before compiling do

   npm i

Automatically open default email client and pre-populate content

JQuery:

$(function () {
      $('.SendEmail').click(function (event) {
        var email = '[email protected]';
        var subject = 'Test';
        var emailBody = 'Hi Sample,';
        var attach = 'path';
        document.location = "mailto:"+email+"?subject="+subject+"&body="+emailBody+
            "?attach="+attach;
      });
    });

HTML:

 <button class="SendEmail">Send Email</button>

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

I think may be more automatic, grunt task usemin take care to do all this jobs for you, only need some configuration:

https://stackoverflow.com/a/33481683/1897196

What is the strict aliasing rule?

As addendum to what Doug T. already wrote, here is a simple test case which probably triggers it with gcc :

check.c

#include <stdio.h>

void check(short *h,long *k)
{
    *h=5;
    *k=6;
    if (*h == 5)
        printf("strict aliasing problem\n");
}

int main(void)
{
    long      k[1];
    check((short *)k,k);
    return 0;
}

Compile with gcc -O2 -o check check.c . Usually (with most gcc versions I tried) this outputs "strict aliasing problem", because the compiler assumes that "h" cannot be the same address as "k" in the "check" function. Because of that the compiler optimizes the if (*h == 5) away and always calls the printf.

For those who are interested here is the x64 assembler code, produced by gcc 4.6.3, running on ubuntu 12.04.2 for x64:

movw    $5, (%rdi)
movq    $6, (%rsi)
movl    $.LC0, %edi
jmp puts

So the if condition is completely gone from the assembler code.

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

The reason that you get this error on OSX is the rvm-installed ruby.

If you run into this issue on OSX you can find a really broad explanation of it in this blog post:

http://toadle.me/2015/04/16/fixing-failing-ssl-verification-with-rvm.html

The short version is that, for some versions of Ruby, RVM downloads pre-compiled binaries, which look for certificates in the wrong location. By forcing RVM to download the source and compile on your own machine, you ensure that the configuration for the certificate location is correct.

The command to do this is:

rvm install 2.2.0 --disable-binary

if you already have the version in question, you can re-install it with:

rvm reinstall 2.2.0 --disable-binary

(obviously, substitute your ruby version as needed).

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

One way of doing this without changing Volley's source code is to check for the response data in the VolleyError and parse it your self.

As of f605da3 commit, Volley throws a ServerError exception that contains the raw network response.

So you can do something similar to this in your error listener:

/* import com.android.volley.toolbox.HttpHeaderParser; */
public void onErrorResponse(VolleyError error) {

    // As of f605da3 the following should work
    NetworkResponse response = error.networkResponse;
    if (error instanceof ServerError && response != null) {
        try {
            String res = new String(response.data,
                       HttpHeaderParser.parseCharset(response.headers, "utf-8"));
            // Now you can use any deserializer to make sense of data
            JSONObject obj = new JSONObject(res);
        } catch (UnsupportedEncodingException e1) {
            // Couldn't properly decode data to string
            e1.printStackTrace();
        } catch (JSONException e2) {
            // returned data is not JSONObject?
            e2.printStackTrace();
        }
    }
}

For future, if Volley changes, one can follow the above approach where you need to check the VolleyError for raw data that has been sent by the server and parse it.

I hope that they implement that TODO mentioned in the source file.

Changing selection in a select with the Chosen plugin

In case of multiple type of select and/or if you want to remove already selected items one by one, directly within a dropdown list items, you can use something like:

jQuery("body").on("click", ".result-selected", function() {
    var locID = jQuery(this).attr('class').split('__').pop();
    // I have a class name: class="result-selected locvalue__209"
    var arrayCurrent = jQuery('#searchlocation').val();
    var index = arrayCurrent.indexOf(locID);
    if (index > -1) {
        arrayCurrent.splice(index, 1);
    }
    jQuery('#searchlocation').val(arrayCurrent).trigger('chosen:updated');
});

Display more Text in fullcalendar

With the modification of a single line you could alter the fullcalendar.js script to allow a line break and put multiple information on the same line.

In FullCalendar.js on line ~3922 find htmlEscape(s) function and add .replace(/<br\s?/?>/g, '
') to the end of it.

function htmlEscape(s) {
    return s.replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/'/g, '&#039;')
    .replace(/"/g, '&quot;')
    .replace(/\n/g, '<br />')
    .replace(/&lt;br\s?\/?&gt;/g, '<br />');
}

This will allow you to have multiple lines for the title, separating the information. Example replace the event.title with title: 'All Day Event' + '<br />' + 'Other Description'

How to execute an SSIS package from .NET?

Here is how to set variables in the package from code -

using Microsoft.SqlServer.Dts.Runtime;

private void Execute_Package()
    {           
        string pkgLocation = @"c:\test.dtsx";

        Package pkg;
        Application app;
        DTSExecResult pkgResults;
        Variables vars;

        app = new Application();
        pkg = app.LoadPackage(pkgLocation, null);

        vars = pkg.Variables;
        vars["A_Variable"].Value = "Some value";               

        pkgResults = pkg.Execute(null, vars, null, null, null);

        if (pkgResults == DTSExecResult.Success)
            Console.WriteLine("Package ran successfully");
        else
            Console.WriteLine("Package failed");
    }

How to create timer events using C++ 11?

The asynchronous solution from Edward:

  • create new thread
  • sleep in that thread
  • do the task in that thread

is simple and might just work for you.

I would also like to give a more advanced version which has these advantages:

  • no thread startup overhead
  • only a single extra thread per process required to handle all timed tasks

This might be in particular useful in large software projects where you have many task executed repetitively in your process and you care about resource usage (threads) and also startup overhead.

Idea: Have one service thread which processes all registered timed tasks. Use boost io_service for that.

Code similar to: http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/tutorial/tuttimer2/src.html

#include <cstdio>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

int main()
{
  boost::asio::io_service io;

  boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
  t.async_wait([](const boost::system::error_code& /*e*/){
    printf("Printed after 1s\n"); });

  boost::asio::deadline_timer t2(io, boost::posix_time::seconds(1));
  t2.async_wait([](const boost::system::error_code& /*e*/){
    printf("Printed after 1s\n"); });

  // both prints happen at the same time,
  // but only a single thread is used to handle both timed tasks
  // - namely the main thread calling io.run();

  io.run();

  return 0;
}

changing permission for files and folder recursively using shell command in mac

You can just use the -R (recursive) flag.

chmod -R 777 /Users/Test/Desktop/PATH

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

Creating threads - Task.Factory.StartNew vs new Thread()

There is a big difference. Tasks are scheduled on the ThreadPool and could even be executed synchronous if appropiate.

If you have a long running background work you should specify this by using the correct Task Option.

You should prefer Task Parallel Library over explicit thread handling, as it is more optimized. Also you have more features like Continuation.

Regex to match only uppercase "words" with some exceptions

To some extent, this is going to vary by the "flavour" of RegEx you're using. The following is based on .NET RegEx, which uses \b for word boundaries. In the last example, it also uses negative lookaround (?<!) and (?!) as well as non-capturing parentheses (?:)

Basically, though, if the terms always contain at least one uppercase letter followed by at least one number, you can use

\b[A-Z]+[0-9]+\b

For all-uppercase and numbers (total must be 2 or more):

\b[A-Z0-9]{2,}\b

For all-uppercase and numbers, but starting with at least one letter:

\b[A-Z][A-Z0-9]+\b

The granddaddy, to return items that have any combination of uppercase letters and numbers, but which are not single letters at the beginning of a line and which are not part of a line that is all uppercase:

(?:(?<!^)[A-Z]\b|(?<!^[A-Z0-9 ]*)\b[A-Z0-9]+\b(?![A-Z0-9 ]$))

breakdown:

The regex starts with (?:. The ?: signifies that -- although what follows is in parentheses, I'm not interested in capturing the result. This is called "non-capturing parentheses." Here, I'm using the paretheses because I'm using alternation (see below).

Inside the non-capturing parens, I have two separate clauses separated by the pipe symbol |. This is alternation -- like an "or". The regex can match the first expression or the second. The two cases here are "is this the first word of the line" or "everything else," because we have the special requirement of excluding one-letter words at the beginning of the line.

Now, let's look at each expression in the alternation.

The first expression is: (?<!^)[A-Z]\b. The main clause here is [A-Z]\b, which is any one capital letter followed by a word boundary, which could be punctuation, whitespace, linebreak, etc. The part before that is (?<!^), which is a "negative lookbehind." This is a zero-width assertion, which means it doesn't "consume" characters as part of a match -- not really important to understand that here. The syntax for negative lookbehind in .NET is (?<!x), where x is the expression that must not exist before our main clause. Here that expression is simply ^, or start-of-line, so this side of the alternation translates as "any word consisting of a single, uppercase letter that is not at the beginning of the line."

Okay, so we're matching one-letter, uppercase words that are not at the beginning of the line. We still need to match words consisting of all numbers and uppercase letters.

That is handled by a relatively small portion of the second expression in the alternation: \b[A-Z0-9]+\b. The \bs represent word boundaries, and the [A-Z0-9]+ matches one or more numbers and capital letters together.

The rest of the expression consists of other lookarounds. (?<!^[A-Z0-9 ]*) is another negative lookbehind, where the expression is ^[A-Z0-9 ]*. This means what precedes must not be all capital letters and numbers.

The second lookaround is (?![A-Z0-9 ]$), which is a negative lookahead. This means what follows must not be all capital letters and numbers.

So, altogether, we are capturing words of all capital letters and numbers, and excluding one-letter, uppercase characters from the start of the line and everything from lines that are all uppercase.

There is at least one weakness here in that the lookarounds in the second alternation expression act independently, so a sentence like "A P1 should connect to the J9" will match J9, but not P1, because everything before P1 is capitalized.

It is possible to get around this issue, but it would almost triple the length of the regex. Trying to do so much in a single regex is seldom, if ever, justfied. You'll be better off breaking up the work either into multiple regexes or a combination of regex and standard string processing commands in your programming language of choice.

Centering the image in Bootstrap

.img-responsive {
     margin: 0 auto;
 }

you can write like above code in your document so no need to add one another class in image tag.

How can you program if you're blind?

harald van Breederode is a well-known Dutch Oracle DBA expert, trainer and presenter who is blind. His blog contains some useful tips for visually impaired people.

Extracting a parameter from a URL in WordPress

In the call back function, use the $request parameter

$parameters = $request->get_params();
echo $parameters['ppc'];

boundingRectWithSize for NSAttributedString returning wrong size

Encountered exactly same issue.

To me, the issue is solved by TTTAttributedLabel's

+ (CGSize)sizeThatFitsAttributedString:(NSAttributedString *)attributedString
                       withConstraints:(CGSize)size
                limitedToNumberOfLines:(NSUInteger)numberOfLines

method, as it provide accurate result.

"Unorderable types: int() < str()"

Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.

Dynamic loading of images in WPF

It is because the Creation was delayed. If you want the picture to be loaded immediately, you can simply add this code into the init phase.

src.CacheOption = BitmapCacheOption.OnLoad;

like this:

src.BeginInit();
src.UriSource = new Uri("picture.jpg", UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();

Is a view faster than a simple query?

Definitely a view is better than a nested query for SQL Server. Without knowing exactly why it is better (until I read Mark Brittingham's post), I had run some tests and experienced almost shocking performance improvements when using a view versus a nested query. After running each version of the query several hundred times in a row, the view version of the query completed in half the time. I'd say that's proof enough for me.

Viewing all `git diffs` with vimdiff

Git accepts kdiff3, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge,
and opendiff as valid diff tools. You can also set up a custom tool. 

git config --global diff.tool vimdiff
git config --global diff.tool kdiff3
git config --global diff.tool meld
git config --global diff.tool xxdiff
git config --global diff.tool emerge
git config --global diff.tool gvimdiff
git config --global diff.tool ecmerge

How can I restart a Java application?

Basically, you can't. At least not in a reliable way. However, you shouldn't need to.

The can't part

To restart a Java program, you need to restart the JVM. To restart the JVM you need to

  1. Locate the java launcher that was used. You may try with System.getProperty("java.home") but there's no guarantee that this will actually point to the launcher that was used to launch your application. (The value returned may not point to the JRE used to launch the application or it could have been overridden by -Djava.home.)

  2. You would presumably want to honor the original memory settings etc (-Xmx, -Xms, …) so you need to figure out which settings where used to start the first JVM. You could try using ManagementFactory.getRuntimeMXBean().getInputArguments() but there's no guarantee that this will reflect the settings used. This is even spelled out in the documentation of that method:

    Typically, not all command-line options to the 'java' command are passed to the Java virtual machine. Thus, the returned input arguments may not include all command-line options.

  3. If your program reads input from Standard.in the original stdin will be lost in the restart.

  4. Lots of these tricks and hacks will fail in the presence of a SecurityManager.

The shouldn't need part

I recommend you to design your application so that it is easy to clean every thing up and after that create a new instance of your "main" class.

Many applications are designed to do nothing but create an instance in the main-method:

public class MainClass {
    ...
    public static void main(String[] args) {
        new MainClass().launch();
    }
    ...
}

By using this pattern, it should be easy enough to do something like:

public class MainClass {
    ...
    public static void main(String[] args) {
        boolean restart;
        do {
            restart = new MainClass().launch();
        } while (restart);
    }
    ...
}

and let launch() return true if and only if the application was shut down in a way that it needs to be restarted.

Declare an empty two-dimensional array in Javascript?

If we don’t use ES2015 and don’t have fill(), just use .apply()

See https://stackoverflow.com/a/47041157/1851492

_x000D_
_x000D_
let Array2D = (r, c, fill) => Array.apply(null, new Array(r)).map(function() {return Array.apply(null, new Array(c)).map(function() {return fill})})_x000D_
_x000D_
console.log(JSON.stringify(Array2D(3,4,0)));_x000D_
console.log(JSON.stringify(Array2D(4,5,1)));
_x000D_
_x000D_
_x000D_

Google Maps API OVER QUERY LIMIT per second limit

Often when you need to show so many points on the map, you'd be better off using the server-side approach, this article explains when to use each:

Geocoding Strategies: https://developers.google.com/maps/articles/geocodestrat

The client-side limit is not exactly "10 requests per second", and since it's not explained in the API docs I wouldn't rely on its behavior.

unix diff side-to-side results?

Enhanced diff command with color, side by side and alias

Let's say the file contents are like:

cat /tmp/test1.txt
1
2
3
4
5
8
9

and

cat /tmp/test2.txt
1
1.5
2
4
5
6
7

Now comparing side-by-side

diff --width=$COLUMNS --suppress-common-lines --side-by-side --color=always /tmp/test1.txt /tmp/test2.txt
                                                                              > 1.5
3                                                                             <
8                                                                             | 6
9                                                                             | 7

You can define alias to use

alias diff='diff --width=$COLUMNS --suppress-common-lines --side-by-side --color=always'

Then new diff result:

diff /tmp/test1.txt /tmp/test2.txt
                                                                              > 1.5
3                                                                             <
8                                                                             | 6
9                                                                             | 7

JVM heap parameters

Apart from standard Heap parameters -Xms and -Xmx it's also good to know -XX:PermSize and -XX:MaxPermSize, which is used to specify size of Perm Gen space because even though you could have space in other generation in heap you can run out of memory if your perm gen space gets full. This link also has nice overview of some important JVM parameters.

Read specific columns from a csv file with csv module?

Use pandas:

import pandas as pd
my_csv = pd.read_csv(filename)
column = my_csv.column_name
# you can also use my_csv['column_name']

Discard unneeded columns at parse time:

my_filtered_csv = pd.read_csv(filename, usecols=['col1', 'col3', 'col7'])

P.S. I'm just aggregating what other's have said in a simple manner. Actual answers are taken from here and here.

Uncaught (in promise) TypeError: Failed to fetch and Cors error

you can use solutions without adding "Access-Control-Allow-Origin": "*", if your server is already using Proxy gateway this issue will not happen because the front and backend will be route in the same IP and port in client side but for development, you need one of this three solution if you don't need extra code 1- simulate the real environment by using a proxy server and configure the front and backend in the same port

2- if you using Chrome you can use the extension called Allow-Control-Allow-Origin: * it will help you to avoid this problem

3- you can use the code but some browsers versions may not support that so try to use one of the previous solutions

the best solution is using a proxy like ngnix its easy to configure and it will simulate the real situation of the production deployment

Running an outside program (executable) in Python?

If using Python 2.7 or higher (especially prior to Python 3.5) you can use the following:

import subprocess
  • subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False) Runs the command described by args. Waits for command to complete, then returns the returncode attribute.
  • subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False) Runs command with arguments. Waits for command to complete. If the return code was zero then returns, otherwise raises CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute

Example: subprocess.check_call([r"C:\pathToYourProgram\yourProgram.exe", "your", "arguments", "comma", "separated"])

In regular Python strings, the \U character combination signals a extended Unicode code point escape.

Here is the link to the documentation: http://docs.python.org/3.2/library/subprocess.html

For Python 3.5+ you can now use run() in many cases: https://docs.python.org/3.5/library/subprocess.html#subprocess.run

Build Error - missing required architecture i386 in file

I fixed it in a different way.The reason why i was getting this error was that i added security.framework twice in my project.I was not able to see security framework in xcode ,i opened the project in finder and found this framework which i deleted and problem solved.

Twitter Bootstrap: Print content of modal window

I was facing two issues Issue 1: all fields were coming one after other and Issue 2 white space at the bottom of the page when used to print from popup.

I Resolved this by

making display none to all body * elements most of them go for visibility hidden which creates space so avoid visibility hidden

    @media print {
        body * {
           display:none;
        width:auto;
        height:auto;
        margin:0px;padding:0px; 
        }
        #printSection, #printSection * {
            display:inline-block!important;
        }
        #printSection {
            position:absolute;
            left:0;
            top:0;  
            margin:0px; 
            page-break-before: none;
            page-break-after: none;
            page-break-inside: avoid;      
        }
#printSection .form-group{

      width:100%!important;
      float:left!important;
      page-break-after: avoid;
    }
#printSection label{
        float:left!important;
        width:200px!important;
        display:inline-block!important;
      }

#printSection .form-control.search-input{
        float:left!important;
        width:200px!important;
        display: inline-block!important;
      }
}

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

This is what worked for me: Using Gradle 4.8.1

buildscript {
    ext.kotlin_version = '1.1.1' 
repositories {
    jcenter()
    google()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.1.0'}
}
allprojects {
    repositories {
        mavenLocal()
        jcenter()
        google()
        maven {
            url "$rootDir/../node_modules/react-native/android"
        }
    maven {
            url 'https://dl.bintray.com/kotlin/kotlin-dev/'
    }
  }
}   

Empty brackets '[]' appearing when using .where

Stuarts' answer is correct, but if you are not sure if you are saving the titles in lowercase, you can also make a case insensitive search

There are a lot of answered questions in Stack Overflow with more data on this:

Example 1

Example 2

How to use LocalBroadcastManager?

In Eclipse, eventually I had to add Compatibility/Support Library by right-clicking on my project and selecting:

Android Tools -> Add Support Library

Once it was added, then I was able to use LocalBroadcastManager class in my code.


Android Compatibility Library

Recording video feed from an IP camera over a network

Why don't you consider www.cameraftp.com? it supports image upload and online viewer

Calling Non-Static Method In Static Method In Java

It sounds like the method really should be static (i.e. it doesn't access any data members and it doesn't need an instance to be invoked on). Since you used the term "static class", I understand that the whole class is probably dedicated to utility-like methods that could be static.

However, Java doesn't allow the implementation of an interface-defined method to be static. So when you (naturally) try to make the method static, you get the "cannot-hide-the-instance-method" error. (The Java Language Specification mentions this in section 9.4: "Note that a method declared in an interface must not be declared static, or a compile-time error occurs, because static methods cannot be abstract.")

So as long as the method is present in xInterface, and your class implements xInterface, you won't be able to make the method static.

If you can't change the interface (or don't want to), there are several things you can do:

  • Make the class a singleton: make the constructor private, and have a static data member in the class to hold the only existing instance. This way you'll be invoking the method on an instance, but at least you won't be creating new instances each time you need to call the method.
  • Implement 2 methods in your class: an instance method (as defined in xInterface), and a static method. The instance method will consist of a single line that delegates to the static method.

Fuzzy matching using T-SQL

do it this way

         create table person(
         personid int identity(1,1) primary key,
         firstname varchar(20),
         lastname varchar(20),
         addressindex int,
         sound varchar(10)
         )

and later on create a trigger

         create trigger trigoninsert for dbo.person
         on insert 
         as
         declare @personid int;
         select @personid=personid from inserted;
         update person
         set sound=soundex(firstname) where personid=@personid;

now what i can do is i can create a procedure which looks something like this

         create procedure getfuzzi(@personid int)
          as
         declare @sound varchar(10);
         set @sound=(select sound from person where personid=@personid;
         select personid,firstname,lastname,addressindex from person
         where sound=@sound

this will return you all the names that are nearly in match with the names provided by for a particular personid

Making sure at least one checkbox is checked

Vanilla JS:

var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable

function activitiesReset() {
    var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
        for (var i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].checked) {
                return true;
            }
        }
        return false;
    }
    error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead. 
        if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
            error[2].style.display = 'block'; // red error label is now visible.
        }
}

for (var i=0; i<checkboxes.length; i++) {  // whenever a checkbox is checked or unchecked, activitiesReset runs.
    checkboxes[i].addEventListener('change', activitiesReset);
}


Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});

Difference between style = "position:absolute" and style = "position:relative"

position: relative act as a parent element position: absolute act a child of relative position. you can see the below example

.postion-element{
   position:relative;
   width:200px;
   height:200px;
   background-color:green;
 }
.absolute-element{
  position:absolute;
  top:10px;
  left:10px;
  background-color:blue;
 }

Iterating through populated rows

For the benefit of anyone searching for similar, see worksheet .UsedRange,
e.g. ? ActiveSheet.UsedRange.Rows.Count
and loops such as
For Each loopRow in Sheets(1).UsedRange.Rows: Print loopRow.Row: Next

how to check if input field is empty

use .val(), it will return the value of the <input>

$("#spa").val().length > 0

And you had a typo, length not lenght.

Counting the number of elements with the values of x in a vector

One option could be to use vec_count() function from the vctrs library:

vec_count(numbers)

   key count
1  435     3
2   67     2
3    4     2
4   34     2
5   56     2
6   23     2
7  456     1
8   43     1
9  453     1
10   5     1
11 657     1
12 324     1
13  54     1
14 567     1
15  65     1

The default ordering puts the most frequent values at top. If looking for sorting according keys (a table()-like output):

vec_count(numbers, sort = "key")

   key count
1    4     2
2    5     1
3   23     2
4   34     2
5   43     1
6   54     1
7   56     2
8   65     1
9   67     2
10 324     1
11 435     3
12 453     1
13 456     1
14 567     1
15 657     1

How can I create an executable JAR with dependencies using Maven?

You can add the following to your pom.xml:

<build>
<defaultGoal>install</defaultGoal>
<plugins>
  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
      <source>1.6</source>
      <target>1.6</target>
    </configuration>
  </plugin>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.3.1</version>
    <configuration>
      <archive>
        <manifest>
          <addClasspath>true</addClasspath>
          <mainClass>com.mycompany.package.MainClass</mainClass>
        </manifest>
      </archive>
    </configuration>
  </plugin>
  <plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
      <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
      <archive>
        <manifest>
          <mainClass>com.mycompany.package.MainClass</mainClass>
        </manifest>
      </archive>
    </configuration>
    <executions>
      <execution>
        <id>make-my-jar-with-dependencies</id>
        <phase>package</phase>
        <goals>
          <goal>single</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</plugins>
</build>

Afterwards you have to switch via the console to the directory, where the pom.xml is located. Then you have to execute mvn assembly:single and then your executable JAR file with dependencies will be hopefully build. You can check it when switching to the output (target) directory with cd ./target and starting your jar with a command similiar to java -jar mavenproject1-1.0-SNAPSHOT-jar-with-dependencies.jar.

I tested this with Apache Maven 3.0.3.

Base64 Decoding in iOS 7+

In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL:

NSURL *URL = [NSURL URLWithString:
      [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
           base64String]];

return [NSData dataWithContentsOfURL:URL];

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

You need to only depend on one major version of angular, so update all modules depending on angular 2.x :

  • update @angular/flex-layout to ^2.0.0-beta.9
  • update @angular/material to ^2.0.0-beta.12
  • update angularfire2 to ^4.0.0-rc.2
  • update zone.js to ^0.8.18
  • update webpack to ^3.8.1
  • add @angular/[email protected] (required for @angular/material)
  • replace angular2-google-maps by @agm/[email protected] (new name)

How to check if an excel cell is empty using Apache POI?

This is the safest and most concise way I see as of POI 3.1.7 up to POI 4:

boolean isBlankCell = CellType.BLANK == cell.getCellTypeEnum();
boolean isEmptyStringCell = CellType.STRING == cell.getCellTypeEnum() && cell.getStringCellValue().trim().isEmpty(); 

if (isBlankCell || isEmptyStringCell) {
    ...

As of POI 4 getCellTypeEnum() will be deprecated if favor of getCellType() but the return type should stay the same.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

I found that max_new_space_size is not an option in node 4.1.1 and max_old_space_size alone did not solve my problem. I am adding the following to my shebang and the combination of these seems to work:

#!/usr/bin/env node --max_old_space_size=4096 --optimize_for_size --max_executable_size=4096 --stack_size=4096

[EDIT]: 4096 === 4GB of memory, if your device is low on memory you may want to choose a smaller amount.

[UPDATE]: Also discovered this error while running grunt which previously was run like so:

./node_modules/.bin/grunt

After updating the command to the following it stopped having memory errors:

node --max_old_space_size=2048 ./node_modules/.bin/grunt 

No log4j2 configuration file found. Using default configuration: logging only errors to the console

Make sure that you have put a log4j2.* file instead of a log4j.* file under .../src/main/resources folder.

.gitignore for Visual Studio Projects and Solutions

There's an online tool which allow you to generate .gitignore file based on your OS, IDE, language, etc. Take a look at http://www.gitignore.io/.

enter image description here

On 8/20/2014, here's the file that is generated for Visual Studio + Windows.

# Created by http://www.gitignore.io

### VisualStudio ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

# User-specific files
*.suo
*.user
*.sln.docstates

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
build/
bld/
[Bb]in/
[Oo]bj/

# Roslyn cache directories
*.ide/

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

#NUNIT
*.VisualState.xml
TestResult.xml

# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c

*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc

# Chutzpah Test files
_Chutzpah*

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile

# Visual Studio profiler
*.psess
*.vsp
*.vspx

# TFS 2012 Local Workspace
$tf/

# Guidance Automation Toolkit
*.gpState

# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user

# JustCode is a .NET coding addin-in
.JustCode

# TeamCity is a build add-in
_TeamCity*

# DotCover is a Code Coverage Tool
*.dotCover

# NCrunch
_NCrunch_*
.*crunch*.local.xml

# MightyMoose
*.mm.*
AutoTest.Net/

# Web workbench (sass)
.sass-cache/

# Installshield output folder
[Ee]xpress/

# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
publish/

# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings 
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj

# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# If using the old MSBuild-Integrated Package Restore, uncomment this:
#!**/packages/repositories.config

# Windows Azure Build Output
csx/
*.build.csdef

# Windows Store app package directory
AppPackages/

# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/

# RIA/Silverlight projects
Generated_Code/

# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm

# SQL Server files
*.mdf
*.ldf

# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings

# Microsoft Fakes
FakesAssemblies/


### Windows ###
# Windows image file caches
Thumbs.db
ehthumbs.db

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msm
*.msp

How can I edit a view using phpMyAdmin 3.2.4?

In your database table list it should show View in Type column. To edit View:

  1. Click on your View in table list
  2. Click on Structure tab
  3. Click on Edit View under Check All

enter image description here

Hope this help

update: in PHPMyAdmin 4.x, it doesn't show View in Type, but you can still recognize it:

  1. In Row column: It had zero Row
  2. In Action column: It had greyed empty button

Of course it may be just an empty table, but when you open the structure, you will know whether it's a table or a view.

Load and execution sequence of a web page?

Dynatrace AJAX Edition shows you the exact sequence of page loading, parsing and execution.

Conversion of a datetime2 data type to a datetime data type results out-of-range value

Add the below mentioned attribute on the property in your model class.

Attribute = [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
Reference = System.ComponentModel.DataAnnotations.Schema

Initially I forgot to add this attribute. So in my database the constraint was created like

ALTER TABLE [dbo].[TableName] ADD DEFAULT (getdate()) FOR [ColumnName]

and I added this attribute and updated my db then it got changed into

ALTER TABLE [dbo].[TableName] ADD CONSTRAINT [DF_dbo.TableName_ColumnName] DEFAULT (getdate()) FOR [ColumnName]

How do I check if a C++ string is an int?

The accepted answer will give a false positive if the input is a number plus text, because "stol" will convert the firsts digits and ignore the rest.

I like the following version the most, since it's a nice one-liner that doesn't need to define a function and you can just copy and paste wherever you need it.

#include <string>

...

std::string s;

bool has_only_digits = (s.find_first_not_of( "0123456789" ) == std::string::npos);

EDIT: if you like this implementation but you do want to use it as a function, then this should do:

bool has_only_digits(const string s){
  return s.find_first_not_of( "0123456789" ) == string::npos;
}

How to horizontally align ul to center of div?

ul {
      text-align: center;
      list-style: inside;
    }

Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

There is a good article on MDN that explains the theory behind those concepts: https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements

It also explains the important conceptual differences between boundingClientRect's width/height vs offsetWidth/offsetHeight.

Then, to prove the theory right or wrong, you need some tests. That's what I did here: https://github.com/lingtalfi/dimensions-cheatsheet

It's testing for chrome53, ff49, safari9, edge13 and ie11.

The results of the tests prove that the theory is generally right. For the tests, I created 3 divs containing 10 lorem ipsum paragraphs each. Some css was applied to them:

.div1{
    width: 500px;
    height: 300px;
    padding: 10px;
    border: 5px solid black;
    overflow: auto;
}
.div2{
    width: 500px;
    height: 300px;
    padding: 10px;
    border: 5px solid black;
    box-sizing: border-box;
    overflow: auto;
}

.div3{
    width: 500px;
    height: 300px;
    padding: 10px;
    border: 5px solid black;
    overflow: auto;
    transform: scale(0.5);
}

And here are the results:

  • div1

    • offsetWidth: 530 (chrome53, ff49, safari9, edge13, ie11)
    • offsetHeight: 330 (chrome53, ff49, safari9, edge13, ie11)
    • bcr.width: 530 (chrome53, ff49, safari9, edge13, ie11)
    • bcr.height: 330 (chrome53, ff49, safari9, edge13, ie11)

    • clientWidth: 505 (chrome53, ff49, safari9)

    • clientWidth: 508 (edge13)
    • clientWidth: 503 (ie11)
    • clientHeight: 320 (chrome53, ff49, safari9, edge13, ie11)

    • scrollWidth: 505 (chrome53, safari9, ff49)

    • scrollWidth: 508 (edge13)
    • scrollWidth: 503 (ie11)
    • scrollHeight: 916 (chrome53, safari9)
    • scrollHeight: 954 (ff49)
    • scrollHeight: 922 (edge13, ie11)
  • div2

    • offsetWidth: 500 (chrome53, ff49, safari9, edge13, ie11)
    • offsetHeight: 300 (chrome53, ff49, safari9, edge13, ie11)
    • bcr.width: 500 (chrome53, ff49, safari9, edge13, ie11)
    • bcr.height: 300 (chrome53, ff49, safari9)
    • bcr.height: 299.9999694824219 (edge13, ie11)
    • clientWidth: 475 (chrome53, ff49, safari9)
    • clientWidth: 478 (edge13)
    • clientWidth: 473 (ie11)
    • clientHeight: 290 (chrome53, ff49, safari9, edge13, ie11)

    • scrollWidth: 475 (chrome53, safari9, ff49)

    • scrollWidth: 478 (edge13)
    • scrollWidth: 473 (ie11)
    • scrollHeight: 916 (chrome53, safari9)
    • scrollHeight: 954 (ff49)
    • scrollHeight: 922 (edge13, ie11)
  • div3

    • offsetWidth: 530 (chrome53, ff49, safari9, edge13, ie11)
    • offsetHeight: 330 (chrome53, ff49, safari9, edge13, ie11)
    • bcr.width: 265 (chrome53, ff49, safari9, edge13, ie11)
    • bcr.height: 165 (chrome53, ff49, safari9, edge13, ie11)
    • clientWidth: 505 (chrome53, ff49, safari9)
    • clientWidth: 508 (edge13)
    • clientWidth: 503 (ie11)
    • clientHeight: 320 (chrome53, ff49, safari9, edge13, ie11)

    • scrollWidth: 505 (chrome53, safari9, ff49)

    • scrollWidth: 508 (edge13)
    • scrollWidth: 503 (ie11)
    • scrollHeight: 916 (chrome53, safari9)
    • scrollHeight: 954 (ff49)
    • scrollHeight: 922 (edge13, ie11)

So, apart from the boundingClientRect's height value (299.9999694824219 instead of expected 300) in edge13 and ie11, the results confirm that the theory behind this works.

From there, here is my definition of those concepts:

  • offsetWidth/offsetHeight: dimensions of the layout border box
  • boundingClientRect: dimensions of the rendering border box
  • clientWidth/clientHeight: dimensions of the visible part of the layout padding box (excluding scroll bars)
  • scrollWidth/scrollHeight: dimensions of the layout padding box if it wasn't constrained by scroll bars

Note: the default vertical scroll bar's width is 12px in edge13, 15px in chrome53, ff49 and safari9, and 17px in ie11 (done by measurements in photoshop from screenshots, and proven right by the results of the tests).

However, in some cases, maybe your app is not using the default vertical scroll bar's width.

So, given the definitions of those concepts, the vertical scroll bar's width should be equal to (in pseudo code):

  • layout dimension: offsetWidth - clientWidth - (borderLeftWidth + borderRightWidth)

  • rendering dimension: boundingClientRect.width - clientWidth - (borderLeftWidth + borderRightWidth)

Note, if you don't understand layout vs rendering please read the mdn article.

Also, if you have another browser (or if you want to see the results of the tests for yourself), you can see my test page here: http://codepen.io/lingtalfi/pen/BLdBdL

Abstract Class:-Real Time Example

The best example of an abstract class is GenericServlet. GenericServlet is the parent class of HttpServlet. It is an abstract class.

When inheriting 'GenericServlet' in a custom servlet class, the service() method must be overridden.

When to use "ON UPDATE CASCADE"

I think you've pretty much nailed the points!

If you follow database design best practices and your primary key is never updatable (which I think should always be the case anyway), then you never really need the ON UPDATE CASCADE clause.

Zed made a good point, that if you use a natural key (e.g. a regular field from your database table) as your primary key, then there might be certain situations where you need to update your primary keys. Another recent example would be the ISBN (International Standard Book Numbers) which changed from 10 to 13 digits+characters not too long ago.

This is not the case if you choose to use surrogate (e.g. artifically system-generated) keys as your primary key (which would be my preferred choice in all but the most rare occasions).

So in the end: if your primary key never changes, then you never need the ON UPDATE CASCADE clause.

Marc

'str' object does not support item assignment in Python

Another approach if you wanted to swap out a specific character for another character:

def swap(input_string):
   if len(input_string) == 0:
     return input_string
   if input_string[0] == "x":
     return "y" + swap(input_string[1:])
   else:
     return input_string[0] + swap(input_string[1:])

How to execute a program or call a system command from Python

Use the subprocess module in the standard library:

import subprocess
subprocess.run(["ls", "-l"])

The advantage of subprocess.run over os.system is that it is more flexible (you can get the stdout, stderr, the "real" status code, better error handling, etc...).

Even the documentation for os.system recommends using subprocess instead:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

On Python 3.4 and earlier, use subprocess.call instead of .run:

subprocess.call(["ls", "-l"])

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

Have you tried this http://tools.android.com/preview-channel ? Download preview channel. After that, install ADT Preview.

How I can get web page's content and save it into the string variable

I recommend not using WebClient.DownloadString. This is because (at least in .NET 3.5) DownloadString is not smart enough to use/remove the BOM, should it be present. This can result in the BOM () incorrectly appearing as part of the string when UTF-8 data is returned (at least without a charset) - ick!

Instead, this slight variation will work correctly with BOMs:

string ReadTextFromUrl(string url) {
    // WebClient is still convenient
    // Assume UTF8, but detect BOM - could also honor response charset I suppose
    using (var client = new WebClient())
    using (var stream = client.OpenRead(url))
    using (var textReader = new StreamReader(stream, Encoding.UTF8, true)) {
        return textReader.ReadToEnd();
    }
}

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

It appears this has been fixed in MVC4.

You can do this, which worked well for me:

public ActionResult SomeControllerAction()
{
  var jsonResult = Json(veryLargeCollection, JsonRequestBehavior.AllowGet);
  jsonResult.MaxJsonLength = int.MaxValue;
  return jsonResult;
}

How to check python anaconda version installed on Windows 10 PC?

If you want to check the python version in a particular cond environment you can also use conda list python

Unable to use Intellij with a generated sources folder

Whoever wrote that plugin screwed up big time. That's not the way to do it!

Any workaround would be a huge hack, make the plugin developer aware of his bug.

Sorry, that's the only thing to do.


OK here's a hack, directly after your plugin's execution, use the antrun plugin to move the directory somewhere else:

<plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.6</version>
    <executions>
      <execution>
        <phase>process-sources</phase>
        <configuration>
          <target>
            <move todir="${project.build.directory}/generated-sources/toolname/com"
                  overwrite="true">
                <fileset dir="${project.build.directory}/generated-sources/com"/>
            </move>
          </target>
        </configuration>
        <goals>
          <goal>run</goal>
        </goals>
      </execution>
    </executions>
</plugin>

In this example, toolname should be replaced by anything that uniquely identifies the plugin that created the code and com stands for the root of the created packages. If you have multiple package roots, you probably need multiple <move> tasks.

But if the plugin adds the folder as source folder, then you're screwed.

Commit empty folder structure (with git)

This is easy.

tell .gitignore to ignore everything except .gitignore and the folders you want to keep. Put .gitignore into folders that you want to keep in the repo.

Contents of the top-most .gitignore:

# ignore everything except .gitignore and folders that I care about:
*
!images*
!.gitignore

In the nested images folder this is your .gitignore:

# ignore everything except .gitignore
*
!.gitignore

Note, you must spell out in the .gitignore the names of the folders you don't want to be ignored in the folder where that .gitignore is located. Otherwise they are, obviously, ignored.

Your folders in the repo will, obviously, NOT be empty, as each one will have .gitignore in it, but that part can be ignored, right. :)

A simple explanation of Naive Bayes Classification

I realize that this is an old question, with an established answer. The reason I'm posting is that is the accepted answer has many elements of k-NN (k-nearest neighbors), a different algorithm.

Both k-NN and NaiveBayes are classification algorithms. Conceptually, k-NN uses the idea of "nearness" to classify new entities. In k-NN 'nearness' is modeled with ideas such as Euclidean Distance or Cosine Distance. By contrast, in NaiveBayes, the concept of 'probability' is used to classify new entities.

Since the question is about Naive Bayes, here's how I'd describe the ideas and steps to someone. I'll try to do it with as few equations and in plain English as much as possible.

First, Conditional Probability & Bayes' Rule

Before someone can understand and appreciate the nuances of Naive Bayes', they need to know a couple of related concepts first, namely, the idea of Conditional Probability, and Bayes' Rule. (If you are familiar with these concepts, skip to the section titled Getting to Naive Bayes')

Conditional Probability in plain English: What is the probability that something will happen, given that something else has already happened.

Let's say that there is some Outcome O. And some Evidence E. From the way these probabilities are defined: The Probability of having both the Outcome O and Evidence E is: (Probability of O occurring) multiplied by the (Prob of E given that O happened)

One Example to understand Conditional Probability:

Let say we have a collection of US Senators. Senators could be Democrats or Republicans. They are also either male or female.

If we select one senator completely randomly, what is the probability that this person is a female Democrat? Conditional Probability can help us answer that.

Probability of (Democrat and Female Senator)= Prob(Senator is Democrat) multiplied by Conditional Probability of Being Female given that they are a Democrat.

  P(Democrat & Female) = P(Democrat) * P(Female | Democrat) 

We could compute the exact same thing, the reverse way:

  P(Democrat & Female) = P(Female) * P(Democrat | Female) 

Understanding Bayes Rule

Conceptually, this is a way to go from P(Evidence| Known Outcome) to P(Outcome|Known Evidence). Often, we know how frequently some particular evidence is observed, given a known outcome. We have to use this known fact to compute the reverse, to compute the chance of that outcome happening, given the evidence.

P(Outcome given that we know some Evidence) = P(Evidence given that we know the Outcome) times Prob(Outcome), scaled by the P(Evidence)

The classic example to understand Bayes' Rule:

Probability of Disease D given Test-positive = 

               P(Test is positive|Disease) * P(Disease)
     _______________________________________________________________
     (scaled by) P(Testing Positive, with or without the disease)

Now, all this was just preamble, to get to Naive Bayes.

Getting to Naive Bayes'

So far, we have talked only about one piece of evidence. In reality, we have to predict an outcome given multiple evidence. In that case, the math gets very complicated. To get around that complication, one approach is to 'uncouple' multiple pieces of evidence, and to treat each of piece of evidence as independent. This approach is why this is called naive Bayes.

P(Outcome|Multiple Evidence) = 
P(Evidence1|Outcome) * P(Evidence2|outcome) * ... * P(EvidenceN|outcome) * P(Outcome)
scaled by P(Multiple Evidence)

Many people choose to remember this as:

                      P(Likelihood of Evidence) * Prior prob of outcome
P(outcome|evidence) = _________________________________________________
                                         P(Evidence)

Notice a few things about this equation:

  • If the Prob(evidence|outcome) is 1, then we are just multiplying by 1.
  • If the Prob(some particular evidence|outcome) is 0, then the whole prob. becomes 0. If you see contradicting evidence, we can rule out that outcome.
  • Since we divide everything by P(Evidence), we can even get away without calculating it.
  • The intuition behind multiplying by the prior is so that we give high probability to more common outcomes, and low probabilities to unlikely outcomes. These are also called base rates and they are a way to scale our predicted probabilities.

How to Apply NaiveBayes to Predict an Outcome?

Just run the formula above for each possible outcome. Since we are trying to classify, each outcome is called a class and it has a class label. Our job is to look at the evidence, to consider how likely it is to be this class or that class, and assign a label to each entity. Again, we take a very simple approach: The class that has the highest probability is declared the "winner" and that class label gets assigned to that combination of evidences.

Fruit Example

Let's try it out on an example to increase our understanding: The OP asked for a 'fruit' identification example.

Let's say that we have data on 1000 pieces of fruit. They happen to be Banana, Orange or some Other Fruit. We know 3 characteristics about each fruit:

  1. Whether it is Long
  2. Whether it is Sweet and
  3. If its color is Yellow.

This is our 'training set.' We will use this to predict the type of any new fruit we encounter.

Type           Long | Not Long || Sweet | Not Sweet || Yellow |Not Yellow|Total
             ___________________________________________________________________
Banana      |  400  |    100   || 350   |    150    ||  450   |  50      |  500
Orange      |    0  |    300   || 150   |    150    ||  300   |   0      |  300
Other Fruit |  100  |    100   || 150   |     50    ||   50   | 150      |  200
            ____________________________________________________________________
Total       |  500  |    500   || 650   |    350    ||  800   | 200      | 1000
             ___________________________________________________________________

We can pre-compute a lot of things about our fruit collection.

The so-called "Prior" probabilities. (If we didn't know any of the fruit attributes, this would be our guess.) These are our base rates.

 P(Banana)      = 0.5 (500/1000)
 P(Orange)      = 0.3
 P(Other Fruit) = 0.2

Probability of "Evidence"

p(Long)   = 0.5
P(Sweet)  = 0.65
P(Yellow) = 0.8

Probability of "Likelihood"

P(Long|Banana) = 0.8
P(Long|Orange) = 0  [Oranges are never long in all the fruit we have seen.]
 ....

P(Yellow|Other Fruit)     =  50/200 = 0.25
P(Not Yellow|Other Fruit) = 0.75

Given a Fruit, how to classify it?

Let's say that we are given the properties of an unknown fruit, and asked to classify it. We are told that the fruit is Long, Sweet and Yellow. Is it a Banana? Is it an Orange? Or Is it some Other Fruit?

We can simply run the numbers for each of the 3 outcomes, one by one. Then we choose the highest probability and 'classify' our unknown fruit as belonging to the class that had the highest probability based on our prior evidence (our 1000 fruit training set):

P(Banana|Long, Sweet and Yellow) 
      P(Long|Banana) * P(Sweet|Banana) * P(Yellow|Banana) * P(banana)
    = _______________________________________________________________
                      P(Long) * P(Sweet) * P(Yellow)
                      
    = 0.8 * 0.7 * 0.9 * 0.5 / P(evidence)

    = 0.252 / P(evidence)


P(Orange|Long, Sweet and Yellow) = 0


P(Other Fruit|Long, Sweet and Yellow)
      P(Long|Other fruit) * P(Sweet|Other fruit) * P(Yellow|Other fruit) * P(Other Fruit)
    = ____________________________________________________________________________________
                                          P(evidence)

    = (100/200 * 150/200 * 50/200 * 200/1000) / P(evidence)

    = 0.01875 / P(evidence)

By an overwhelming margin (0.252 >> 0.01875), we classify this Sweet/Long/Yellow fruit as likely to be a Banana.

Why is Bayes Classifier so popular?

Look at what it eventually comes down to. Just some counting and multiplication. We can pre-compute all these terms, and so classifying becomes easy, quick and efficient.

Let z = 1 / P(evidence). Now we quickly compute the following three quantities.

P(Banana|evidence) = z * Prob(Banana) * Prob(Evidence1|Banana) * Prob(Evidence2|Banana) ...
P(Orange|Evidence) = z * Prob(Orange) * Prob(Evidence1|Orange) * Prob(Evidence2|Orange) ...
P(Other|Evidence)  = z * Prob(Other)  * Prob(Evidence1|Other)  * Prob(Evidence2|Other)  ...

Assign the class label of whichever is the highest number, and you are done.

Despite the name, Naive Bayes turns out to be excellent in certain applications. Text classification is one area where it really shines.

Hope that helps in understanding the concepts behind the Naive Bayes algorithm.

How do I test if a recordSet is empty? isNull?

I would check the "End of File" flag:

If temp_rst1.EOF Or temp_rst2.EOF Then MsgBox "null"

Git: How to remove remote origin from Git repo

To remove a remote:

git remote remove origin

To add a remote:

git remote add origin yourRemoteUrl

and finally

git push -u origin master

Append a dictionary to a dictionary

The answer I want to give is "use collections.ChainMap", but I just discovered that it was only added in Python 3.3: https://docs.python.org/3.3/library/collections.html#chainmap-objects

You can try to crib the class from the 3.3 source though: http://hg.python.org/cpython/file/3.3/Lib/collections/init.py#l763

Here is a less feature-full Python 2.x compatible version (same author): http://code.activestate.com/recipes/305268-chained-map-lookups/

Instead of expanding/overwriting one dictionary with another using dict.merge, or creating an additional copy merging both, you create a lookup chain that searches both in order. Because it doesn't duplicate the mappings it wraps ChainMap uses very little memory, and sees later modifications to any sub-mapping. Because order matters you can also use the chain to layer defaults (i.e. user prefs > config > env).

Why should I use a container div in HTML?

div tags are used to style the webpage so that it look visually appealing for the users or audience of the website. using container-div in html will make the website look more professional and attractive and therefore more people will want to explore your page.

PHP multiline string with PHP

You cannot run PHP code within a string like that. It just doesn't work. As well, when you're "out" of PHP code (?>), any text outside of the PHP blocks is considered output anyway, so there's no need for the echo statement.

If you do need to do multiline output from with a chunk of PHP code, consider using a HEREDOC:

<?php

$var = 'Howdy';

echo <<<EOL
This is output
And this is a new line
blah blah blah and this following $var will actually say Howdy as well

and now the output ends
EOL;

What are the use cases for selecting CHAR over VARCHAR in SQL?

There is a difference between early performance optimization and using a best practice type of rule. If you are creating new tables where you will always have a fixed length field, it makes sense to use CHAR, you should be using it in that case. This isn't early optimization, but rather implementing a rule of thumb (or best practice).

i.e. - If you have a 2 letter state field, use CHAR(2). If you have a field with the actual state names, use VARCHAR.

Change URL parameters

Another variation on Sujoy's answer. Just changed the variable names & added a namespace wrapper:

window.MyNamespace = window.MyNamespace  || {};
window.MyNamespace.Uri = window.MyNamespace.Uri || {};

(function (ns) {

    ns.SetQueryStringParameter = function(url, parameterName, parameterValue) {

        var otherQueryStringParameters = "";

        var urlParts = url.split("?");

        var baseUrl = urlParts[0];
        var queryString = urlParts[1];

        var itemSeparator = "";
        if (queryString) {

            var queryStringParts = queryString.split("&");

            for (var i = 0; i < queryStringParts.length; i++){

                if(queryStringParts[i].split('=')[0] != parameterName){

                    otherQueryStringParameters += itemSeparator + queryStringParts[i];
                    itemSeparator = "&";
                }
            }
        }

        var newQueryStringParameter = itemSeparator + parameterName + "=" + parameterValue;

        return baseUrl + "?" + otherQueryStringParameters + newQueryStringParameter;
    };

})(window.MyNamespace.Uri);

Useage is now:

var changedUrl = MyNamespace.Uri.SetQueryStringParameter(originalUrl, "CarType", "Ford");

Can I call an overloaded constructor from another constructor of the same class in C#?

No, You can't do that, the only place you can call the constructor from another constructor in C# is immediately after ":" after the constructor. for example

class foo
{
    public foo(){}
    public foo(string s ) { }
    public foo (string s1, string s2) : this(s1) {....}

}

How can I check if the current date/time is past a set date/time?

Since PHP >= 5.2.2 you can use the DateTime class as such:

if (new DateTime() > new DateTime("2010-05-15 16:00:00")) {
    # current time is greater than 2010-05-15 16:00:00
    # in other words, 2010-05-15 16:00:00 has passed
}

The string passed to the DateTime constructor is parsed according to these rules.


Note that it is also possible to use time and strtotime functions. See original answer.

Python: Converting string into decimal number

You will need to use strip() because of the extra bits in the strings.

A2 = [float(x.strip('"')) for x in A1]

C++ convert string to hexadecimal and vice versa

This is a bit faster:

static const char* s_hexTable[256] = 
{
    "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11",
    "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23",
    "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35",
    "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47",
    "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59",
    "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b",
    "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d",
    "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
    "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1",
    "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3",
    "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5",
    "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
    "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9",
    "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb",
    "fc", "fd", "fe", "ff"
};

// Convert binary data sequence [beginIt, endIt) to hexadecimal string
void dataToHexString(const uint8_t*const beginIt, const uint8_t*const endIt, string& str)
{
    str.clear();
    str.reserve((endIt - beginIt) * 2);
    for(const uint8_t* it(beginIt); it != endIt; ++it)
    {
        str += s_hexTable[*it];
    }
}

Setting up enviromental variables in Windows 10 to use java and javac

To find the env vars dialog in Windows 10:

Right Click Start
>>  Click Control Panel  (Or you may have System in the list)
>>  Click System
>>  Click Advanced system settings
>>  Go to the Advanced Tab
>>  Click the "Environment Variables..." button at the bottom of that dialog page.

What's a good hex editor/viewer for the Mac?

  1. Open file with Xcode and press Command + Shift + J
  2. Right click file name in left pane
  3. Open as -> Hex

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

How to remove an item from an array in AngularJS scope?

You can also use this

$scope.persons = $filter('filter')($scope.persons , { id: ('!' + person.id) });

jQuery Mobile Page refresh mechanism

function refreshPage()
{
    jQuery.mobile.changePage(window.location.href, {
        allowSamePageTransition: true,
        transition: 'none',
        reloadPage: true
    });
}

Taken from here http://scottwb.com/blog/2012/06/29/reload-the-same-page-without-blinking-on-jquery-mobile/ also tested on jQuery Mobile 1.2.0

How to calculate time difference in java?

Just like any other language; convert your time periods to a unix timestamp (ie, seconds since the Unix epoch) and then simply subtract. Then, the resulting seconds should be used as a new unix timestamp and read formatted in whatever format you want.

Ah, give the above poster (genesiss) his due credit, code's always handy ;) Though, you now have an explanation as well :)

Return a value if no rows are found in Microsoft tSQL

@hai-phan's answer using LEFT JOIN is the key, but it might be a bit hard to follow. I had a complicated query that may also return nothing. I just simplified his answer to my need. It's easy to apply to query with many columns.

;WITH CTE AS (
  -- SELECT S.Id, ...
  -- FROM Sites S WHERE Id = @SiteId
  -- EXCEPT SOME CONDITION.
  -- Whatever your query is
)
SELECT CTE.* -- If you want something else instead of NULL, use COALESCE.
FROM (SELECT @SiteId AS ID) R
LEFT JOIN CTE ON CTE.Id = R.ID

Update: This answer on SqlServerCentral is the best. It utilizes this feature of MAX - "MAX returns NULL when there is no row to select."

SELECT ISNULL(MAX(value), 0) FROM table WHERE Id = @SiteId

How to override the [] operator in Python?

You are looking for the __getitem__ method. See http://docs.python.org/reference/datamodel.html, section 3.4.6

How do I convert an interval into a number of hours with postgres?

         select date 'now()' - date '1955-12-15';

Here is the simple query which calculates total no of days.

Calendar Recurring/Repeating Events - Best Storage Method

I developed an esoteric programming language just for this case. The best part about it is that it is schema less and platform independent. You just have to write a selector program, for your schedule, syntax of which is constrained by the set of rules described here -

https://github.com/tusharmath/sheql/wiki/Rules

The rules are extendible and you can add any sort of customization based on the kind of repetition logic you want to perform, without worrying about schema migrations etc.

This is a completely different approach and might have some disadvantages of its own.

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

How to push JSON object in to array using javascript

Observation

  • If there is a single object and you want to push whole object into an array then no need to iterate the object.

Try this :

_x000D_
_x000D_
var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};_x000D_
_x000D_
var data = [];_x000D_
data.push(feed);_x000D_
_x000D_
console.log(data);
_x000D_
_x000D_
_x000D_

Instead of :

_x000D_
_x000D_
var my_json = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};_x000D_
_x000D_
var data = [];_x000D_
for(var i in my_json) {_x000D_
    data.push(my_json[i]);_x000D_
}_x000D_
_x000D_
console.log(data);
_x000D_
_x000D_
_x000D_

Change "on" color of a Switch

<androidx.appcompat.widget.SwitchCompat
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:thumbTint="@color/white"
                app:trackTint="@drawable/checker_track"/>

And inside checker_track.xml:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/lightish_blue" android:state_checked="true"/>
    <item android:color="@color/hint" android:state_checked="false"/>
</selector>

pass parameter by link_to ruby on rails

Try:

<%= link_to "Add to cart", {:controller => "car", :action => "add_to_cart", :car => car.id }%>

and then in your controller

@car = Car.find(params[:car])

which, will find in your 'cars' table (as with rails pluralization) in your DB a car with id == to car.id

hope it helps! happy coding

more than a year later, but if you see it or anyone does, i could use the points ;D

Authentication versus Authorization

In short, please. :-)

Authentication = login + password (who you are)

Authorization = permissions (what you are allowed to do)

Short "auth" is most likely to refer either to the first one or to both.

to call onChange event after pressing Enter key

You can use event.key

_x000D_
_x000D_
function Input({onKeyPress}) {_x000D_
  return (_x000D_
    <div>_x000D_
      <h2>Input</h2>_x000D_
      <input type="text" onKeyPress={onKeyPress}/>_x000D_
    </div>_x000D_
  )_x000D_
}_x000D_
_x000D_
class Form extends React.Component {_x000D_
  state = {value:""}_x000D_
_x000D_
  handleKeyPress = (e) => {_x000D_
    if (e.key === 'Enter') {_x000D_
      this.setState({value:e.target.value})_x000D_
    }_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return (_x000D_
      <section>_x000D_
        <Input onKeyPress={this.handleKeyPress}/>_x000D_
        <br/>_x000D_
        <output>{this.state.value}</output>_x000D_
      </section>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <Form />,_x000D_
  document.getElementById("react")_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<div id="react"></div>
_x000D_
_x000D_
_x000D_

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

Python Pandas merge only certain columns

This is to merge selected columns from two tables.

If table_1 contains t1_a,t1_b,t1_c..,id,..t1_z columns, and table_2 contains t2_a, t2_b, t2_c..., id,..t2_z columns, and only t1_a, id, t2_a are required in the final table, then

mergedCSV = table_1[['t1_a','id']].merge(table_2[['t2_a','id']], on = 'id',how = 'left')
# save resulting output file    
mergedCSV.to_csv('output.csv',index = False)

Function to calculate R2 (R-squared) in R

Why not this:

rsq <- function(x, y) summary(lm(y~x))$r.squared
rsq(obs, mod)
#[1] 0.8560185

How to Select Every Row Where Column Value is NOT Distinct

The thing that is incorrect with your query is that you are grouping by email and name, that forms a group of each unique set of email and name combined together and hence

aaron and [email protected]
christy and [email protected]
john and [email protected]

are treated as 3 different groups rather all belonging to 1 single group.

Please use the query as given below :

select emailaddress,customername from customers where emailaddress in
(select emailaddress from customers group by emailaddress having count(*) > 1)

Get index of a key/value pair in a C# dictionary based on the value

There's no such concept of an "index" within a dictionary - it's fundamentally unordered. Of course when you iterate over it you'll get the items in some order, but that order isn't guaranteed and can change over time (particularly if you add or remove entries).

Obviously you can get the key from a KeyValuePair just by using the Key property, so that will let you use the indexer of the dictionary:

var pair = ...;
var value = dictionary[pair.Key];
Assert.AreEqual(value, pair.Value);

You haven't really said what you're trying to do. If you're trying to find some key which corresponds to a particular value, you could use:

var key = dictionary.Where(pair => pair.Value == desiredValue)
                    .Select(pair => pair.Key)
                    .FirstOrDefault();

key will be null if the entry doesn't exist.

This is assuming that the key type is a reference type... if it's a value type you'll need to do things slightly differently.

Of course, if you really want to look up values by key, you should consider using another dictionary which maps the other way round in addition to your existing dictionary.

Set timeout for ajax (jQuery)

use the full-featured .ajax jQuery function. compare with https://stackoverflow.com/a/3543713/1689451 for an example.

without testing, just merging your code with the referenced SO question:

target = $(this).attr('data-target');

$.ajax({
    url: $(this).attr('href'),
    type: "GET",
    timeout: 2000,
    success: function(response) { $(target).modal({
        show: true
    }); },
    error: function(x, t, m) {
        if(t==="timeout") {
            alert("got timeout");
        } else {
            alert(t);
        }
    }
});?

Creating a button in Android Toolbar

Toolbar customization can done by following ways

write button and textViews code inside toolbar as shown below

<android.support.v7.widget.Toolbar
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <Button
      android:layout_width="wrap_content"
        android:layout_height="@dimen/btn_height_small"
        android:text="Departure"
        android:layout_gravity="right"
        />
</android.support.v7.widget.Toolbar>

Other way is to use item menu as shown below

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

How to check if an element is off-screen

Well... I've found some issues in every proposed solution here.

  • You should be able to choose if you want entire element to be on screen or just any part of it
  • Proposed solutions fails if element is higher/wider than window and kinda covers browser window.

Here is my solution that include jQuery .fn instance function and expression. I've created more variables inside my function than I could, but for complex logical problem I like to divide it into smaller, clearly named pieces.

I'm using getBoundingClientRect method that returns element position relatively to the viewport so I don't need to care about scroll position

Useage:

$(".some-element").filter(":onscreen").doSomething();
$(".some-element").filter(":entireonscreen").doSomething();
$(".some-element").isOnScreen(); // true / false
$(".some-element").isOnScreen(true); // true / false (partially on screen)
$(".some-element").is(":onscreen"); // true / false (partially on screen)
$(".some-element").is(":entireonscreen"); // true / false 

Source:

$.fn.isOnScreen = function(partial){

    //let's be sure we're checking only one element (in case function is called on set)
    var t = $(this).first();

    //we're using getBoundingClientRect to get position of element relative to viewport
    //so we dont need to care about scroll position
    var box = t[0].getBoundingClientRect();

    //let's save window size
    var win = {
        h : $(window).height(),
        w : $(window).width()
    };

    //now we check against edges of element

    //firstly we check one axis
    //for example we check if left edge of element is between left and right edge of scree (still might be above/below)
    var topEdgeInRange = box.top >= 0 && box.top <= win.h;
    var bottomEdgeInRange = box.bottom >= 0 && box.bottom <= win.h;

    var leftEdgeInRange = box.left >= 0 && box.left <= win.w;
    var rightEdgeInRange = box.right >= 0 && box.right <= win.w;


    //here we check if element is bigger then window and 'covers' the screen in given axis
    var coverScreenHorizontally = box.left <= 0 && box.right >= win.w;
    var coverScreenVertically = box.top <= 0 && box.bottom >= win.h;

    //now we check 2nd axis
    var topEdgeInScreen = topEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );
    var bottomEdgeInScreen = bottomEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );

    var leftEdgeInScreen = leftEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );
    var rightEdgeInScreen = rightEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );

    //now knowing presence of each edge on screen, we check if element is partially or entirely present on screen
    var isPartiallyOnScreen = topEdgeInScreen || bottomEdgeInScreen || leftEdgeInScreen || rightEdgeInScreen;
    var isEntirelyOnScreen = topEdgeInScreen && bottomEdgeInScreen && leftEdgeInScreen && rightEdgeInScreen;

    return partial ? isPartiallyOnScreen : isEntirelyOnScreen;

};

$.expr.filters.onscreen = function(elem) {
  return $(elem).isOnScreen(true);
};

$.expr.filters.entireonscreen = function(elem) {
  return $(elem).isOnScreen(true);
};

Int to byte array

Most of the answers here are either 'UnSafe" or not LittleEndian safe. BitConverter is not LittleEndian safe. So building on an example in here (see the post by PZahra) I made a LittleEndian safe version simply by reading the byte array in reverse when BitConverter.IsLittleEndian == true

void Main(){    
    Console.WriteLine(BitConverter.IsLittleEndian); 
    byte[] bytes = BitConverter.GetBytes(0xdcbaabcdfffe1608);
    //Console.WriteLine(bytes); 
    string hexStr = ByteArrayToHex(bytes);
    Console.WriteLine(hexStr);
}

public static string ByteArrayToHex(byte[] data) 
{ 
   char[] c = new char[data.Length * 2]; 
   byte b; 
  if(BitConverter.IsLittleEndian)
  {
        //read the byte array in reverse
        for (int y = data.Length -1, x = 0; y >= 0; --y, ++x) 
        { 
            b = ((byte)(data[y] >> 4)); 
            c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30); 
            b = ((byte)(data[y] & 0xF)); 
            c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30); 
        }               
    }
    else
    {
        for (int y = 0, x = 0; y < data.Length; ++y, ++x) 
        { 
            b = ((byte)(data[y] >> 4)); 
            c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30); 
            b = ((byte)(data[y] & 0xF)); 
            c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30); 
        }
    }
    return String.Concat("0x",new string(c));
}

It returns this:

True
0xDCBAABCDFFFE1608

which is the exact hex that went into the byte array.

How do I embed a mp4 movie into my html?

If you have an mp4 video residing at your server, and you want the visitors to stream that over your HTML page.

<video width="480" height="320" controls="controls">
<source src="http://serverIP_or_domain/location_of_video.mp4" type="video/mp4">
</video>

Get height of div with no height set in css

Can do this in jQuery. Try all options .height(), .innerHeight() or .outerHeight().

$('document').ready(function() {
    $('#right_div').css({'height': $('#left_div').innerHeight()});
});

Example Screenshot

enter image description here

Hope this helps. Thanks!!

Transaction marked as rollback only: How do I find the cause

There is always a reason why the nested method roll back. If you don't see the reason, you need to change your logger level to debug, where you will see the more details where transaction failed. I changed my logback.xml by adding

<logger name="org.springframework.transaction" level="debug"/>
<logger name="org.springframework.orm.jpa" level="debug"/>

then I got this line in the log:

Participating transaction failed - marking existing transaction as rollback-only

So I just stepped through my code to see where this line is generated and found that there is a catch block which did not throw anything.

private Student add(Student s) {
        try {
            Student retval = studentRepository.save(s);
            return retval;
        } catch (Exception e) {
            
        }
        return null;
    }

JavaScript: function returning an object

In JavaScript, most functions are both callable and instantiable: they have both a [[Call]] and [[Construct]] internal methods.

As callable objects, you can use parentheses to call them, optionally passing some arguments. As a result of the call, the function can return a value.

var player = makeGamePlayer("John Smith", 15, 3);

The code above calls function makeGamePlayer and stores the returned value in the variable player. In this case, you may want to define the function like this:

function makeGamePlayer(name, totalScore, gamesPlayed) {
  // Define desired object
  var obj = {
    name:  name,
    totalScore: totalScore,
    gamesPlayed: gamesPlayed
  };
  // Return it
  return obj;
}

Additionally, when you call a function you are also passing an additional argument under the hood, which determines the value of this inside the function. In the case above, since makeGamePlayer is not called as a method, the this value will be the global object in sloppy mode, or undefined in strict mode.

As constructors, you can use the new operator to instantiate them. This operator uses the [[Construct]] internal method (only available in constructors), which does something like this:

  1. Creates a new object which inherits from the .prototype of the constructor
  2. Calls the constructor passing this object as the this value
  3. It returns the value returned by the constructor if it's an object, or the object created at step 1 otherwise.
var player = new GamePlayer("John Smith", 15, 3);

The code above creates an instance of GamePlayer and stores the returned value in the variable player. In this case, you may want to define the function like this:

function GamePlayer(name,totalScore,gamesPlayed) {
  // `this` is the instance which is currently being created
  this.name =  name;
  this.totalScore = totalScore;
  this.gamesPlayed = gamesPlayed;
  // No need to return, but you can use `return this;` if you want
}

By convention, constructor names begin with an uppercase letter.

The advantage of using constructors is that the instances inherit from GamePlayer.prototype. Then, you can define properties there and make them available in all instances

How do I check if an HTML element is empty using jQuery?

Line breaks are considered as content to elements in FF.

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

Ex:

$("div:empty").text("Empty").css('background', '#ff0000');

In IE both divs are considered empty, in FF an Chrome only the last one is empty.

You can use the solution provided by @qwertymk

if(!/[\S]/.test($('#element').html())) { // for one element
    alert('empty');
}

or

$('.elements').each(function(){  // for many elements
    if(!/[\S]/.test($(this).html())) { 
        // is empty
    }
})

AngularJS disable partial caching on dev machine

If you are talking about cache that is been used for caching of templates without reloading whole page, then you can empty it by something like:

.controller('mainCtrl', function($scope, $templateCache) {
  $scope.clearCache = function() { 
    $templateCache.removeAll();
  }
});

And in markup:

<button ng-click='clearCache()'>Clear cache</button>

And press this button to clear cache.

How to count items in JSON object using command line?

You can also use jq to track down the array within the returned json and then pipe that in to a second jq call to get its length. Suppose it was in a property called records, like {"records":[...]}.

$ curl https://my-source-of-json.com/list | jq -r '.records' | jq length
2
$ 

How do I clone a github project to run locally?

You clone a repository with git clone [url]. Like so,

$ git clone https://github.com/libgit2/libgit2

What causes a Python segmentation fault?

Segmentation fault is a generic one, there are many possible reasons for this:

  • Low memory
  • Faulty Ram memory
  • Fetching a huge data set from the db using a query (if the size of fetched data is more than swap mem)
  • wrong query / buggy code
  • having long loop (multiple recursion)

How do I copy a hash in Ruby?

Since Ruby has a million ways to do it, here's another way using Enumerable:

h0 = {  "John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
h1 = h0.inject({}) do |new, (name, value)| 
    new[name] = value;
    new 
end

How using try catch for exception handling is best practice

You should consider these Design Guidelines for Exceptions

  • Exception Throwing
  • Using Standard Exception Types
  • Exceptions and Performance

https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/exceptions

How do you check "if not null" with Eloquent?

I see this question is a bit old but I ran across it looking for an answer. Although I did not have success with the answers here I think this might be because I'm on PHP 7.2 and Laravel 5.7. or possible because I was just playing around with some data on the CLI using Laravel Tinker.

I have some things I tried that worked for me and others that did not that I hope will help others out.


I did not have success running:

    MyModel::whereNotNull('deleted_by')->get()->all();             // []
    MyModel::where('deleted_by', '<>', null)->get()->all();        // []
    MyModel::where('deleted_by', '!=', null)->get()->all();        // []
    MyModel::where('deleted_by', '<>', '', 'and')->get()->all();   // []
    MyModel::where('deleted_by', '<>', null, 'and')->get()->all(); // []
    MyModel::where('deleted_by', 'IS NOT', null)->get()->all();    // []

All of the above returned an empty array for me


I did however have success running:

    DB::table('my_models')->whereNotNull('deleted_by')->get()->all(); // [ ... ]

This returned all the results in an array as I expected. Note: you can drop the all() and get back a Illuminate\Database\Eloquent\Collection instead of an array if you prefer.

How to source virtualenv activate in a Bash script

When I was learning venv I created a script to remind me how to activate it.

#!/bin/sh
# init_venv.sh
if [ -d "./bin" ];then
  echo "[info] Ctrl+d to deactivate"
  bash -c ". bin/activate; exec /usr/bin/env bash --rcfile <(echo 'PS1=\"(venv)\${PS1}\"') -i"
fi

This has the advantage that it changes the prompt.

Adding to a vector of pair

As many people suggested, you could use std::make_pair.

But I would like to point out another method of doing the same:

revenue.push_back({"string",map[i].second});

push_back() accepts a single parameter, so you could use "{}" to achieve this!

Shell Script Syntax Error: Unexpected End of File

I had this problem when running some script in cygwin. Fixed by running dos2unix on the script, with proper description of problem and solution given in that answer

Using Python 3 in virtualenv

You can specify specific Version of Python while creating environment.
It's mentioned in virtualenv.py

virtualenv --python=python3.5 envname

In some cases this has to be the full path to the executable:

virtualenv --python=/Users/username/.pyenv/versions/3.6.0/bin/python3.6 envname

How -p works

parser.add_option(
    '-p', '--python',
    dest='python',
    metavar='PYTHON_EXE',
    help='The Python interpreter to use, e.g., --python=python3.5 will use the python3.5 '
    'interpreter to create the new environment.  The default is the interpreter that '
    'virtualenv was installed with (%s)' % sys.executable)

Getting the source HTML of the current page from chrome extension

Here is my solution:

chrome.runtime.onMessage.addListener(function(request, sender) {
        if (request.action == "getSource") {
            this.pageSource = request.source;
            var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
            alert(title)
        }
    });

    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
        chrome.tabs.executeScript(
            tabs[0].id,
            { code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
        );
    });

Splitting String and put it on int array

You are doing Integer division, so you will lose the correct length if the user happens to put in an odd number of inputs - that is one problem I noticed. Because of this, when I run the code with an input of '1,2,3,4,5,6,7' my last value is ignored...

Using Font Awesome icon for bullet points, with a single list item element

My solution using standard <ul> and <i> inside <li>

  <ul>
    <li><i class="fab fa-cc-paypal"></i> <div>Paypal</div></li>
    <li><i class="fab fa-cc-apple-pay"></i> <div>Apple Pay</div></li>
    <li><i class="fab fa-cc-stripe"></i> <div>Stripe</div></li>
    <li><i class="fab fa-cc-visa"></i> <div>VISA</div></li>
  </ul>

enter image description here

DEMO HERE

Get current URL from IFRAME

If your iframe is from another domain, (cross domain), the other answers are not going to help you... you will simply need to use this:

var currentUrl = document.referrer;

and - here you've got the main url!

CSS content generation before or after 'input' elements

This is not due to input tags not having any content per-se, but that their content is outside the scope of CSS.

input elements are a special type called replaced elements, these do not support :pseudo selectors like :before and :after.

In CSS, a replaced element is an element whose representation is outside the scope of CSS. These are kind of external objects whose representation is independent of the CSS. Typical replaced elements are <img>, <object>, <video> or form elements like <textarea> and <input>. Some elements, like <audio> or <canvas> are replaced elements only in specific cases. Objects inserted using the CSS content properties are anonymous replaced elements.

Note that this is even referred to in the spec:

This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML).

And more explicitly:

Replaced elements do not have ::before and ::after pseudo-elements

TypeError: 'dict' object is not callable

it's number_map[int(x)], you tried to actually call the map with one argument

Using DISTINCT and COUNT together in a MySQL Query

SELECTING DISTINCT PRODUCT AND DISPLAY COUNT PER PRODUCT

for another answer about this type of question this is my another answer for getting count of product base on product name distinct like this sample below:

Table Value

select * FROM Product

Counted Product Name

SELECT DISTINCT(Product_Name),
(SELECT COUNT(Product_Name) 
from Product  WHERE Product_Name = Prod.Product_Name)  
as `Product_Count`
from Product as Prod

Record Count: 4; Execution Time: 2ms

How to use source: function()... and AJAX in JQuery UI autocomplete

This is completely new working code with sample AJAX call.

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>

<div>
    <div id="project-label">Select a project (type "j" for a start):</div>
    <img id="project-icon" src="images/transparent_1x1.png" class="ui-state-default" alt="" />
    <input id="project" />
    <input type="hidden" id="project-i" />
</div>


@*Auto Complete*@
<script>
    $(function () {

        $("#project").autocomplete({
            minLength: 0,
            source : function( request, response ) {
                $.ajax({
                    url: "http://jsonplaceholder.typicode.com/posts/1/comments",
                    dataType: "jsonp",
                    data: {
                        q: request.term
                    },
                    success: function (data) {
                        response( data );
                    }
                });
            },
            focus: function (event, ui) {
                $("#project").val(ui.item.label);
                return false;
            },
            select: function (event, ui) {
                $("#project").val(ui.item.name);
                $("#project-id").val(ui.item.email);                    

                return false;
            }
        })
            .data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("<li>")
                    .data("ui-autocomplete-item", item)
                    .append("<a> " + item.name + "<br>" + item.email + "</a>")
                    .appendTo(ul);
            };
    });
</script>