Programs & Examples On #Password hash

How to use PHP's password_hash to hash and verify passwords

Using password_hash is the recommended way to store passwords. Don't separate them to DB and files.

Let's say we have the following input:

$password = $_POST['password'];

You first hash the password by doing this:

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

Then see the output:

var_dump($hashed_password);

As you can see it's hashed. (I assume you did those steps).

Now you store this hashed password in your database, ensuring your password column is large enough to hold the hashed value (at least 60 characters or longer). When a user asks to log them in, you check the password input with this hash value in the database, by doing this:

// Query the database for username and password
// ...

if(password_verify($password, $hashed_password)) {
    // If the password inputs matched the hashed password in the database
    // Do something, you know... log them in.
} 

// Else, Redirect them back to the login page.

Official Reference

Password encryption at client side

For a similar situation I used this PKCS #5: Password-Based Cryptography Standard from RSA laboratories. You can avoid storing password, by substituting it with something that can be generated only from the password (in one sentence). There are some JavaScript implementations.

Joining Spark dataframes on the key

inner join with scala

val joinedDataFrame = PersonDf.join(ProfileDf ,"personId")
joinedDataFrame.show

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

I was also facing the same problem. In My case, I am using JUnit 5 with gradle 6.6. I am managing integration test-cases in a separate folder call integ. I have to define a new task in build.gradle file and after adding first line -> useJUnitPlatform() , My problem got solved

check if variable is dataframe

Use isinstance, nothing else:

if isinstance(x, pd.DataFrame):
    ... # do something

PEP8 says explicitly that isinstance is the preferred way to check types

No:  type(x) is pd.DataFrame
No:  type(x) == pd.DataFrame
Yes: isinstance(x, pd.DataFrame)

And don't even think about

if obj.__class__.__name__ = 'DataFrame':
    expect_problems_some_day()

isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

if isinstance(obj, basestring):
    i_am_string(obj)

Specifically for pandas DataFrame objects:

import pandas as pd
isinstance(var, pd.DataFrame)

UIGestureRecognizer on UIImageView

Swift 2.0 Solution

You create a tap, pinch or swipe gesture recognizer in the same manor. Below I'll walk you through 4 steps to getting your recognizer up and running.

4 Steps

1.) Inherit from UIGestureRecognizerDelegate by adding it to your class signature.

class ViewController: UIViewController, UIGestureRecognizerDelegate {...}

2.) Control drag from your image to your viewController to create an IBOutlet:

@IBOutlet weak var tapView: UIImageView!

3.) In your viewDidLoad add the following code:

// create an instance of UITapGestureRecognizer and tell it to run 
// an action we'll call "handleTap:"
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
// we use our delegate
tap.delegate = self
// allow for user interaction
tapView.userInteractionEnabled = true
// add tap as a gestureRecognizer to tapView
tapView.addGestureRecognizer(tap)

4.) Create the function that will be called when your gesture recognizer is tapped. (You can exclude the = nil if you choose).

func handleTap(sender: UITapGestureRecognizer? = nil) {
    // just creating an alert to prove our tap worked!
    let tapAlert = UIAlertController(title: "hmmm...", message: "this actually worked?", preferredStyle: UIAlertControllerStyle.Alert)
    tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
    self.presentViewController(tapAlert, animated: true, completion: nil)
}

Your final code should look something like this:

class ViewController: UIViewController, UIGestureRecognizerDelegate {

    @IBOutlet weak var tapView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
        tap.delegate = self
        tapView.userInteractionEnabled = true
        tapView.addGestureRecognizer(tap)
    }

    func handleTap(sender: UITapGestureRecognizer? = nil) {
        let tapAlert = UIAlertController(title: "hmmm...", message: "this actually worked?", preferredStyle: UIAlertControllerStyle.Alert)
        tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
        self.presentViewController(tapAlert, animated: true, completion: nil)
    }
}

Do Git tags only apply to the current branch?

If you want to tag the branch you are in, then type:

git tag <tag>

and push the branch with:

git push origin --tags

How to catch and print the full exception traceback without halting/exiting the program?

If you're debugging and just want to see the current stack trace, you can simply call:

traceback.print_stack()

There's no need to manually raise an exception just to catch it again.

SQL: How to properly check if a record exists

You can use:

SELECT COUNT(1) FROM MyTable WHERE ... 

or

WHERE [NOT] EXISTS 
( SELECT 1 FROM MyTable WHERE ... )

This will be more efficient than SELECT * since you're simply selecting the value 1 for each row, rather than all the fields.

There's also a subtle difference between COUNT(*) and COUNT(column name):

  • COUNT(*) will count all rows, including nulls
  • COUNT(column name) will only count non null occurrences of column name

JQuery get all elements by class name

Alternative solution (you can replace createElement with a your own element)

var mvar = $('.mbox').wrapAll(document.createElement('div')).closest('div').text();
console.log(mvar);

First Or Create

firstOrCreate() checks for all the arguments to be present before it finds a match.

If you only want to check on a specific field, then use firstOrCreate(['field_name' => 'value']) like

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'abcd',
    'lastName' => 'efgh',
    'veristyName'=>'xyz',
]);

Then it check only the email

MS Access: how to compact current database in VBA

There's also Michael Kaplan's SOON ("Shut One, Open New") add-in. You'd have to chain it, but it's one way to do this.

I can't say I've had much reason to ever want to do this programatically, since I'm programming for end users, and they are never using anything but the front end in the Access user interface, and there's no reason to regularly compact a properly-designed front end.

Hour from DateTime? in 24 hours format

Using ToString("HH:mm") certainly gives you what you want as a string.

If you want the current hour/minute as numbers, string manipulation isn't necessary; you can use the TimeOfDay property:

TimeSpan timeOfDay = fechaHora.TimeOfDay;
int hour = timeOfDay.Hours;
int minute = timeOfDay.Minutes;

How to create Custom Ratings bar in Android

Making the custom rating bar with layer list and selectors is complex, it is better to override the RatingBar class and create a custom RatingBar. createBackgroundDrawableShape() is the function where you should put your empty state png and createProgressDrawableShape() is the function where you should put your filled state png.

Note: This code will not work with svg for now.

public class CustomRatingBar extends RatingBar {

    @Nullable
    private Bitmap mSampleTile;

    public ShapeDrawableRatingBar(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        setProgressDrawable(createProgressDrawable());
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (mSampleTile != null) {
            final int width = mSampleTile.getWidth() * getNumStars();
            setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0), getMeasuredHeight());
        }
    }

    protected LayerDrawable createProgressDrawable() {
        final Drawable backgroundDrawable = createBackgroundDrawableShape();
        LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{
            backgroundDrawable,
            backgroundDrawable,
            createProgressDrawableShape()
        });

        layerDrawable.setId(0, android.R.id.background);
        layerDrawable.setId(1, android.R.id.secondaryProgress);
        layerDrawable.setId(2, android.R.id.progress);
        return layerDrawable;
    }

    protected Drawable createBackgroundDrawableShape() {
        final Bitmap tileBitmap = drawableToBitmap(getResources().getDrawable(R.drawable.ic_star_empty));
        if (mSampleTile == null) {
            mSampleTile = tileBitmap;
        }
        final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape());
        final BitmapShader bitmapShader = new BitmapShader(tileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
        shapeDrawable.getPaint().setShader(bitmapShader);
        return shapeDrawable;
    }

    protected Drawable createProgressDrawableShape() {
        final Bitmap tileBitmap = drawableToBitmap(getResources().getDrawable(R.drawable.ic_star_full));
        final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape());
        final BitmapShader bitmapShader = new BitmapShader(tileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
        shapeDrawable.getPaint().setShader(bitmapShader);
        return new ClipDrawable(shapeDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
    }

    Shape getDrawableShape() {
        final float[] roundedCorners = new float[]{5, 5, 5, 5, 5, 5, 5, 5};
        return new RoundRectShape(roundedCorners, null, null);
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        int width = drawable.getIntrinsicWidth();
        width = width > 0 ? width : 1;
        int height = drawable.getIntrinsicHeight();
        height = height > 0 ? height : 1;

        final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }
}

How to set image in circle in swift

For Swift 4:

import UIKit

extension UIImageView {

func makeRounded() {
    let radius = self.frame.width/2.0
    self.layer.cornerRadius = radius
    self.layer.masksToBounds = true
   }
}

Bootstrap 4 File Input

I just solved it this way

Html:

<div class="custom-file">
   <input id="logo" type="file" class="custom-file-input">
   <label for="logo" class="custom-file-label text-truncate">Choose file...</label>
</div>

JS:

$('.custom-file-input').on('change', function() { 
   let fileName = $(this).val().split('\\').pop(); 
   $(this).next('.custom-file-label').addClass("selected").html(fileName); 
});

Note: Thanks to ajax333221 for mentioning the .text-truncate class that will hide the overflow within label if the selected file name is too long.

How to Exit a Method without Exiting the Program?

In addition to Mark's answer, you also need to be aware of scope, which (as in C/C++) is specified using braces. So:

if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
    textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;

will always return at that point. However:

if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
{
    textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
    return;
}

will only return if it goes into that if statement.

jQuery UI dialog box not positioned center screen

$('#dlg').dialog({
    title: 'My Dialog',
    left: (parseInt(jQuery(window).width())-1200)/2,
    top:(parseInt(jQuery(window).height())-720)/2,
    width: 1200,
    height: 720,
    closed: false,
    cache: false,
    modal: true,
    toolbar:'#dlg-toolbar'
});

H2 in-memory database. Table not found

Solved by creating a new src/test/resources folder + insert application.properties file, explicitly specifying to create a test dbase :

spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create

Can I recover a branch after its deletion in Git?

If you like to use a GUI, you can perform the entire operation with gitk.

gitk --reflog

This will allow you to see the branch's commit history as if the branch hadn't been deleted. Now simply right click on the most recent commit to the branch and select the menu option Create new branch.

Container is running beyond memory limits

While working with spark in EMR I was having the same problem and setting maximizeResourceAllocation=true did the trick; hope it helps someone. You have to set it when you create the cluster. From the EMR docs:

aws emr create-cluster --release-label emr-5.4.0 --applications Name=Spark \
--instance-type m3.xlarge --instance-count 2 --service-role EMR_DefaultRole --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole --configurations https://s3.amazonaws.com/mybucket/myfolder/myConfig.json

Where myConfig.json should say:

[
  {
    "Classification": "spark",
    "Properties": {
      "maximizeResourceAllocation": "true"
    }
  }
]

How do you run a .bat file from PHP?

on my windows machine 8 machine running IIS 8 I can run the batch file just by putting the bats name and forgettig the path to it. Or by putting the bat in c:\windows\system32 don't ask me how it works but it does. LOL

$test=shell_exec("C:\windows\system32\cmd.exe /c $streamnumX.bat");

Android eclipse DDMS - Can't access data/data/ on phone to pull files

Much simpler than messing around with permissions in the android FS (which always feels like
a hack for me - because i believe there must be a kind of integrated way) is just to:

Allow ADB root access and Restart the deamon with root permissions.

  1. First be sure that ADB can have root access on your device (or emulator):
    (Settings -> Developer Options -> Root-Access for ADB or Apps & ADB.
  2. Restart the ADB-Service with root-permissions:
    Open a command prompt and type: adb.exe root
  3. Restart ADM (Android Device Manager):
    Enjoy browsing all files
  4. To negate this process:
    Type adb.exe unroot in your command prompt.

Run a single migration file

This are the steps to run again this migration file "20150927161307_create_users.rb"

  1. Run the console mode. (rails c)
  2. Copy and past the class which is in that file to the console.

    class CreateUsers < ActiveRecord::Migration
      def change
        create_table :users do |t|
          t.string :name
          t.string :email
          t.timestamps null: false   end
        end
      end
    end
    
  3. Create an instance of the class CreateUsers: c1 = CreateUsers.new

  4. Execute the method change of that instance: c1.change

About "*.d.ts" in TypeScript

d stands for Declaration Files:

When a TypeScript script gets compiled there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript. In the process the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript.

The concept of declaration files is analogous to the concept of header file found in C/C++.

declare module arithmetics {
    add(left: number, right: number): number;
    subtract(left: number, right: number): number;
    multiply(left: number, right: number): number;
    divide(left: number, right: number): number;
}

Type declaration files can be written by hand for existing JavaScript libraries, as has been done for jQuery and Node.js.

Large collections of declaration files for popular JavaScript libraries are hosted on GitHub in DefinitelyTyped and the Typings Registry. A command-line utility called typings is provided to help search and install declaration files from the repositories.

How to fix "containing working copy admin area is missing" in SVN?

I had this error recently, when the files were excluded by settings in my SVN globals. The error was especially nasty since I also deleted the files directly from the repository - and this meant that the above solutions were refusing wouldn't work. In this case, manually deleting the .svn directory from the directory that I removed from SVN allowed me to run an update which then allowed me to commit.

Convert date to day name e.g. Mon, Tue, Wed

Very Simply Short week day name with Month and year

echo date('D, d-M-y');

output

Tue, 16-Feb-21

as per my requirements

return $item->start_time->format("D, d-M");

output

Tue, 16-Feb

How to safely open/close files in python 2.4

See docs.python.org:

When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.

Hence use close() elegantly with try/finally:

f = open('file.txt', 'r')

try:
    # do stuff with f
finally:
    f.close()

This ensures that even if # do stuff with f raises an exception, f will still be closed properly.

Note that open should appear outside of the try. If open itself raises an exception, the file wasn't opened and does not need to be closed. Also, if open raises an exception its result is not assigned to f and it is an error to call f.close().

Correct way to integrate jQuery plugins in AngularJS

i have alreay 2 situations where directives and services/factories didnt play well.

the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).

in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.

i even tried to make a directive with a controller and an isolated-scope

only when i moved everything to a controller and it worked like magic.

example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS

Getting a directory name from a filename

Standard C++ won't do much for you in this regard, since path names are platform-specific. You can manually parse the string (as in glowcoder's answer), use operating system facilities (e.g. http://msdn.microsoft.com/en-us/library/aa364232(v=VS.85).aspx ), or probably the best approach, you can use a third-party filesystem library like boost::filesystem.

jQuery - multiple $(document).ready ...?

$(document).ready(); is the same as any other function. it fires once the document is ready - ie loaded. the question is about what happens when multiple $(document).ready()'s are fired not when you fire the same function within multiple $(document).ready()'s

//this
<div id="target"></div>

$(document).ready(function(){
   jQuery('#target').append('target edit 1<br>');
});
$(document).ready(function(){
   jQuery('#target').append('target edit 2<br>');
});
$(document).ready(function(){
   jQuery('#target').append('target edit 3<br>');
});

//is the same as
<div id="target"></div>

$(document).ready(function(){

    jQuery('#target').append('target edit 1<br>');

    jQuery('#target').append('target edit 2<br>');

    jQuery('#target').append('target edit 3<br>');

});

both will behave exactly the same. the only difference is that although the former will achieve the same results. the latter will run a fraction of a second faster and requires less typing. :)

in conclusion where ever possible only use 1 $(document).ready();

//old answer

They will both get called in order. Best practice would be to combine them. but dont worry if its not possible. the page will not explode.

Check if MySQL table exists or not

$query = mysqli_query('SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME IN ("table1","table2","table3") AND TABLE_SCHEMA="yourschema"');
$tablesExists = array();
while( null!==($row=mysqli_fetch_row($query)) ){
    $tablesExists[] = $row[0];
}

Disable HttpClient logging

I experienced such problem after setting HttpComponentsClientHttpRequestFactory for my rest template.

Setting OkHttpClientHttpRequestFactory should solve problem with trash logging.

Highlight the difference between two strings in PHP

What you are looking for is a "diff algorithm". A quick google search led me to this solution. I did not test it, but maybe it will do what you need.

jQuery preventDefault() not triggered

Try this one:

   $("div.subtab_left li.notebook a").click(function(e) {
    e.preventDefault();
    return false;   
    });

Fastest way to get the first n elements of a List into an Array

Option 1 Faster Than Option 2

Because Option 2 creates a new List reference, and then creates an n element array from the List (option 1 perfectly sizes the output array). However, first you need to fix the off by one bug. Use < (not <=). Like,

String[] out = new String[n];
for(int i = 0; i < n; i++) {
    out[i] = in.get(i);
}

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

_x000D_
_x000D_
const string = "foo";_x000D_
const substring = "oo";_x000D_
_x000D_
console.log(string.includes(substring));
_x000D_
_x000D_
_x000D_

includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

_x000D_
_x000D_
var string = "foo";_x000D_
var substring = "oo";_x000D_
_x000D_
console.log(string.indexOf(substring) !== -1);
_x000D_
_x000D_
_x000D_

Getting Class type from String

Class<?> cls = Class.forName(className);

But your className should be fully-qualified - i.e. com.mycompany.MyClass

Detecting Windows or Linux?

I think It's a best approach to use Apache lang dependency to decide which OS you're running programmatically through Java

import org.apache.commons.lang3.SystemUtils;

public class App {
    public static void main( String[] args ) {
        if(SystemUtils.IS_OS_WINDOWS_7)
            System.out.println("It's a Windows 7 OS");
        if(SystemUtils.IS_OS_WINDOWS_8)
            System.out.println("It's a Windows 8 OS");
        if(SystemUtils.IS_OS_LINUX)
            System.out.println("It's a Linux OS");
        if(SystemUtils.IS_OS_MAC)
            System.out.println("It's a MAC OS");
    }
}

Pip install Matplotlib error with virtualenv

To reduce the required packages to install you just need

apt-get install -y \
    libfreetype6-dev \
    libxft-dev && \
    pip install matplotlib

and you will get the following packages locally installed

Collecting matplotlib
  Downloading matplotlib-2.2.0-cp35-cp35m-manylinux1_x86_64.whl (12.5MB)
Collecting pytz (from matplotlib)
  Downloading pytz-2018.3-py2.py3-none-any.whl (509kB)
Collecting python-dateutil>=2.1 (from matplotlib)
  Downloading python_dateutil-2.6.1-py2.py3-none-any.whl (194kB)
Collecting pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 (from matplotlib)
  Downloading pyparsing-2.2.0-py2.py3-none-any.whl (56kB)
Requirement already satisfied: six>=1.10 in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages (from matplotlib)
Collecting cycler>=0.10 (from matplotlib)
  Downloading cycler-0.10.0-py2.py3-none-any.whl
Collecting kiwisolver>=1.0.1 (from matplotlib)
  Downloading kiwisolver-1.0.1-cp35-cp35m-manylinux1_x86_64.whl (949kB)
Requirement already satisfied: numpy>=1.7.1 in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages (from matplotlib)
Requirement already satisfied: setuptools in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages/setuptools-27.2.0-py3.5.egg (from kiwisolver>=1.0.1->matplotlib)
Installing collected packages: pytz, python-dateutil, pyparsing, cycler, kiwisolver, matplotlib
Successfully installed cycler-0.10.0 kiwisolver-1.0.1 matplotlib-2.2.0 pyparsing-2.2.0 python-dateutil-2.6.1 pytz-2018.3

How to read files from resources folder in Scala?

Onliner solution for Scala >= 2.12

val source_html = Source.fromResource("file.html").mkString

Where is Developer Command Prompt for VS2013?

From VS2013 Menu Select "Tools", then Select "External Tools". Enter as below:

  • Title: "VS2013 Native Tools-Command Prompt" would be good
  • Command: C:\Windows\System32\cmd.exe
  • Arguments: /k "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat"
  • Initial Directory: Select as suits your needs.

Click OK. Now you have command prompt access under the Tools Menu.

Html attributes for EditorFor() in ASP.NET MVC

If you don't want to use Metadata you can use a [UIHint("PeriodType")] attribute to decorate the property or if its a complex type you don't have to decorate anything. EditorFor will then look for a PeriodType.aspx or ascx file in the EditorTemplates folder and use that instead.

What exactly does Perl's "bless" do?

This function tells the entity referenced by REF that it is now an object in the CLASSNAME package, or the current package if CLASSNAME is omitted. Use of the two-argument form of bless is recommended.

Example:

bless REF, CLASSNAME
bless REF

Return Value

This function returns the reference to an object blessed into CLASSNAME.

Example:

Following is the example code showing its basic usage, the object reference is created by blessing a reference to the package's class -

#!/usr/bin/perl

package Person;
sub new
{
    my $class = shift;
    my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
    # Print all the values just for clarification.
    print "First Name is $self->{_firstName}\n";
    print "Last Name is $self->{_lastName}\n";
    print "SSN is $self->{_ssn}\n";
    bless $self, $class;
    return $self;
}

jQuery: Clearing Form Inputs

Demo : http://jsfiddle.net/xavi3r/D3prt/

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');

Original Answer: Resetting a multi-stage form with jQuery


Mike's suggestion (from the comments) to keep checkbox and selects intact!

Warning: If you're creating elements (so they're not in the dom), replace :hidden with [type=hidden] or all fields will be ignored!

$(':input','#myform')
  .removeAttr('checked')
  .removeAttr('selected')
  .not(':button, :submit, :reset, :hidden, :radio, :checkbox')
  .val('');

Combining two expressions (Expression<Func<T, bool>>)

I think this works fine, isn't it ?

Func<T, bool> expr1 = (x => x.Att1 == "a");
Func<T, bool> expr2 = (x => x.Att2 == "b");
Func<T, bool> expr1ANDexpr2 = (x => expr1(x) && expr2(x));
Func<T, bool> expr1ORexpr2 = (x => expr1(x) || expr2(x));
Func<T, bool> NOTexpr1 = (x => !expr1(x));

D3 Appending Text to a SVG Rectangle

Have you tried the SVG text element?

.append("text").text(function(d, i) { return d[whichevernode];})

rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>)

Append the text element as a sibling and work on positioning.

UPDATE

Using g grouping, how about something like this? fiddle

You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)

&& (AND) and || (OR) in IF statements

Yes, the short-circuit evaluation for boolean expressions is the default behaviour in all the C-like family.

An interesting fact is that Java also uses the & and | as logic operands (they are overloaded, with int types they are the expected bitwise operations) to evaluate all the terms in the expression, which is also useful when you need the side-effects.

Copy entire directory contents to another directory?

Neither FileUtils.copyDirectory() nor Archimedes's answer copy directory attributes (file owner, permissions, modification times, etc).

https://stackoverflow.com/a/18691793/14731 provides a complete JDK7 solution that does precisely that.

non static method cannot be referenced from a static context

You're trying to invoke an instance method on the class it self.

You should do:

    Random rand = new Random();
    int a = 0 ; 
    while (!done) { 
        int a = rand.nextInt(10) ; 
    ....

Instead

As I told you here stackoverflow.com/questions/2694470/whats-wrong...

Stylesheet not updating

I had the same problem and it was due to the browser caching the stylesheet. Try refreshing the Cache:

    Cmd + Shift + r (on a mac) OR Ctrl + F5 (on windows)

This will do a hard refresh, and should use the new stylesheet that you uploaded to the server.

creating batch script to unzip a file without additional zip tools

Another approach to this issue could be to create a self extracting executable (.exe) using something like winzip and use this as the install vector rather than the zip file. Similarly, you could use NSIS to create an executable installer and use that instead of the zip.

SQL Server - Convert date field to UTC

I'm a bit late to the game but I needed to do something like this on SQL 2012, I haven't fully tested it yet but here is what I came up with.

CREATE FUNCTION SMS.fnConvertUTC
(
    @DateCST datetime
)
RETURNS DATETIME
AS
BEGIN
    RETURN 
        CASE 
        WHEN @DateCST 
            BETWEEN 
                CASE WHEN @DateCST > '2007-01-01' 
                THEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(@DateCST)) + '-MAR-14 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(@DateCST)) + '-MAR-14 02:00' ) + 1
                ELSE CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(@DateCST)) + '-APR-07 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(@DateCST)) + '-APR-07 02:00' ) + 1 END
            AND
                CASE WHEN @DateCST > '2007-01-01' 
                THEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(@DateCST)) + '-NOV-07 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(@DateCST)) + '-NOV-07 02:00' ) + 1
                ELSE CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(@DateCST)) + '-OCT-31 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(@DateCST)) + '-OCT-31 02:00' ) + 1 END
        THEN DATEADD(HOUR,4,@DateCST)
        ELSE DATEADD(HOUR,5,@DateCST) 
        END
END

Above someone posted a static list DST dates so I wrote the below query to compare this code's output to that list... so far it looks correct.

;WITH DT AS 
( 
    SELECT MyDate = GETDATE() 
    UNION ALL 
    SELECT MyDate = DATEADD(YEAR,-1,MyDate) FROM DT
    WHERE DATEADD(YEAR,-1,MyDate) > DATEADD(YEAR, -30, GETDATE())
)
SELECT 
    SpringForward = CASE 
        WHEN MyDate > '2007-01-01' 
        THEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(MyDate)) + '-MAR-14 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(MyDate)) + '-MAR-14 02:00' ) + 1
        ELSE CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(MyDate)) + '-APR-07 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(MyDate)) + '-APR-07 02:00' ) + 1 END
,   FallBackward  = CASE 
        WHEN MyDate > '2007-01-01' 
        THEN CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(MyDate)) + '-NOV-07 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(MyDate)) + '-NOV-07 02:00' ) + 1
        ELSE CONVERT(DATETIME, CONVERT(VARCHAR,YEAR(MyDate)) + '-OCT-31 02:00') - DATEPART(DW,CONVERT(VARCHAR,YEAR(MyDate)) + '-OCT-31 02:00' ) + 1 END
FROM DT
ORDER BY 1 DESC
SpringForward      FallBackward
----------------   ----------------
2020-03-08 02:00   2020-11-01 02:00
2019-03-10 02:00   2019-11-03 02:00
2018-03-11 02:00   2018-11-04 02:00
2017-03-12 02:00   2017-11-05 02:00
2016-03-13 02:00   2016-11-06 02:00
2015-03-08 02:00   2015-11-01 02:00
2014-03-09 02:00   2014-11-02 02:00
2013-03-10 02:00   2013-11-03 02:00
2012-03-11 02:00   2012-11-04 02:00
2011-03-13 02:00   2011-11-06 02:00
2010-03-14 02:00   2010-11-07 02:00
2009-03-08 02:00   2009-11-01 02:00
2008-03-09 02:00   2008-11-02 02:00
2007-03-11 02:00   2007-11-04 02:00
2006-04-02 02:00   2006-10-29 02:00
2005-04-03 02:00   2005-10-30 02:00
2004-04-04 02:00   2004-10-31 02:00
2003-04-06 02:00   2003-10-26 02:00
2002-04-07 02:00   2002-10-27 02:00
2001-04-01 02:00   2001-10-28 02:00
2000-04-02 02:00   2000-10-29 02:00
1999-04-04 02:00   1999-10-31 02:00
1998-04-05 02:00   1998-10-25 02:00
1997-04-06 02:00   1997-10-26 02:00
1996-04-07 02:00   1996-10-27 02:00
1995-04-02 02:00   1995-10-29 02:00
1994-04-03 02:00   1994-10-30 02:00
1993-04-04 02:00   1993-10-31 02:00
1992-04-05 02:00   1992-10-25 02:00
1991-04-07 02:00   1991-10-27 02:00

(30 row(s) affected)

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

You can create the required headers in a filter too.

@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("in AllowAccessFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest)sRequest;
        HttpServletResponse response = (HttpServletResponse)sResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type"); 
        chain.doFilter(request, response);
    }
    ...
}

.datepicker('setdate') issues, in jQuery

When you trying to call setDate you must provide valid javascript Date object.

queryDate = '2009-11-01';

var parsedDate = $.datepicker.parseDate('yy-mm-dd', queryDate);

$('#datePicker').datepicker('setDate', parsedDate);

This will allow you to use different formats for query date and string date representation in datepicker. This approach is very helpful when you create multilingual site. Another helpful function is formatDate, which formats javascript date object to string.

$.datepicker.formatDate( format, date, settings );

How to ignore the certificate check when ssl

Unity C# Version of this solution:

void Awake()
{
    System.Net.ServicePointManager.ServerCertificateValidationCallback += ValidateCertification;
}

void OnDestroy()
{
    ServerCertificateValidationCallback = null;
}

public static bool ValidateCertification(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}

TypeScript: Property does not exist on type '{}'

let propertyName= data['propertyName'];

iPhone UIView Animation Best Practice

From the UIView reference's section about the beginAnimations:context: method:

Use of this method is discouraged in iPhone OS 4.0 and later. You should use the block-based animation methods instead.

Eg of Block-based Animation based on Tom's Comment

[UIView transitionWithView:mysuperview 
                  duration:0.75
                   options:UIViewAnimationTransitionFlipFromRight
                animations:^{ 
                    [myview removeFromSuperview]; 
                } 
                completion:nil];

SQL Server: Extract Table Meta-Data (description, fields and their data types)

Using Object Catalog Views:

SELECT  T.NAME AS [TABLE NAME], C.NAME AS [COLUMN NAME], P.NAME AS [DATA TYPE], P.MAX_LENGTH AS[SIZE],   CAST(P.PRECISION AS VARCHAR) +‘/’+ CAST(P.SCALE AS VARCHAR) AS [PRECISION/SCALE]
FROM ADVENTUREWORKS.SYS.OBJECTS AS T
JOIN ADVENTUREWORKS.SYS.COLUMNS AS C
ON T.OBJECT_ID=C.OBJECT_ID
JOIN ADVENTUREWORKS.SYS.TYPES AS P
ON C.SYSTEM_TYPE_ID=P.SYSTEM_TYPE_ID
WHERE T.TYPE_DESC=‘USER_TABLE’;

Using Information Schema Views

SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION,
       COLUMN_DEFAULT, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH,
       NUMERIC_PRECISION, NUMERIC_PRECISION_RADIX, NUMERIC_SCALE,
       DATETIME_PRECISION
FROM ADVENTUREWORKS.INFORMATION_SCHEMA.COLUMNS

How do I check if a string contains a specific word?

Check if string contains specific words?

This means the string has to be resolved into words (see note below).

One way to do this and to specify the separators is using preg_split (doc):

<?php

function contains_word($str, $word) {
  // split string into words
  // separators are substrings of at least one non-word character
  $arr = preg_split('/\W+/', $str, NULL, PREG_SPLIT_NO_EMPTY);

  // now the words can be examined each
  foreach ($arr as $value) {
    if ($value === $word) {
      return true;
    }
  }
  return false;
}

function test($str, $word) {
  if (contains_word($str, $word)) {
    echo "string '" . $str . "' contains word '" . $word . "'\n";
  } else {
    echo "string '" . $str . "' does not contain word '" . $word . "'\n" ;
  }
}

$a = 'How are you?';

test($a, 'are');
test($a, 'ar');
test($a, 'hare');

?>

A run gives

$ php -f test.php                   
string 'How are you?' contains word 'are' 
string 'How are you?' does not contain word 'ar'
string 'How are you?' does not contain word 'hare'

Note: Here we do not mean word for every sequence of symbols.

A practical definition of word is in the sense the PCRE regular expression engine, where words are substrings consisting of word characters only, being separated by non-word characters.

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl " word ". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place (..)

angularjs directive call function specified in attribute and pass an argument to it

Not knowing exactly what you want to do... but still here's a possible solution.

Create a scope with a '&'-property in the local scope. It "provides a way to execute an expression in the context of the parent scope" (see the directive documentation for details).

I also noticed that you used a shorthand linking function and shoved in object attributes in there. You can't do that. It is more clear (imho) to just return the directive-definition object. See my code below.

Here's a code sample and a fiddle.

<div ng-app="myApp">
<div ng-controller="myController">
    <div my-method='theMethodToBeCalled'>Click me</div>
</div>
</div>

<script>

   var app = angular.module('myApp',[]);

   app.directive("myMethod",function($parse) {
       var directiveDefinitionObject = {
         restrict: 'A',
         scope: { method:'&myMethod' },
         link: function(scope,element,attrs) {
            var expressionHandler = scope.method();
            var id = "123";

            $(element).click(function( e, rowid ) {
               expressionHandler(id);
            });
         }
       };
       return directiveDefinitionObject;
   });

   app.controller("myController",function($scope) {
      $scope.theMethodToBeCalled = function(id) { 
          alert(id); 
      };
   });

</script>

Complex CSS selector for parent of active child

Unfortunately, there's no way to do that with CSS.

It's not very difficult with JavaScript though:

// JavaScript code:
document.getElementsByClassName("active")[0].parentNode;

// jQuery code:
$('.active').parent().get(0); // This would be the <a>'s parent <li>.

How to copy a char array in C?

If your arrays are not string arrays, use: memcpy(array2, array1, sizeof(array2));

How to get URI from an asset File?

Finally, I found a way to get the path of a file which is present in assets from this answer in Kotlin. Here we are copying the assets file to cache and getting the file path from that cache file.

@Throws(IOException::class)
    fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
            .also {
               if (!it.exists()) {
                it.outputStream().use { cache ->
                    context.assets.open(fileName).use { inputStream ->
                            inputStream.copyTo(cache)
                    }
                  }
                }
            }

Get the path to the file like:

val filePath =  getFileFromAssets(context, "fileName.extension").absolutePath

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

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

Regular expression for extracting tag attributes

Although the advice not to parse HTML via regexp is valid, here's a expression that does pretty much what you asked:

/
   \G                     # start where the last match left off
   (?>                    # begin non-backtracking expression
       .*?                # *anything* until...
       <[Aa]\b            # an anchor tag
    )??                   # but look ahead to see that the rest of the expression
                          #    does not match.
    \s+                   # at least one space
    ( \p{Alpha}           # Our first capture, starting with one alpha
      \p{Alnum}*          # followed by any number of alphanumeric characters
    )                     # end capture #1
    (?: \s* = \s*         # a group starting with a '=', possibly surrounded by spaces.
        (?: (['"])        # capture a single quote character
            (.*?)         # anything else
             \2           # which ever quote character we captured before
        |   ( [^>\s'"]+ ) # any number of non-( '>', space, quote ) chars
        )                 # end group
     )?                   # attribute value was optional
/msx;

"But wait," you might say. "What about *comments?!?!" Okay, then you can replace the . in the non-backtracking section with: (It also handles CDATA sections.)

(?:[^<]|<[^!]|<![^-\[]|<!\[(?!CDATA)|<!\[CDATA\[.*?\]\]>|<!--(?:[^-]|-[^-])*-->)
  • Also if you wanted to run a substitution under Perl 5.10 (and I think PCRE), you can put \K right before the attribute name and not have to worry about capturing all the stuff you want to skip over.

Find the min/max element of an array in JavaScript

create a simple object

var myArray = new Array();

myArray = [10,12,14,100];

var getMaxHeight = {
     hight : function( array ){ return Math.max.apply( Math, array );
}

getMaxHeight.hight(myArray);

How to plot a histogram using Matplotlib in Python with a list of data?

If you haven't installed matplotlib yet just try the command.

> pip install matplotlib

Library import

import matplotlib.pyplot as plot

The histogram data:

plot.hist(weightList,density=1, bins=20) 
plot.axis([50, 110, 0, 0.06]) 
#axis([xmin,xmax,ymin,ymax])
plot.xlabel('Weight')
plot.ylabel('Probability')

Display histogram

plot.show()

And the output is like :

enter image description here

getting the index of a row in a pandas apply function

To answer the original question: yes, you can access the index value of a row in apply(). It is available under the key name and requires that you specify axis=1 (because the lambda processes the columns of a row and not the rows of a column).

Working example (pandas 0.23.4):

>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
   b  c
a      
1  2  3
4  5  6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
   b  c  index_x10
a                 
1  2  3         10
4  5  6         40

Difference between Interceptor and Filter in Spring MVC

Filter: - A filter as the name suggests is a Java class executed by the servlet container for each incoming HTTP request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.

Interceptor: - Spring Interceptors are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context.

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

Actually, the is operator checks for identity and == operator checks for equality.

From the language reference:

Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after a = 1; b = 1, a and b may or may not refer to the same object with the value one, depending on the implementation, but after c = []; d = [], c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that c = d = [] assigns the same object to both c and d.)

So from the above statement we can infer that the strings, which are immutable types, may fail when checked with "is" and may succeed when checked with "is".

The same applies for int and tuple which are also immutable types.

How do I get the old value of a changed cell in Excel VBA?

I have the same problem like you and luckily I have read the solution from this link: http://access-excel.tips/value-before-worksheet-change/

Dim oldValue As Variant
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    oldValue = Target.Value
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
    'do something with oldValue...
End Sub

Note: you must place oldValue variable as a global variable so all subclasses can use it.

Update date + one year in mysql

For multiple interval types use a nested construction as in:

 UPDATE table SET date = DATE_ADD(DATE_ADD(date, INTERVAL 1 YEAR), INTERVAL 1 DAY)

For updating a given date in the column date to 1 year + 1 day

Iterating over all the keys of a map

A Type agnostic solution:

for _, key := range reflect.ValueOf(yourMap).MapKeys() {
    value := s.MapIndex(key).Interface()
    fmt.Println("Key:", key, "Value:", value)
}  

What is the meaning of "$" sign in JavaScript

The $() is the shorthand version of jQuery() used in the jQuery Library.

"The Controls collection cannot be modified because the control contains code blocks"

Place the javascript under a div tag.

<div runat="server"> //div tag must have runat server
  //Your Jave script code goes here....
</div>

It'll work!!

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

I think the Key and IV used for encryption using command line and decryption using your program are not same.

Please note that when you use the "-k" (different from "-K"), the input given is considered as a password from which the key is derived. Generally in this case, there is no need for the "-iv" option as both key and password will be derived from the input given with "-k" option.

It is not clear from your question, how you are ensuring that the Key and IV are same between encryption and decryption.

In my suggestion, better use "-K" and "-iv" option to explicitly specify the Key and IV during encryption and use the same for decryption. If you need to use "-k", then use the "-p" option to print the key and iv used for encryption and use the same in your decryption program.

More details can be obtained at https://www.openssl.org/docs/manmaster/apps/enc.html

How to execute two mysql queries as one in PHP/MYSQL?

Using SQL_CALC_FOUND_ROWS you can't.

The row count available through FOUND_ROWS() is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS statement.

As someone noted in your earlier question, using SQL_CALC_FOUND_ROWS is frequently slower than just getting a count.

Perhaps you'd be best off doing this as as subquery:

SELECT 
 (select count(*) from my_table WHERE Name LIKE '%prashant%') 
as total_rows,
Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;

What is the current choice for doing RPC in Python?

There are some attempts at making SOAP work with python, but I haven't tested it much so I can't say if it is good or not.

SOAPy is one example.

Casting objects in Java

Say you have a superclass Fruit and the subclass Banana and you have a method addBananaToBasket()

The method will not accept grapes for example so you want to make sure that you're adding a banana to the basket.

So:

Fruit myFruit = new Banana();
((Banana)myFruit).addBananaToBasket(); ? This is called casting

How to debug Angular JavaScript Code

IMHO, the most frustrating experience comes from getting / setting a value of a specific scope related to an visual element. I did a lot of breakpoints not only in my own code, but also in angular.js itself, but sometimes it is simply not the most effective way. Although the methods below are very powerful, they are definitely considered to be bad practice if you actually use in production code, so use them wisely!

Get a reference in console from a visual element

In many non-IE browsers, you can select an element by right clicking an element and clicking "Inspect Element". Alternatively you can also click on any element in Elements tab in Chrome, for example. The latest selected element will be stored in variable $0 in console.

Get a scope linked to an element

Depending on whether there exists a directive that creates an isolate scope, you can retrieve the scope by angular.element($0).scope() or angular.element($0).isolateScope() (use $($0).scope() if $ is enabled). This is exactly what you get when you are using the latest version of Batarang. If you are changing the value directly, remember to use scope.$digest() to reflect the changes on UI.

$eval is evil

Not necessarily for debugging. scope.$eval(expression) is very handy when you want to quickly check whether an expression has the expected value.

The missing prototype members of scope

The difference between scope.bla and scope.$eval('bla') is the former does not consider the prototypically inherited values. Use the snippet below to get the whole picture (you cannot directly change the value, but you can use $eval anyway!)

scopeCopy = function (scope) {
    var a = {}; 
    for (x in scope){ 
        if (scope.hasOwnProperty(x) && 
            x.substring(0,1) !== '$' && 
            x !== 'this') {
            a[x] = angular.copy(scope[x])
        }
    }
    return a
};

scopeEval = function (scope) {
    if (scope.$parent === null) {
        return hoho(scope)
    } else {
        return angular.extend({}, haha(scope.$parent), hoho(scope))
    }
};

Use it with scopeEval($($0).scope()).

Where is my controller?

Sometimes you may want to monitor the values in ngModel when you are writing a directive. Use $($0).controller('ngModel') and you will get to check the $formatters, $parsers, $modelValue, $viewValue $render and everything.

Array.push() if does not exist?

a is the array of objects you have

a.findIndex(x => x.property=="WhateverPropertyYouWantToMatch") <0 ? 
a.push(objectYouWantToPush) : console.log("response if object exists");

file_get_contents() how to fix error "Failed to open stream", "No such file"

I hope below solution will work for you all as I was having the same problem with my websites...

For : $json = json_decode(file_get_contents('http://...'));

Replace with below query

$Details= unserialize(file_get_contents('http://......'));

A better way to check if a path exists or not in PowerShell

If you just want an alternative to the cmdlet syntax, specifically for files, use the File.Exists() .NET method:

if(![System.IO.File]::Exists($path)){
    # file with path $path doesn't exist
}

If, on the other hand, you want a general purpose negated alias for Test-Path, here is how you should do it:

# Gather command meta data from the original Cmdlet (in this case, Test-Path)
$TestPathCmd = Get-Command Test-Path
$TestPathCmdMetaData = New-Object System.Management.Automation.CommandMetadata $TestPathCmd

# Use the static ProxyCommand.GetParamBlock method to copy 
# Test-Path's param block and CmdletBinding attribute
$Binding = [System.Management.Automation.ProxyCommand]::GetCmdletBindingAttribute($TestPathCmdMetaData)
$Params  = [System.Management.Automation.ProxyCommand]::GetParamBlock($TestPathCmdMetaData)

# Create wrapper for the command that proxies the parameters to Test-Path 
# using @PSBoundParameters, and negates any output with -not
$WrappedCommand = { 
    try { -not (Test-Path @PSBoundParameters) } catch { throw $_ }
}

# define your new function using the details above
$Function:notexists = '{0}param({1}) {2}' -f $Binding,$Params,$WrappedCommand

notexists will now behave exactly like Test-Path, but always return the opposite result:

PS C:\> Test-Path -Path "C:\Windows"
True
PS C:\> notexists -Path "C:\Windows"
False
PS C:\> notexists "C:\Windows" # positional parameter binding exactly like Test-Path
False

As you've already shown yourself, the opposite is quite easy, just alias exists to Test-Path:

PS C:\> New-Alias exists Test-Path
PS C:\> exists -Path "C:\Windows"
True

The program can't start because cygwin1.dll is missing... in Eclipse CDT

This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.

There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.

iPhone Navigation Bar Title text color

This works for me in Swift:

navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]

jQuery: Get the cursor position of text in input without browser specific code?

You can't do this without some browser specific code, since they implement text select ranged slightly differently. However, there are plugins that abstract this away. For exactly what you're after, there's the jQuery Caret (jCaret) plugin.

For your code to get the position you could do something like this:

$("#myTextInput").bind("keydown keypress mousemove", function() {
  alert("Current position: " + $(this).caret().start);
});

You can test it here.

Comprehensive methods of viewing memory usage on Solaris

"top" is usually available on Solaris.

If not then revert to "vmstat" which is available on most UNIX system.

It should look something like this (from an AIX box)

vmstat

System configuration: lcpu=4 mem=12288MB ent=2.00

kthr    memory              page              faults              cpu
----- ----------- ------------------------ ------------ -----------------------
 r  b   avm   fre  re  pi  po  fr   sr  cy  in   sy  cs us sy id wa    pc    ec
 2  1 1614644 585722   0   0   1  22  104   0 808 29047 2767 12  8 77  3  0.45  22.3

the colums "avm" and "fre" tell you the total memory and free memery.

a "man vmstat" should get you the gory details.

Overloading and overriding

  • Overloading = Multiple method signatures, same method name
  • Overriding = Same method signature (declared virtual), implemented in sub classes

An astute interviewer would have followed up with:

What's the difference between overriding and shadowing?

unknown type name 'uint8_t', MinGW

Try including stdint.h or inttypes.h.

How to create a delay in Swift?

Comparison between different approaches in swift 3.0

1. Sleep

This method does not have a call back. Put codes directly after this line to be executed in 4 seconds. It will stop user from iterating with UI elements like the test button until the time is gone. Although the button is kind of frozen when sleep kicks in, other elements like activity indicator is still spinning without freezing. You cannot trigger this action again during the sleep.

sleep(4)
print("done")//Do stuff here

enter image description here

2. Dispatch, Perform and Timer

These three methods work similarly, they are all running on the background thread with call backs, just with different syntax and slightly different features.

Dispatch is commonly used to run something on the background thread. It has the callback as part of the function call

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
    print("done")
})

Perform is actually a simplified timer. It sets up a timer with the delay, and then trigger the function by selector.

perform(#selector(callback), with: nil, afterDelay: 4.0)

func callback() {
    print("done")
}}

And finally, timer also provides ability to repeat the callback, which is not useful in this case

Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(callback), userInfo: nil, repeats: false)


func callback() {
    print("done")
}}

For all these three method, when you click on the button to trigger them, UI will not freeze and you are allowed to click on it again. If you click on the button again, another timer is set up and the callback will be triggered twice.

enter image description here

In conclusion

None of the four method works good enough just by themselves. sleep will disable user interaction, so the screen "freezes"(not actually) and results bad user experience. The other three methods will not freeze the screen, but you can trigger them multiple times, and most of the times, you want to wait until you get the call back before allowing user to make the call again.

So a better design will be using one of the three async methods with screen blocking. When user click on the button, cover the entire screen with some translucent view with a spinning activity indicator on top, telling user that the button click is being handled. Then remove the view and indicator in the call back function, telling user that the the action is properly handled, etc.

Git diff -w ignore whitespace only at start & end of lines

This is an old question, but is still regularly viewed/needed. I want to post to caution readers like me that whitespace as mentioned in the OP's question is not the same as Regex's definition, to include newlines, tabs, and space characters -- Git asks you to be explicit. See some options here: https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration

As stated, git diff -b or git diff --ignore-space-change will ignore spaces at line ends. If you desire that setting to be your default behavior, the following line adds that intent to your .gitconfig file, so it will always ignore the space at line ends:

git config --global core.whitespace trailing-space

In my case, I found this question because I was interested in ignoring "carriage return whitespace differences", so I needed this:

git diff --ignore-cr-at-eol or git config --global core.whitespace cr-at-eol from here.

You can also make it the default only for that repo by omitting the --global parameter, and checking in the settings file for that repo. For the CR problem I faced, it goes away after check-in if warncrlf or autocrlf = true in the [core] section of the .gitconfig file.

How to calculate difference in hours (decimal) between two dates in SQL Server?

Declare @date1 datetime
Declare @date2 datetime

Set @date1 = '11/20/2009 11:00:00 AM'
Set @date2 = '11/20/2009 12:00:00 PM'

Select Cast(DateDiff(hh, @date1, @date2) as decimal(3,2)) as HoursApart

Result = 1.00

Performing Breadth First Search recursively

I found a very beautiful recursive (even functional) Breadth-First traversal related algorithm. Not my idea, but i think it should be mentioned in this topic.

Chris Okasaki explains his breadth-first numbering algorithm from ICFP 2000 at http://okasaki.blogspot.de/2008/07/breadth-first-numbering-algorithm-in.html very clearly with only 3 pictures.

The Scala implementation of Debasish Ghosh, which i found at http://debasishg.blogspot.de/2008/09/breadth-first-numbering-okasakis.html, is:

trait Tree[+T]
case class Node[+T](data: T, left: Tree[T], right: Tree[T]) extends Tree[T]
case object E extends Tree[Nothing]

def bfsNumForest[T](i: Int, trees: Queue[Tree[T]]): Queue[Tree[Int]] = {
  if (trees.isEmpty) Queue.Empty
  else {
    trees.dequeue match {
      case (E, ts) =>
        bfsNumForest(i, ts).enqueue[Tree[Int]](E)
      case (Node(d, l, r), ts) =>
        val q = ts.enqueue(l, r)
        val qq = bfsNumForest(i+1, q)
        val (bb, qqq) = qq.dequeue
        val (aa, tss) = qqq.dequeue
        tss.enqueue[org.dg.collection.BFSNumber.Tree[Int]](Node(i, aa, bb))
    }
  }
}

def bfsNumTree[T](t: Tree[T]): Tree[Int] = {
  val q = Queue.Empty.enqueue[Tree[T]](t)
  val qq = bfsNumForest(1, q)
  qq.dequeue._1
}

How to check if AlarmManager already has an alarm set?

While almost everyone over here has given the correct answer, no body explained on what basis are the Alarms work

You can actually learn more about AlarmManager and its working here . But here is the quick answer

You see AlarmManager basically schedules a PendingIntent at some time in future. So in order to cancel the scheduled Alarm you need to cancel the PendingIntent.

Always keep note of two things while creating the PendingIntent

PendingIntent.getBroadcast(context,REQUEST_CODE,intent, PendingIntent.FLAG_UPDATE_CURRENT);
  • Request Code - Acts as the unique identifier
  • Flag - Defines the behavior of PendingIntent

Now to check if the Alarm is already scheduled or to cancel the Alarm you just need to get access to the same PendingIntent. This can be done if you use same request code and use FLAG_NO_CREATE like shown below

PendingIntent pendingIntent=PendingIntent.getBroadcast(this,REQUEST_CODE,intent,PendingIntent.FLAG_NO_CREATE);

if (pendingIntent!=null)
   alarmManager.cancel(pendingIntent);

With FLAG_NO_CREATE it will return null if the PendingIntent doesn't already exist. If it already exists it returns reference to the existing PendingIntent

How can I make a CSS table fit the screen width?

table { width: 100%; }

Will not produce the exact result you are expecting, because of all the margins and paddings used in body. So IF scripts are OKAY, then use Jquery.

$("#tableid").width($(window).width());

If not, use this snippet

<style>
    body { margin:0;padding:0; }
</style>
<table width="100%" border="1">
    <tr>
        <td>Just a Test
        </td>
    </tr>
</table>

You will notice that the width is perfectly covering the page.

The main thing is too nullify the margin and padding as I have shown at the body, then you are set.

How can I convert an image into Base64 string using JavaScript?

Basically, if your image is

<img id='Img1' src='someurl'>

then you can convert it like

var c = document.createElement('canvas');
var img = document.getElementById('Img1');
c.height = img.naturalHeight;
c.width = img.naturalWidth;
var ctx = c.getContext('2d');

ctx.drawImage(img, 0, 0, c.width, c.height);
var base64String = c.toDataURL();

Android "Only the original thread that created a view hierarchy can touch its views."

Kotlin Answer

We have to use UI Thread for the job with true way. We can use UI Thread in Kotlin:

runOnUiThread(Runnable {
   //TODO: Your job is here..!
})

@canerkaseler

Pythonic way to combine FOR loop and IF statement

Use intersection or intersection_update

  • intersection :

    a = [2,3,4,5,6,7,8,9,0]
    xyz = [0,12,4,6,242,7,9]
    ans = sorted(set(a).intersection(set(xyz)))
    
  • intersection_update:

    a = [2,3,4,5,6,7,8,9,0]
    xyz = [0,12,4,6,242,7,9]
    b = set(a)
    b.intersection_update(xyz)
    

    then b is your answer

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

I tried many things (even those included in this post) but nothing worked. I decided to clear the data for the google account manager since so many mentioned to delete the account and recreate the account. It worked for my Nexus 7 (Android 4.2.2). Received 17 updates :-).

Go to Settings ? Apps ? ALL ? Google Account Manager ? Clear Data.

Reboot device.

Done.

How to style the parent element when hovering a child element?

A simple jquery solution for those who don't need a pure css solution:

_x000D_
_x000D_
    $(".letter").hover(function() {_x000D_
      $(this).closest("#word").toggleClass("hovered")_x000D_
    });
_x000D_
.hovered {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
_x000D_
.letter {_x000D_
  margin: 20px;_x000D_
  background: lightgray;_x000D_
}_x000D_
_x000D_
.letter:hover {_x000D_
  background: grey;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="word">_x000D_
  <div class="letter">T</div>_x000D_
  <div class="letter">E</div>_x000D_
  <div class="letter">S</div>_x000D_
  <div class="letter">T</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Init method in Spring Controller (annotation version)

You can use

@PostConstruct
public void init() {
   // ...
}

What is a good pattern for using a Global Mutex in C#?

I want to make sure this is out there, because it's so hard to get right:

using System.Runtime.InteropServices;   //GuidAttribute
using System.Reflection;                //Assembly
using System.Threading;                 //Mutex
using System.Security.AccessControl;    //MutexAccessRule
using System.Security.Principal;        //SecurityIdentifier

static void Main(string[] args)
{
    // get application GUID as defined in AssemblyInfo.cs
    string appGuid =
        ((GuidAttribute)Assembly.GetExecutingAssembly().
            GetCustomAttributes(typeof(GuidAttribute), false).
                GetValue(0)).Value.ToString();

    // unique id for global mutex - Global prefix means it is global to the machine
    string mutexId = string.Format( "Global\\{{{0}}}", appGuid );

    // Need a place to store a return value in Mutex() constructor call
    bool createdNew;

    // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
    // edited by 'Marc' to work also on localized systems (don't use just "Everyone") 
    var allowEveryoneRule =
        new MutexAccessRule( new SecurityIdentifier( WellKnownSidType.WorldSid
                                                   , null)
                           , MutexRights.FullControl
                           , AccessControlType.Allow
                           );
    var securitySettings = new MutexSecurity();
    securitySettings.AddAccessRule(allowEveryoneRule);

   // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen
    using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
    {
        // edited by acidzombie24
        var hasHandle = false;
        try
        {
            try
            {
                // note, you may want to time out here instead of waiting forever
                // edited by acidzombie24
                // mutex.WaitOne(Timeout.Infinite, false);
                hasHandle = mutex.WaitOne(5000, false);
                if (hasHandle == false)
                    throw new TimeoutException("Timeout waiting for exclusive access");
            }
            catch (AbandonedMutexException)
            {
                // Log the fact that the mutex was abandoned in another process,
                // it will still get acquired
                hasHandle = true;
            }

            // Perform your work here.
        }
        finally
        {
            // edited by acidzombie24, added if statement
            if(hasHandle)
                mutex.ReleaseMutex();
        }
    }
}

How to add a file to the last commit in git?

Yes, there's a command git commit --amend which is used to "fix" last commit.

In your case it would be called as:

git add the_left_out_file
git commit --amend --no-edit

The --no-edit flag allow to make amendment to commit without changing commit message.

EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.

PHP : send mail in localhost

try this

ini_set("SMTP","aspmx.l.google.com");
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: [email protected]" . "\r\n";
mail("[email protected]","test subject","test body",$headers);

How to find the index of an element in an int array?

Integer[] array = {1, 2, 3, 4, 5, 6};

for (int i = 0; i < array.length; i++) {
    if (array[i] == 4) {
        system.out.println(i);
        break;
    }
}

How to split a string in Haskell?

There is a package for this called split.

cabal install split

Use it like this:

ghci> import Data.List.Split
ghci> splitOn "," "my,comma,separated,list"
["my","comma","separated","list"]

It comes with a lot of other functions for splitting on matching delimiters or having several delimiters.

Proper way to set response status and JSON content in a REST API made with nodejs and express

I am using this in my Express.js application:

app.get('/', function (req, res) {
    res.status(200).json({
        message: 'Welcome to the project-name api'
    });
});

Neither BindingResult nor plain target object for bean name available as request attr

I worked on this same issue and I am sure I have found out the exact reason for it.

Neither BindingResult nor plain target object for bean name 'command' available as request attribute

If your successView property value (name of jsp page) is the same as your input page name, then second value of ModelAndView constructor must be match with the commandName of the input page.

E.g.

index.jsp

<html>
<body>
    <table>
        <tr><td><a href="Login.html">Login</a></td></tr>
    </table>
</body>
</html>

dispatcher-servlet.xml

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="prefix">
        <value>/WEB-INF/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>
<bean id="urlMapping"
    class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="urlMap">
        <map>              
            <entry key="/Login.html">
                <ref bean="userController"/>
            </entry>
        </map>          
    </property>             
</bean>     
 <bean id="userController" class="controller.AddCountryFormController">     
       <property name="commandName"><value>country</value></property>
       <property name="commandClass"><value>controller.Country</value></property>        
       <property name="formView"><value>countryForm</value></property>
       <property name="successView"><value>countryForm</value></property>
   </bean>      

AddCountryFormController.java

package controller;

import javax.servlet.http.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.mvc.SimpleFormController;


public class AddCountryFormController extends SimpleFormController
{

    public AddCountryFormController(){
        setCommandName("Country.class");
    }

    protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,Object command,BindException errors){

            Country country=(Country)command;

            System.out.println("calling onsubmit method !!!!!");

        return new ModelAndView(getSuccessView(),"country",country);

    }

}

Country.java

package controller;

public class Country
{
    private String countryName;

    public void setCountryName(String value){
        countryName=value;
    }

    public String getCountryName(){
        return countryName;
    }

}

countryForm.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
    <form:form commandName="country" method="POST" >
            <table>
                    <tr><td><form:input path="countryName"/></td></tr>
                    <tr><td><input type="submit" value="Save"/></td></tr>
            </table>
    </form:form>
</body>
<html>

Input page commandName="country" ModelAndView Constructor as return new ModelAndView(getSuccessView(),"country",country); Means inputpage commandName==ModeAndView(,"commandName",)

Return outside function error in Python

You can only return from inside a function and not from a loop.

It seems like your return should be outside the while loop, and your complete code should be inside a function.

def func():
    N = int(input("enter a positive integer:"))
    counter = 1
    while (N > 0):
        counter = counter * N
        N -= 1
    return counter  # de-indent this 4 spaces to the left.

print func()

And if those codes are not inside a function, then you don't need a return at all. Just print the value of counter outside the while loop.

Difference between jar and war in Java

WAR stands for Web application ARchive

JAR stands for Java ARchive

enter image description here

Determine Pixel Length of String in Javascript/jQuery?

Put it in an absolutely-positioned div then use clientWidth to get the displayed width of the tag. You can even set the visibility to "hidden" to hide the div:

<div id="text" style="position:absolute;visibility:hidden" >This is some text</div>
<input type="button" onclick="getWidth()" value="Go" />
<script type="text/javascript" >
    function getWidth() {
        var width = document.getElementById("text").clientWidth;
        alert(" Width :"+  width);
    }
</script>

iterating and filtering two lists using java 8

`List<String> unavailable = list1.stream()
                .filter(e -> (list2.stream()
                        .filter(d -> d.getStr().equals(e))
                        .count())<1)
                        .collect(Collectors.toList());`
for this if i change to 
`List<String> unavailable = list1.stream()
                .filter(e -> (list2.stream()
                        .filter(d -> d.getStr().equals(e))
                        .count())>0)
                        .collect(Collectors.toList());`
will it give me list1 matched with list2 right? 

What is the difference between fastcgi and fpm?

Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable

whereas

PHP FastCGI Process Manager (PHP-FPM) is an alternative FastCGI daemon for PHP that allows a website to handle strenuous loads. PHP-FPM maintains pools (workers that can respond to PHP requests) to accomplish this. PHP-FPM is faster than traditional CGI-based methods, such as SUPHP, for multi-user PHP environments

However, there are pros and cons to both and one should choose as per their specific use case.

I found info on this link for fastcgi vs fpm quite helpful in choosing which handler to use in my scenario.

Error handling in getJSON calls

I was faced with this same issue, but rather than creating callbacks for a failed request, I simply returned an error with the json data object.

If possible, this seems like the easiest solution. Here's a sample of the Python code I used. (Using Flask, Flask's jsonify f and SQLAlchemy)

try:
    snip = Snip.query.filter_by(user_id=current_user.get_id(), id=snip_id).first()
    db.session.delete(snip)
    db.session.commit()
    return jsonify(success=True)
except Exception, e:
    logging.debug(e)
    return jsonify(error="Sorry, we couldn't delete that clip.")

Then you can check on Javascript like this;

$.getJSON('/ajax/deleteSnip/' + data_id,
    function(data){
    console.log(data);
    if (data.success === true) {
       console.log("successfully deleted snip");
       $('.snippet[data-id="' + data_id + '"]').slideUp();
    }
    else {
       //only shows if the data object was returned
    }
});

Find number of decimal places in decimal value regardless of culture

I'd probably use the solution in @fixagon's answer.

However, while the Decimal struct doesn't have a method to get the number of decimals, you could call Decimal.GetBits to extract the binary representation, then use the integer value and scale to compute the number of decimals.

This would probably be faster than formatting as a string, though you'd have to be processing an awful lot of decimals to notice the difference.

I'll leave the implementation as an exercise.

Emulate Samsung Galaxy Tab

If you are developing on Netbeans, you will not get the Third-Party add-ons. You can download the Skins directly from Samsung here: http://developer.samsung.com/android/tools-sdks

After download, unzip to ...\Android\android-sdk\add-ons[name of device]

Restart the Android SDK Manager, and the new device should be there under Extras.

It would be better to add the download site directly to the SDK...if anyone knows it, please post it.

Scott

How to conclude your merge of a file?

If you encounter this error in SourceTree, go to Actions>Resolve Conflicts>Restart Merge.

SourceTree version used is 1.6.14.0

Reading the selected value from asp:RadioButtonList using jQuery

Try the below code:

<script type="text/javascript">
    $(document).ready(function () {

        $(".ratingButtons").buttonset();

    });
 </script>


<asp:RadioButtonList ID="RadioButtonList1" RepeatDirection="Horizontal" runat="server"
            AutoPostBack="True" DataSourceID="SqlDataSourceSizes"     DataTextField="ProdSize"
            CssClass="ratingButtons" DataValueField="_ProdSizeID" Font-Size="X-Small" 
            ForeColor="#666666">
</asp:RadioButtonList>

Run a controller function whenever a view is opened/shown

For example to @Michael Trouw,

inside your controller put this code. this will run everytime when this state is entered or active, you do not need to worry about disabling cache and it's a better approach.

.controller('exampleCtrl',function($scope){
$scope.$on('$ionicView.enter', function(){
        // Any thing you can think of
        alert("This function just ran away");   
    });
})

You can have more examples of flexibility like $ionicView.beforeEnter -> which runs before a view is shown. And there are some more to it.

Removing all unused references from a project in Visual Studio projects

The Resharper extension will do this for you.

This extension supports Visual Studio 2005 through 2017.

While the compiler won't include unused assemblies, extraneous using statements and references slows down Visual Studio and Intellisense, since there's more code the tools have to consider.

Setting focus on an HTML input box on page load

You could also use:

<body onload="focusOnInput()">
    <form name="passwordForm" action="verify.php" method="post">
        <input name="passwordInput" type="password" />
    </form>
</body>

And then in your JavaScript:

function focusOnInput() {
    document.forms["passwordForm"]["passwordInput"].focus();
}

How do I set the default page of my application in IIS7?

If you want to do something like,User enter url "www.xxxxxx.com/views/root/" & default page is displayed then I guess you have to set the default/home/welcome page attribute in IIS. But if user just enters "www.xxxxxx.com" and you still want to forward to your url, then you have write a line of code in the default page to forward to your desired url. This default page should be in root directory of your application, so www.xxxxx.com will load www.xxxx.com/index.html which will redirect the user to your desired url

How to auto-indent code in the Atom editor?

This works for me:

'atom-workspace atom-text-editor':
    'ctrl-alt-a': 'editor:auto-indent'

You have to select all with ctrl-a first.

Decoding JSON String in Java

This is the JSON String we want to decode :

{ 
   "stats": { 
       "sdr": "aa:bb:cc:dd:ee:ff", 
       "rcv": "aa:bb:cc:dd:ee:ff", 
       "time": "UTC in millis", 
       "type": 1, 
       "subt": 1, 
       "argv": [
          {"1": 2}, 
          {"2": 3}
       ]}
}

I store this string under the variable name "sJSON" Now, this is how to decode it :)

// Creating a JSONObject from a String 
JSONObject nodeRoot  = new JSONObject(sJSON); 

// Creating a sub-JSONObject from another JSONObject
JSONObject nodeStats = nodeRoot.getJSONObject("stats");

// Getting the value of a attribute in a JSONObject
String sSDR = nodeStats.getString("sdr");

The equivalent of a GOTO in python

answer = None
while True:
    answer = raw_input("Do you like pie?")
    if answer in ("yes", "no"): break
    print "That is not a yes or a no"

Would give you what you want with no goto statement.

Convert UTC dates to local time in PHP

Here is a straight way to convert the UTC time of the questioner to local time. This is for a stored time in a database etc., i.e. any time. You just have to find the time difference between UTC time and the local time you are interested in and then ajust the stored UTC time adding to it the difference.

$df = "G:i:s";  // Use a simple time format to find the difference
$ts1 = strtotime(date($df));   // Timestamp of current local time
$ts2 = strtotime(gmdate($df)); // Timestamp of current UTC time
$ts3 = $ts1-$ts2;              // Their difference

You can then add this difference to the stored UTC time. (In my place, Athens, the difference is exactly 5:00:00)

Example:

$time = time() // Or any other timestamp
$time += $ts3  // Add the difference
$dateInLocal = date("Y-m-d H:i:s", $time);

Set a div width, align div center and text align left

Use auto margins.

div {
   margin-left: auto;
   margin-right: auto;
   width: NNNpx;

   /* NOTE: Only works for non-floated block elements */
   display: block;
   float: none;
}

Further reading at SimpleBits CSS Centering 101

dispatch_after - GCD in Swift?

Simplest solution in Swift 3.0 & Swift 4.0 & Swift 5.0

func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { 
        completion()
    }
}

Usage

delayWithSeconds(1) {
   //Do something
}

C# Telnet Library

Here is my code that is finally working

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Threading;

class TelnetTest
{

    static void Main(string[] args)
    {
        TelnetTest tt = new TelnetTest();

        tt.tcpClient = new TcpClient("myserver", 23);
        tt.ns = tt.tcpClient.GetStream();

        tt.connectHost("admin", "admin");
        tt.sendCommand();

        tt.tcpClient.Close();
    }

public void connectHost(string user, string passwd) {
    bool i = true;
    while (i)
    {
        Console.WriteLine("Connecting.....");
        Byte[] output = new Byte[1024];
        String responseoutput = String.Empty;
        Byte[] cmd = System.Text.Encoding.ASCII.GetBytes("\n");
        ns.Write(cmd, 0, cmd.Length);

        Thread.Sleep(1000);
        Int32 bytes = ns.Read(output, 0, output.Length);
        responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
        Console.WriteLine("Responseoutput: " + responseoutput);
        Regex objToMatch = new Regex("login:");
        if (objToMatch.IsMatch(responseoutput)) {
           cmd = System.Text.Encoding.ASCII.GetBytes(user + "\r");
           ns.Write(cmd, 0, cmd.Length);
        }

        Thread.Sleep(1000);
        bytes = ns.Read(output, 0, output.Length);
        responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
        Console.Write(responseoutput);
        objToMatch = new Regex("Password");
        if (objToMatch.IsMatch(responseoutput))
        {
            cmd = System.Text.Encoding.ASCII.GetBytes(passwd + "\r");
            ns.Write(cmd, 0, cmd.Length);
        }

        Thread.Sleep(1000);
        bytes = ns.Read(output, 0, output.Length);
        responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
        Console.Write("Responseoutput: " + responseoutput);

        objToMatch = new Regex("#");
        if (objToMatch.IsMatch(responseoutput))
        {
            i = false;
        }

    }

    Console.WriteLine("Just works");
}
}

How do I change Android Studio editor's background color?

How do I change Android Studio editor's background color?

Changing Editor's Background

Open Preference > Editor (In IDE Settings Section) > Colors & Fonts > Darcula or Any item available there

IDE will display a dialog like this, Press 'No'

Darcula color scheme has been set for editors. Would you like to set Darcula as default Look and Feel?

Changing IDE's Theme

Open Preference > Appearance (In IDE Settings Section) > Theme > Darcula or Any item available there

Press OK. Android Studio will ask you to restart the IDE.

What to do on TransactionTooLargeException

When I am dealing with the WebView in my app it happens. I think it's related to addView and UI resources. In my app I add some code in WebViewActivity like this below then it runs ok:

@Override
protected void onDestroy() {
    if (mWebView != null) {
        ((ViewGroup) mWebView.getParent()).removeView(mWebView);  
        mWebView.removeAllViews();  
        mWebView.destroy();
    }
    super.onDestroy();
}

Join a list of items with different types as string in Python

Calling str(...) is the Pythonic way to convert something to a string.

You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert them one by one in a for-loop and join them with ,:

print(','.join(str(x) for x in list_of_ints))

Jquery sortable 'change' event element position

This works for me:

start: function(event, ui) {
        var start_pos = ui.item.index();
        ui.item.data('start_pos', start_pos);
    },
update: function (event, ui) {
        var start_pos = ui.item.data('start_pos');
        var end_pos = ui.item.index();
        //$('#sortable li').removeClass('highlights');
    }

Finding duplicate integers in an array and display how many times they occurred

int copt = 1;
int element = 0;
int[] array = { 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5 };
for (int i = 0; i < array.Length; i++)
{
   for (int j = i + 1; j < array.Length - 1; j++)
   {
       if (array[i] == array[j])
       {
          element = array[i];
          copt++;
          break;
       }
   }
}

Console.WriteLine("the repeat element is {0} and it's appears {1} times ", element, copt);
Console.ReadKey();

// the output is the element is 3 and appears 9 times

Create table (structure) from existing table

If you want to create a table with the only structure to be copied from the original table then you can use the following command to do that.

create table <tablename> as select * from <sourcetablename> where 1>2;

By this false condition you can leave the records and copy the structure.

Find duplicate records in MySQL

Isn't this easier :

SELECT *
FROM tc_tariff_groups
GROUP BY group_id
HAVING COUNT(group_id) >1

?

How to change UIButton image in Swift

I prefer the method of initializing my variables at the top first:

let playButton:UIButton!
var image:UIImage!

and then setting them in viewDidLoad

override func viewDidLoad {
  ...
  playButton = UIButton(type: .Custom)
  imagePlay = UIImage(named:"play.png")
  playButton.setImage(imagePlay, forState: .Normal)
}

Error ITMS-90717: "Invalid App Store Icon"

The below solution worked for me

  1. Click & open the App Store icon (1024*1024) in the preview app.
  2. Export it by unticking the Alpha channel.
  3. Replace the current App Store icon with the newly exported icon image.
  4. Validate and upload.

Note: This will not work on Mac OS High Sierra, please try a lower version to export without alpha or use any one of the image editing applications or try out the below alternatives.

Alternative 1: (Using Sierra or High Sierra and Ionic)

  1. Copy and Paste the App Store icon to the desktop.
  2. Open the image. Click File Menu->Duplicate.
  3. Save it by unticking the Alpha channel.
  4. Replace the current App Store icon with this one.
  5. Validate and upload.

Alternative 2: If duplicate does not work, try doing opening it in preview and then doing file export. I was able to unselect the alpha channel there. – by Alejandro Corredor.

Alternative 3 : Using High Sierra and Ionic, found the problem image in the following folder: [app name]/platforms/ios/[app name]/Images.xcassets/Appicon.appiconset/icon-1024.png. We have to copy it to the desktop and Save As while unchecking Alpha, then rename it to icon-1024.png, then delete the original and copy the new file back to the original folder. Export did not work though no error was displayed and all permissions were set/777. Hope this helps save someone the day I just lost. – by Ralph Hinkley

enter image description here

Remove characters after specific character in string, then remove substring?

I second Hightechrider: there is a specialized Url class already built for you.

I must also point out, however, that the PHP's replaceAll uses regular expressions for search pattern, which you can do in .NET as well - look at the RegEx class.

Android RecyclerView addition & removal of items

make interface into custom adapter class and handling click event on recycler view..

 onItemClickListner onItemClickListner;

public void setOnItemClickListner(CommentsAdapter.onItemClickListner onItemClickListner) {
    this.onItemClickListner = onItemClickListner;
}

public interface onItemClickListner {
    void onClick(Contact contact);//pass your object types.
}
    @Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
    // below code handle click event on recycler view item.
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onItemClickListner.onClick(mContectList.get(position));
        }
    });
}

after define adapter and bind into recycler view called below code..

        adapter.setOnItemClickListner(new CommentsAdapter.onItemClickListner() {
        @Override
        public void onClick(Contact contact) {
            contectList.remove(contectList.get(contectList.indexOf(contact)));
            adapter.notifyDataSetChanged();
        }
    });
}

JSTL if tag for equal strings

<c:if test="${ansokanInfo.pSystem eq 'NAT'}">

ASP.NET DateTime Picker

@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control", @type = "date" } })

this works well

"%%" and "%/%" for the remainder and the quotient

I think it is because % has often be associated with the modulus operator in many programming languages.

It is the case, e.g., in C, C++, C# and Java, and many other languages which derive their syntax from C (C itself took it from B).

jQuery datepicker to prevent past date

$("#datePicker").datePicker({startDate: new Date() });. This works for me

How to get the nvidia driver version from the command line?

On any linux system with the NVIDIA driver installed and loaded into the kernel, you can execute:

cat /proc/driver/nvidia/version

to get the version of the currently loaded NVIDIA kernel module, for example:

$ cat /proc/driver/nvidia/version 
NVRM version: NVIDIA UNIX x86_64 Kernel Module  304.54  Sat Sep 29 00:05:49 PDT 2012
GCC version:  gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) 

How to exit a 'git status' list in a terminal?

exit did it for me. My results after pressing return;

my-mac:Car Game mymac$ exit
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
    ...completed.
[Process completed]

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

You'd have to test it but if you embedded an iframe within your page then used CSS to absolutely position the 1st row & column at 0,0 in the iframe page would that solve your problem?

Matplotlib (pyplot) savefig outputs blank image

First, what happens when T0 is not None? I would test that, then I would adjust the values I pass to plt.subplot(); maybe try values 131, 132, and 133, or values that depend whether or not T0 exists.

Second, after plt.show() is called, a new figure is created. To deal with this, you can

  1. Call plt.savefig('tessstttyyy.png', dpi=100) before you call plt.show()

  2. Save the figure before you show() by calling plt.gcf() for "get current figure", then you can call savefig() on this Figure object at any time.

For example:

fig1 = plt.gcf()
plt.show()
plt.draw()
fig1.savefig('tessstttyyy.png', dpi=100)

In your code, 'tesssttyyy.png' is blank because it is saving the new figure, to which nothing has been plotted.

Regular expression to match any character being repeated more than 10 times

On some apps you need to remove the slashes to make it work.

/(.)\1{9,}/

or this:

(.)\1{9,}

Trying to Validate URL Using JavaScript

Import in an npm package like

https://www.npmjs.com/package/valid-url

and use it to validate your url.

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

How can I count the occurrences of a list item?

To count the number of diverse elements having a common type:

li = ['A0','c5','A8','A2','A5','c2','A3','A9']

print sum(1 for el in li if el[0]=='A' and el[1] in '01234')

gives

3 , not 6

How could I create a list in c++?

You should really use the standard List class. Unless, of course, this is a homework question, or you want to know how lists are implemented by STL.

You'll find plenty of simple tutorials via google, like this one. If you want to know how linked lists work "under the hood", try searching for C list examples/tutorials rather than C++.

Is there an onSelect event or equivalent for HTML <select>?

Try this:

<select id="nameSelect" onfocus="javascript:document.getElementById('nameSelect').selectedIndex=-1;" onchange="doSomething(this);">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
</select>

Formatting a number with leading zeros in PHP

sprintf is what you need.

EDIT (somehow requested by the downvotes), from the page linked above, here's a sample "zero-padded integers":

<?php
    $isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

JQuery, setTimeout not working

setInterval(function() {
    $('#board').append('.');
}, 1000);

You can use clearInterval if you wanted to stop it at one point.

Maven project.build.directory

It points to your top level output directory (which by default is target):

https://web.archive.org/web/20150527103929/http://docs.codehaus.org/display/MAVENUSER/MavenPropertiesGuide

EDIT: As has been pointed out, Codehaus is now sadly defunct. You can find details about these properties from Sonatype here:

http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-properties.html#resource-filtering-sect-project-properties

If you are ever trying to reference output directories in Maven, you should never use a literal value like target/classes. Instead you should use property references to refer to these directories.

    project.build.sourceDirectory
    project.build.scriptSourceDirectory
    project.build.testSourceDirectory
    project.build.outputDirectory
    project.build.testOutputDirectory
    project.build.directory

sourceDirectory, scriptSourceDirectory, and testSourceDirectory provide access to the source directories for the project. outputDirectory and testOutputDirectory provide access to the directories where Maven is going to put bytecode or other build output. directory refers to the directory which contains all of these output directories.

Android offline documentation and sample codes

First of All you should download the Android SDK. Download here:
http://developer.android.com/sdk/index.html

Then, as stated in the SDK README:

The Android SDK archive now only contains the tools. It no longer comes populated with a specific Android platform or Google add-on. Instead you use the SDK Manager to install or update SDK components such as platforms, tools, add-ons, and documentation.

Does overflow:hidden applied to <body> work on iPhone Safari?

For me this:

height: 100%; 
overflow: hidden; 
width: 100%; 
position: fixed;

Wasn't enough, i't didn't work on iOS on Safari. I also had to add:

top: 0;
left: 0;
right: 0;
bottom: 0;

To make it work good. Works fine now :)

Python Database connection Close

Connections have a close method as specified in PEP-249 (Python Database API Specification v2.0):

import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 

csr = conn.cursor()  
csr.close()
conn.close()     #<--- Close the connection

Since the pyodbc connection and cursor are both context managers, nowadays it would be more convenient (and preferable) to write this as:

import pyodbc
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 
with conn:
    crs = conn.cursor()
    do_stuff
    # conn.commit() will automatically be called when Python leaves the outer `with` statement
    # Neither crs.close() nor conn.close() will be called upon leaving the `with` statement!! 

See https://github.com/mkleehammer/pyodbc/issues/43 for an explanation for why conn.close() is not called.

Note that unlike the original code, this causes conn.commit() to be called. Use the outer with statement to control when you want commit to be called.


Also note that regardless of whether or not you use the with statements, per the docs,

Connections are automatically closed when they are deleted (typically when they go out of scope) so you should not normally need to call [conn.close()], but you can explicitly close the connection if you wish.

and similarly for cursors (my emphasis):

Cursors are closed automatically when they are deleted (typically when they go out of scope), so calling [csr.close()] is not usually necessary.

How to add Drop-Down list (<select>) programmatically?

I have quickly made a function that can achieve this, it may not be the best way to do this but it simply works and should be cross browser, please also know that i am NOT a expert in JavaScript so any tips are great :)

Pure Javascript Create Element Solution

function createElement(){
    var element  = document.createElement(arguments[0]),
        text     = arguments[1],
        attr     = arguments[2],
        append   = arguments[3],
        appendTo = arguments[4];

    for(var key = 0; key < Object.keys(attr).length ; key++){
        var name = Object.keys(attr)[key],
             value = attr[name],
             tempAttr = document.createAttribute(name);
             tempAttr.value = value;
        element.setAttributeNode(tempAttr)
    }
    
    if(append){
        for(var _key = 0; _key < append.length; _key++) {
            element.appendChild(append[_key]);
        }
    }

    if(text) element.appendChild(document.createTextNode(text));

    if(appendTo){
        var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
        target.appendChild(element)
    }       

    return element;
}

lets see how we make this

<select name="drop1" id="Select1">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

here's how it works

    var options = [
        createElement('option', 'Volvo', {value: 'volvo'}),
        createElement('option', 'Saab', {value: 'saab'}),
        createElement('option', 'Mercedes', {value: 'mercedes'}),
        createElement('option', 'Audi', {value: 'audi'})
    ];


    createElement('select', null, // 'select' = name of element to create, null = no text to insert
        {id: 'Select1', name: 'drop1'}, // Attributes to attach
        [options[0], options[1], options[2], options[3]], // append all 4 elements
        'body' // append final element to body - this also takes a element by id without the #
    );

this is the params

createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');

This function would suit if you have to append many element, if there is any way to improve this answer please let me know.

edit:

Here is a working demo

JSFiddle Demo

This can be highly customized to suit your project!

HTTP authentication logout via PHP

There's a lot of great - complex - answers here. In my particular case i found a clean and simple fix for the logout. I have yet to test in Edge. On my page that I have logged in to, I have placed a logout link similar to this:

<a href="https://MyDomainHere.net/logout.html">logout</a>

And in the head of that logout.html page (which is also protected by the .htaccess) I have a page refresh similar to this:

<meta http-equiv="Refresh" content="0; url=https://logout:[email protected]/" />

Where you would leave the words "logout" in place to clear the username and password cached for the site.

I will admit that if multiple pages needed to be able to be directly logged in to from the beginning, each of those points of entry would need their own corresponding logout.html page. Otherwise you could centralize the logout by introducing an additional gatekeeper step into the process before the actual login prompt, requiring entry of a phrase to reach a destination of login.

ExecuteNonQuery doesn't return results

Could you post the exact query? The ExecuteNonQuery method returns the @@ROWCOUNT Sql Server variable what ever it is after the last query has executed is what the ExecuteNonQuery method returns.

How do I disable and re-enable a button in with javascript?

true and false are not meant to be strings in this context.

You want the literal true and false Boolean values.

startButton.disabled = true;

startButton.disabled = false;

The reason it sort of works (disables the element) is because a non empty string is truthy. So assigning 'false' to the disabled property has the same effect of setting it to true.

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

If you are connecting to an old SQL Server:

Switch from System.Data.SqlClient.SqlConnection to System.Data.OleDb.OleDbConnection

Use an OleDb connection string:

<connectionStrings>
<add name="Northwind" connectionString="Provider=SQLOLEDB.1; Data Source=MyServer; Initial Catalog=Northwind;  Persist Security Info=True; User ID=abc; Password=xyz;" providerName="System.Data.OleDb" />
</connectionStrings>

How to view table contents in Mysql Workbench GUI?

Select Database , select table and click icon as shown in picture.enter image description here

Checking if a list is empty with LINQ

If I check with Count() Linq executes a "SELECT COUNT(*).." in the database, but I need to check if the results contains data, I resolved to introducing FirstOrDefault() instead of Count();

Before

var cfop = from tabelaCFOPs in ERPDAOManager.GetTable<TabelaCFOPs>()

if (cfop.Count() > 0)
{
    var itemCfop = cfop.First();
    //....
}

After

var cfop = from tabelaCFOPs in ERPDAOManager.GetTable<TabelaCFOPs>()

var itemCfop = cfop.FirstOrDefault();

if (itemCfop != null)
{
    //....
}

How to search for an element in an stl list?

No, not directly in the std::list template itself. You can however use std::find algorithm like that:

std::list<int> my_list;
//...
int some_value = 12;
std::list<int>::iterator iter = std::find (my_list.begin(), my_list.end(), some_value);
// now variable iter either represents valid iterator pointing to the found element,
// or it will be equal to my_list.end()

AppendChild() is not a function javascript

Your div variable is a string, not a DOM element object:

var div = '<div>top div</div>';

Strings don't have an appendChild method. Instead of creating a raw HTML string, create the div as a DOM element and append a text node, then append the input element:

var div = document.createElement('div');
div.appendChild(document.createTextNode('top div'));

div.appendChild(element);

Calculate compass bearing / heading to location in Android

I know this is a little old but for the sake of folks like myself from google who didn't find a complete answer here. Here are some extracts from my app which put the arrows inside a custom listview....

Location loc;   //Will hold lastknown location
Location wptLoc = new Location("");    // Waypoint location 
float dist = -1;
float bearing = 0;
float heading = 0;
float arrow_rotation = 0;

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

if(loc == null) {   //No recent GPS fix
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(true);
    criteria.setCostAllowed(true);
    criteria.setSpeedRequired(false);
    loc = lm.getLastKnownLocation(lm.getBestProvider(criteria, true));
}

if(loc != null) {
    wptLoc.setLongitude(cursor.getFloat(2));    //Cursor is from SimpleCursorAdapter
    wptLoc.setLatitude(cursor.getFloat(3));
    dist = loc.distanceTo(wptLoc);
    bearing = loc.bearingTo(wptLoc);    // -180 to 180
    heading = loc.getBearing();         // 0 to 360
    // *** Code to calculate where the arrow should point ***
    arrow_rotation = (360+((bearing + 360) % 360)-heading) % 360;
}

I willing to bet it could be simplified but it works! LastKnownLocation was used since this code was from new SimpleCursorAdapter.ViewBinder()

onLocationChanged contains a call to notifyDataSetChanged();

code also from new SimpleCursorAdapter.ViewBinder() to set image rotation and listrow colours (only applied in a single columnIndex mind you)...

LinearLayout ll = ((LinearLayout)view.getParent());
ll.setBackgroundColor(bc); 
int childcount = ll.getChildCount();
for (int i=0; i < childcount; i++){
    View v = ll.getChildAt(i);
    if(v instanceof TextView) ((TextView)v).setTextColor(fc);
    if(v instanceof ImageView) {
        ImageView img = (ImageView)v;
        img.setImageResource(R.drawable.ic_arrow);
        Matrix matrix = new Matrix();
        img.setScaleType(ScaleType.MATRIX);
        matrix.postRotate(arrow_rotation, img.getWidth()/2, img.getHeight()/2);
        img.setImageMatrix(matrix); 
}

In case you're wondering I did away with the magnetic sensor dramas, wasn't worth the hassle in my case. I hope somebody finds this as useful as I usually do when google brings me to stackoverflow!

How to get the last characters in a String in Java, regardless of String size

org.apache.commons.lang3.StringUtils.substring(s, -7) 

gives you the answer. It returns the input if it is shorter than 7, and null if s == null. It never throws an exception.

See https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#substring-java.lang.String-int-int-

What is the difference between Scrum and Agile Development?

Waterfall methodology is a sequential design process. This means that as each of the eight stages (conception, initiation, analysis, design, construction, testing, implementation, and maintenance) are completed, the developers move on to the next step.

As this process is sequential, once a step has been completed, developers can’t go back to a previous step – not without scratching the whole project and starting from the beginning. There’s no room for change or error, so a project outcome and an extensive plan must be set in the beginning and then followed careful

ACP Agile Certification came about as a “solution” to the disadvantages of the waterfall methodology. Instead of a sequential design process, the Agile methodology follows an incremental approach. Developers start off with a simplistic project design, and then begin to work on small modules. The work on these modules is done in weekly or monthly sprints, and at the end of each sprint, project priorities are evaluated and tests are run. These sprints allow for bugs to be discovered, and customer feedback to be incorporated into the design before the next sprint is run.

The process, with its lack of initial design and steps, is often criticized for its collaborative nature that focuses on principles rather than process.

Is Python strongly typed?

class testme(object):
    ''' A test object '''
    def __init__(self):
        self.y = 0

def f(aTestMe1, aTestMe2):
    return aTestMe1.y + aTestMe2.y




c = testme            #get a variable to the class
c.x = 10              #add an attribute x inital value 10
c.y = 4               #change the default attribute value of y to 4

t = testme()          # declare t to be an instance object of testme
r = testme()          # declare r to be an instance object of testme

t.y = 6               # set t.y to a number
r.y = 7               # set r.y to a number

print(f(r,t))         # call function designed to operate on testme objects

r.y = "I am r.y"      # redefine r.y to be a string

print(f(r,t))         #POW!!!!  not good....

The above would create a nightmare of unmaintainable code in a large system over a long period time. Call it what you want, but the ability to "dynamically" change a variables type is just a bad idea...

How to get an object's methods?

the best way is:

let methods = Object.getOwnPropertyNames(yourobject);
console.log(methods)

use 'let' only in es6, use 'var' instead

Backporting Python 3 open(encoding="utf-8") to Python 2

I think

from io import open

should do.

How can I filter a date of a DateTimeField in Django?

There's a fantastic blogpost that covers this here: Comparing Dates and Datetimes in the Django ORM

The best solution posted for Django>1.7,<1.9 is to register a transform:

from django.db import models

class MySQLDatetimeDate(models.Transform):
    """
    This implements a custom SQL lookup when using `__date` with datetimes.
    To enable filtering on datetimes that fall on a given date, import
    this transform and register it with the DateTimeField.
    """
    lookup_name = 'date'

    def as_sql(self, compiler, connection):
        lhs, params = compiler.compile(self.lhs)
        return 'DATE({})'.format(lhs), params

    @property
    def output_field(self):
        return models.DateField()

Then you can use it in your filters like this:

Foo.objects.filter(created_on__date=date)

EDIT

This solution is definitely back end dependent. From the article:

Of course, this implementation relies on your particular flavor of SQL having a DATE() function. MySQL does. So does SQLite. On the other hand, I haven’t worked with PostgreSQL personally, but some googling leads me to believe that it does not have a DATE() function. So an implementation this simple seems like it will necessarily be somewhat backend-dependent.

What are WSDL, SOAP and REST?

Every time someone mentions SOAP/WSDL, I think of objects and classes defined in xml...

"You use SOAP just the same way that you would any PHP class. However, in this case the class does not exist in the local applications file system, but at a remote site accessed over http." ... "If we think of using a SOAP service as just another PHP class then the WSDL document is a list of all the available class methods and properties. "

http://www.doublehops.com/2009/07/07/quick-tutorial-on-getting-started-with-soap-in-php/comment-page-1/

..and whenever someone talks about REST I think of HTTP's commands (request methods) like POST, GET and DELETE

Windows 7 SDK installation failure

I could never get the Windows 7 SDK to install either, and it suggested I remove the latest SDK and Visual Studio 2012 Express. That didn't work.

There was also something about .NET 3.5. I installed the Server 2008 SDK with .NET 3.5, uninstalled Visual Studio 2010 redistributables and made sure redistributables were unchecked in the installation options.

Also, you need the .NET 4 framework already installed, which you can download from Microsoft's site. Then it worked.

How can I "reset" an Arduino board?

I had the very same problem today. Here is a simple solution we found to solve this issue (thanks to Anghiara):

Instead of loading your new code to the Arduino using the "upload button" (the circle with the green arrow) in your screen, use your mouse to click "Sketch" and then "Upload".

Please remember to add a delay() line to your code when working with Serial.println() and loops. I learned my lesson the hard way.

Insert Update trigger how to determine if insert or update

After a lot of searching I could not find an exact example of a single SQL Server trigger that handles all (3) three conditions of the trigger actions INSERT, UPDATE, and DELETE. I finally found a line of text that talked about the fact that when a DELETE or UPDATE occurs, the common DELETED table will contain a record for these two actions. Based upon that information, I then created a small Action routine which determines why the trigger has been activated. This type of interface is sometimes needed when there is both a common configuration and a specific action to occur on an INSERT vs. UPDATE trigger. In these cases, to create a separate trigger for the UPDATE and the INSERT would become maintenance problem. (i.e. were both triggers updated properly for the necessary common data algorithm fix?)

To that end, I would like to give the following multi-trigger event code snippet for handling INSERT, UPDATE, DELETE in one trigger for an Microsoft SQL Server.

CREATE TRIGGER [dbo].[INSUPDDEL_MyDataTable]
ON [dbo].[MyDataTable] FOR INSERT, UPDATE, DELETE
AS 

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with caller queries SELECT statements.
-- If an update/insert/delete occurs on the main table, the number of records affected
-- should only be based on that table and not what records the triggers may/may not
-- select.
SET NOCOUNT ON;

--
-- Variables Needed for this Trigger
-- 
DECLARE @PACKLIST_ID varchar(15)
DECLARE @LINE_NO smallint
DECLARE @SHIPPED_QTY decimal(14,4)
DECLARE @CUST_ORDER_ID varchar(15)
--
-- Determine if this is an INSERT,UPDATE, or DELETE Action
-- 
DECLARE @Action as char(1)
DECLARE @Count as int
SET @Action = 'I' -- Set Action to 'I'nsert by default.
SELECT @Count = COUNT(*) FROM DELETED
if @Count > 0
    BEGIN
        SET @Action = 'D' -- Set Action to 'D'eleted.
        SELECT @Count = COUNT(*) FROM INSERTED
        IF @Count > 0
            SET @Action = 'U' -- Set Action to 'U'pdated.
    END

if @Action = 'D'
    -- This is a DELETE Record Action
    --
    BEGIN
        SELECT @PACKLIST_ID =[PACKLIST_ID]
                    ,@LINE_NO = [LINE_NO]
        FROM DELETED

        DELETE [dbo].[MyDataTable]
        WHERE [PACKLIST_ID]=@PACKLIST_ID AND [LINE_NO]=@LINE_NO
    END
 Else
    BEGIN
            --
            -- Table INSERTED is common to both the INSERT, UPDATE trigger
            --
            SELECT @PACKLIST_ID =[PACKLIST_ID]
                ,@LINE_NO = [LINE_NO]
                ,@SHIPPED_QTY =[SHIPPED_QTY]
                ,@CUST_ORDER_ID = [CUST_ORDER_ID]
            FROM INSERTED 

         if @Action = 'I'
            -- This is an Insert Record Action
            --
            BEGIN
                INSERT INTO [MyChildTable]
                    (([PACKLIST_ID]
                    ,[LINE_NO]
                    ,[STATUS]
                VALUES
                    (@PACKLIST_ID
                    ,@LINE_NO
                    ,'New Record'
                    )
            END
        else
            -- This is an Update Record Action
            --
            BEGIN
                UPDATE [MyChildTable]
                    SET [PACKLIST_ID] = @PACKLIST_ID
                          ,[LINE_NO] = @LINE_NO
                          ,[STATUS]='Update Record'
                WHERE [PACKLIST_ID]=@PACKLIST_ID AND [LINE_NO]=@LINE_NO
            END
    END   

Develop Android app using C#

You could use Mono for Android:

http://xamarin.com/monoforandroid

An alternative is dot42:

http://www.dot42.com/

dot42 provides a free community licence as well as a professional licence for $399.

How to adjust an UIButton's imageSize?

Swift 3

I set myButton width and height to 40 and my padding from EdgeInsetsMake is 15 all sides. I suggest to add a background color to your button to see the actual padding.

myButton.backgroundColor = UIColor.gray // sample color to check padding
myButton.imageView?.contentMode = .scaleAspectFit
myButton.imageEdgeInsets = UIEdgeInsetsMake(15, 15, 15, 15)

Not class selector in jQuery

You need the :not() selector:

$('div[class^="first-"]:not(.first-bar)')

or, alternatively, the .not() method:

$('div[class^="first-"]').not('.first-bar');

Find all zero-byte files in directory and subdirectories

As addition to the answers above:

If you would like to delete those files

find $dir -size 0 -type f -delete

Multiple file extensions in OpenFileDialog

Based on First answer here is the complete image selection options:

Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
           |PNG|*.PNG;*.png
           |JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
           |Bitmap(.BMP,.bmp)|*.BMP;*.bmp                                    
           |GIF|*.GIF;*.gif
           |TIF|*.tif;*.tiff
           |ICO|*.ico;*.ICO";

How to have Android Service communicate with Activity

Besides LocalBroadcastManager , Event Bus and Messenger already answered in this question,we can use Pending Intent to communicate from service.

As mentioned here in my blog post

Communication between service and Activity can be done using PendingIntent.For that we can use createPendingResult().createPendingResult() creates a new PendingIntent object which you can hand to service to use and to send result data back to your activity inside onActivityResult(int, int, Intent) callback.Since a PendingIntent is Parcelable , and can therefore be put into an Intent extra,your activity can pass this PendingIntent to the service.The service, in turn, can call send() method on the PendingIntent to notify the activity via onActivityResult of an event.

Activity

public class PendingIntentActivity extends AppCompatActivity
{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

PendingIntent pendingResult = createPendingResult(
100, new Intent(), 0);
Intent intent = new Intent(getApplicationContext(), PendingIntentService.class);
intent.putExtra("pendingIntent", pendingResult);
startService(intent);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode==200) {
Toast.makeText(this,data.getStringExtra("name"),Toast.LENGTH_LONG).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
}

Service

public class PendingIntentService extends Service {

    private static final String[] items= { "lorem", "ipsum", "dolor",
            "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi",
            "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam",
            "vel", "erat", "placerat", "ante", "porttitor", "sodales",
            "pellentesque", "augue", "purus" };
    private PendingIntent data;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        data = intent.getParcelableExtra("pendingIntent");

        new LoadWordsThread().start();
        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    class LoadWordsThread extends Thread {
        @Override
        public void run() {
            for (String item : items) {
                if (!isInterrupted()) {

                    Intent result = new Intent();
                    result.putExtra("name", item);
                    try {
                        data.send(PendingIntentService.this,200,result);
                    } catch (PendingIntent.CanceledException e) {

                        e.printStackTrace();
                    }
                    SystemClock.sleep(400);

                }
            }
        }
    }
}

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

enter image description here

I selected Automatic option to select the ViewController.swift file. And then I can able to take outlets.

SQL Server Regular expressions in T-SQL

How about the PATINDEX function?

The pattern matching in TSQL is not a complete regex library, but it gives you the basics.

(From Books Online)

Wildcard  Meaning  
% Any string of zero or more characters.

_ Any single character.

[ ] Any single character within the specified range 
    (for example, [a-f]) or set (for example, [abcdef]).

[^] Any single character not within the specified range 
    (for example, [^a - f]) or set (for example, [^abcdef]).

How do I initialize a TypeScript Object with a JSON-Object?

Option #5: Using Typescript constructors and jQuery.extend

This seems to be the most maintainable method: add a constructor that takes as parameter the json structure, and extend the json object. That way you can parse a json structure into the whole application model.

There is no need to create interfaces, or listing properties in constructor.

export class Company
{
    Employees : Employee[];

    constructor( jsonData: any )
    {
        jQuery.extend( this, jsonData);

        // apply the same principle to linked objects:
        if ( jsonData.Employees )
            this.Employees = jQuery.map( jsonData.Employees , (emp) => {
                return new Employee ( emp );  });
    }

    calculateSalaries() : void { .... }
}

export class Employee
{
    name: string;
    salary: number;
    city: string;

    constructor( jsonData: any )
    {
        jQuery.extend( this, jsonData);

        // case where your object's property does not match the json's:
        this.city = jsonData.town;
    }
}

In your ajax callback where you receive a company to calculate salaries:

onReceiveCompany( jsonCompany : any ) 
{
   let newCompany = new Company( jsonCompany );

   // call the methods on your newCompany object ...
   newCompany.calculateSalaries()
}

multiple classes on single element html

Short Answer

Yes.


Explanation

It is a good practice since an element can be a part of different groups, and you may want specific elements to be a part of more than one group. The element can hold an infinite number of classes in HTML5, while in HTML4 you are limited by a specific length.

The following example will show you the use of multiple classes.

The first class makes the text color red.

The second class makes the background-color blue.

See how the DOM Element with multiple classes will behave, it will wear both CSS statements at the same time.

Result: multiple CSS statements in different classes will stack up.

You can read more about CSS Specificity.


CSS

.class1 {
    color:red;
}

.class2 {
    background-color:blue;
}

HTML

<div class="class1">text 1</div>
<div class="class2">text 2</div>
<div class="class1 class2">text 3</div>

Live demo

How do I escape only single quotes?

I wrote the following function. It replaces the following:

Single quote ['] with a slash and a single quote [\'].

Backslash [\] with two backslashes [\\]

function escapePhpString($target) {
    $replacements = array(
            "'" => '\\\'',
            "\\" => '\\\\'
    );
    return strtr($target, $replacements);
}

You can modify it to add or remove character replacements in the $replacements array. For example, to replace \r\n, it becomes "\r\n" => "\r\n" and "\n" => "\n".

/**
 * With new line replacements too
 */
function escapePhpString($target) {
    $replacements = array(
            "'" => '\\\'',
            "\\" => '\\\\',
            "\r\n" => "\\r\\n",
            "\n" => "\\n"
    );
    return strtr($target, $replacements);
}

The neat feature about strtr is that it will prefer long replacements.

Example, "Cool\r\nFeature" will escape \r\n rather than escaping \n along.

In Python, how do I convert all of the items in a list to floats?

[float(i) for i in lst]

to be precise, it creates a new list with float values. Unlike the map approach it will work in py3k.

How to run python script in webpage

As others have pointed out, there are many web frameworks for Python.

But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:

  1. Rename your script to index.cgi. You also need to execute chmod +x index.cgi to give it execution privileges.

  2. Add these 2 lines in the beginning of the file:

#!/usr/bin/python   
print('Content-type: text/html\r\n\r')

After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.

Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python might work instead.