Programs & Examples On #Degrees

Java: Calculating the angle between two points in degrees

The javadoc for Math.atan(double) is pretty clear that the returning value can range from -pi/2 to pi/2. So you need to compensate for that return value.

How can I do a case insensitive string comparison?

You should use static String.Compare function like following

x => String.Compare (x.Username, (string)drUser["Username"],
                     StringComparison.OrdinalIgnoreCase) == 0

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

Found transport-attribute in binding-element which tells us that this is the WSDL 1.1 binding for the SOAP 1.1 HTTP binding.

ex.

<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

How to use Angular4 to set focus by element id

One of the answers in the question referred to by @Z.Bagley gave me the answer. I had to import Renderer2 from @angular/core into my component. Then:

const element = this.renderer.selectRootElement('#input1');

// setTimeout(() => element.focus, 0);
setTimeout(() => element.focus(), 0);

Thank you @MrBlaise for the solution!

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

Python/Json:Expecting property name enclosed in double quotes

import ast

inpt = {'http://example.org/about': {'http://purl.org/dc/terms/title':
                                     [{'type': 'literal', 'value': "Anna's Homepage"}]}}

json_data = ast.literal_eval(json.dumps(inpt))

print(json_data)

this will solve the problem.

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

    Windows PowerShell
    Copyright (C) 2014 Microsoft Corporation. All rights reserved.

    PS C:\Windows\system32> **$dte = Get-Date**
    PS C:\Windows\system32> **$PastDueDate = $dte.AddDays(-45).Date**
    PS C:\Windows\system32> **$PastDueDate**

    Sunday, March 1, 2020 12:00:00 AM

   PS C:\Windows\system32> **$NewDateFormat = Get-Date $PastDueDate -Format MMddyyyy**
   PS C:\Windows\system32> **$NewDateFormat 03012020**

There're few additional methods available as well e.g.: $dte.AddDays(-45).Day

Coding Conventions - Naming Enums

They're still types, so I always use the same naming conventions I use for classes.

I definitely would frown on putting "Class" or "Enum" in a name. If you have both a FruitClass and a FruitEnum then something else is wrong and you need more descriptive names. I'm trying to think about the kind of code that would lead to needing both, and it seems like there should be a Fruit base class with subtypes instead of an enum. (That's just my own speculation though, you may have a different situation than what I'm imagining.)

The best reference that I can find for naming constants comes from the Variables tutorial:

If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

How to display a list of images in a ListView in Android?

I'd start with something like this (and if there is something wrong with my code, I'd of course appreciate any comment):

public class ItemsList extends ListActivity {

private ItemsAdapter adapter;

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

    setContentView(R.layout.items_list);

    this.adapter = new ItemsAdapter(this, R.layout.items_list_item, ItemManager.getLoadedItems());
    setListAdapter(this.adapter);
}

private class ItemsAdapter extends ArrayAdapter<Item> {

    private Item[] items;

    public ItemsAdapter(Context context, int textViewResourceId, Item[] items) {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.items_list_item, null);
        }

        Item it = items[position];
        if (it != null) {
            ImageView iv = (ImageView) v.findViewById(R.id.list_item_image);
            if (iv != null) {
                iv.setImageDrawable(it.getImage());
            }
        }

        return v;
    }
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    this.adapter.getItem(position).click(this.getApplicationContext());
}
}

E.g. extending ArrayAdapter with own type of Items (holding information about your pictures) and overriden getView() method, that prepares view for items within list. There is also method add() on ArrayAdapter to add items to the end of the list.

R.layout.items_list is simple layout with ListView

R.layout.items_list_item is layout representing one item in list

Removing "bullets" from unordered list <ul>

Have you tried setting

li {list-style-type: none;}

According to Need an unordered list without any bullets, you need to add this style to the li elements.

Get the string value from List<String> through loop for display

Answer if you only want to use for each loop ..

for (WebElement s : options) {
    int i = options.indexOf(s);
    System.out.println(options.get(i).getText());
}

How to give a user only select permission on a database

You could add the user to the Database Level Role db_datareader.

Members of the db_datareader fixed database role can run a SELECT statement against any table or view in the database.

See Books Online for reference:

http://msdn.microsoft.com/en-us/library/ms189121%28SQL.90%29.aspx

You can add a database user to a database role using the following query:

EXEC sp_addrolemember N'db_datareader', N'userName'

Validation of file extension before uploading file

try this (Works for me)

_x000D_
_x000D_
  _x000D_
  function validate(){_x000D_
  var file= form.file.value;_x000D_
       var reg = /(.*?)\.(jpg|bmp|jpeg|png)$/;_x000D_
       if(!file.match(reg))_x000D_
       {_x000D_
        alert("Invalid File");_x000D_
        return false;_x000D_
       }_x000D_
       }
_x000D_
<form name="form">_x000D_
<input type="file" name="file"/>_x000D_
<input type="submit" onClick="return validate();"/>_x000D_
</form>_x000D_
_x000D_
     
_x000D_
_x000D_
_x000D_

How to simplify a null-safe compareTo() implementation?

You could design your class to be immutable (Effective Java 2nd Ed. has a great section on this, Item 15: Minimize mutability) and make sure upon construction that no nulls are possible (and use the null object pattern if needed). Then you can skip all those checks and safely assume the values are not null.

Why should hash functions use a prime number modulus?

Primes are used because you have good chances of obtaining a unique value for a typical hash-function which uses polynomials modulo P. Say, you use such hash-function for strings of length <= N, and you have a collision. That means that 2 different polynomials produce the same value modulo P. The difference of those polynomials is again a polynomial of the same degree N (or less). It has no more than N roots (this is here the nature of math shows itself, since this claim is only true for a polynomial over a field => prime number). So if N is much less than P, you are likely not to have a collision. After that, experiment can probably show that 37 is big enough to avoid collisions for a hash-table of strings which have length 5-10, and is small enough to use for calculations.

How to make ConstraintLayout work with percentage values?

The Guideline is invaluable - and the app:layout_constraintGuide_percent is a great friend... However sometimes we want percentages without guidelines. Now it's possible to use weights:

android:layout_width="0dp"
app:layout_constraintHorizontal_weight="1"

Here is a more complete example that uses a guideline with additional weights:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context="android.itomerbu.layoutdemo.MainActivity">

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.44"/>

    <Button
        android:id="@+id/btnThird"
        android:layout_width="0dp"
        app:layout_constraintHorizontal_weight="1"
        android:layout_height="wrap_content"
        android:text="@string/btnThird"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintRight_toLeftOf="@+id/btnTwoThirds"
        app:layout_constraintBottom_toTopOf="@+id/guideline"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"/>

    <Button
        android:id="@+id/btnTwoThirds"
        app:layout_constraintHorizontal_weight="2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/btnTwoThirds"
        app:layout_constraintBottom_toBottomOf="@+id/btnThird"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/btnThird"/>
</android.support.constraint.ConstraintLayout>

What is it exactly a BLOB in a DBMS context

any large single block of data stored in a database, such as a picture or sound file, which does not include record fields, and cannot be directly searched by the database's search engine.

How to find nth occurrence of character in a string?

//scala

// throw's -1 if the value isn't present for nth time, even if it is present till n-1 th time. // throw's index if the value is present for nth time

def indexOfWithNumber(tempString:String,valueString:String,numberOfOccurance:Int):Int={
var stabilizeIndex=0 
var tempSubString=tempString 
var tempIndex=tempString.indexOf(valueString) 
breakable
{
for ( i <- 1 to numberOfOccurance)
if ((tempSubString.indexOf(valueString) != -1) && (tempIndex != -1))
{
tempIndex=tempSubString.indexOf(valueString)
tempSubString=tempSubString.substring(tempIndex+1,tempSubString.size) // ADJUSTING FOR 0
stabilizeIndex=stabilizeIndex+tempIndex+1 // ADJUSTING FOR 0
}
else
{ 
stabilizeIndex= -1
tempIndex= 0
break
}
}
stabilizeIndex match { case value if value <= -1 => -1 case _ => stabilizeIndex-1 } // reverting for adjusting 0 previously
}


indexOfWithNumber("bbcfgtbgft","b",3) // 6
indexOfWithNumber("bbcfgtbgft","b",2) //1
indexOfWithNumber("bbcfgtbgft","b",4) //-1

indexOfWithNumber("bbcfgtbcgft","bc",1)  //1
indexOfWithNumber("bbcfgtbcgft","bc",4) //-1
indexOfWithNumber("bbcfgtbcgft","bc",2) //6

"Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP

Its because the variable '$user_location' is not getting defined. If you are using any if loop inside which you are declaring the '$user_location' variable then you must also have an else loop and define the same. For example:

$a=10;
if($a==5) { $user_location='Paris';} else { }
echo $user_location;

The above code will create error as The if loop is not satisfied and in the else loop '$user_location' was not defined. Still PHP was asked to echo out the variable. So to modify the code you must do the following:

$a=10;
if($a==5) { $user_location='Paris';} else { $user_location='SOMETHING OR BLANK'; }
echo $user_location;

What is a word boundary in regex, does \b match hyphen '-'?

Check out the documentation on boundary conditions:

http://java.sun.com/docs/books/tutorial/essential/regex/bounds.html

Check out this sample:

public static void main(final String[] args)
    {
        String x = "I found the value -12 in my string.";
        System.err.println(Arrays.toString(x.split("\\b-?\\d+\\b")));
    }

When you print it out, notice that the output is this:

[I found the value -, in my string.]

This means that the "-" character is not being picked up as being on the boundary of a word because it's not considered a word character. Looks like @brianary kinda beat me to the punch, so he gets an up-vote.

Printing Exception Message in java

try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}

plotting different colors in matplotlib

@tcaswell already answered, but I was in the middle of typing my answer up, so I'll go ahead and post it...

There are a number of different ways you could do this. To begin with, matplotlib will automatically cycle through colors. By default, it cycles through blue, green, red, cyan, magenta, yellow, black:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

If you want to control which colors matplotlib cycles through, use ax.set_color_cycle:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
fig, ax = plt.subplots()
ax.set_color_cycle(['red', 'black', 'yellow'])
for i in range(1, 6):
    plt.plot(x, i * x + i, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

If you'd like to explicitly specify the colors that will be used, just pass it to the color kwarg (html colors names are accepted, as are rgb tuples and hex strings):

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
for i, color in enumerate(['red', 'black', 'blue', 'brown', 'green'], start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

Finally, if you'd like to automatically select a specified number of colors from an existing colormap:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 1, 10)
number = 5
cmap = plt.get_cmap('gnuplot')
colors = [cmap(i) for i in np.linspace(0, 1, number)]

for i, color in enumerate(colors, start=1):
    plt.plot(x, i * x + i, color=color, label='$y = {i}x + {i}$'.format(i=i))
plt.legend(loc='best')
plt.show()

enter image description here

How do I pass variables and data from PHP to JavaScript?

I quite like the way the WordPress works with its enqueue and localize functions, so following that model, I wrote a simple class for putting a scripts into page according to the script dependencies, and for making additional data available for the script.

class mHeader {

    private $scripts = array();

    /**
     * @param string $id        Unique script identifier
     * @param string $src      Script src attribute
     * @param array  $deps       An array of dependencies ( script identifiers ).
     * @param array  $data       An array, data that will be json_encoded and available to the script.
     */
    function enqueue_script($id, $src, $deps = array(), $data = array()) {
        $this->scripts[$id] = array('src' => $src, 'deps' => $deps, 'data' => $data);
    }

    private function dependencies($script) {
        if ($script['deps']) {
            return array_map(array($this, 'dependencies'), array_intersect_key($this->scripts, array_flip($script['deps'])));
        }
    }

    private function _unset($key, &$deps, &$out) {
        $out[$key] = $this->scripts[$key];
        unset($deps[$key]);
    }

    private function flattern(&$deps, &$out = array()) {

        foreach($deps as $key => $value) {
            empty($value) ? $this->_unset($key, $deps, $out) : $this->flattern( $deps[$key], $out);
        }
    }

    function print_scripts() {

        if (!$this->scripts)
            return;

        $deps = array_map(array($this, 'dependencies'), $this->scripts);
        while ($deps)
            $this->flattern($deps, $js);

        foreach($js as $key => $script) {
            $script['data'] && printf("<script> var %s = %s; </script>" . PHP_EOL, key($script['data']), json_encode(current( $script['data'])));
            echo "<script id=\"$key-js\" src=\"$script[src]\" type=\"text/javascript\"></script>" . PHP_EOL;
        }
    }
}

The call to the enqueue_script() function is for adding script, setting the source and dependencies on other scripts, and additional data needed for the script.

$header = new mHeader();

$header->enqueue_script('jquery-ui', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js', array('jquery'));
$header->enqueue_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js');
$header->enqueue_script('custom-script', '//custom-script.min.js', array('jquery-ui'), array('mydata' => array('value' => 20)));

$header->print_scripts();

And, print_scripts() method of the above example will send this output:

<script id="jquery-js" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script id="jquery-ui-js" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js" type="text/javascript"></script>
<script> var mydata = {"value":20}; </script>
<script id="custom-script-js" src="//custom-script.min.js" type="text/javascript"></script>

Regardless the fact that the script 'jquery' is enqueued after the 'jquery-ui', it is printed before because it is defined in 'jquery-ui' that it depends on 'jquery'. Additional data for the 'custom-script' are inside a new script block and are placed in front of it, it contains mydata object that holds additional data, now available to 'custom-script'.

What is the difference between explicit and implicit cursors in Oracle?

An explicit cursor is defined as such in a declaration block:

DECLARE 
CURSOR cur IS 
  SELECT columns FROM table WHERE condition;
BEGIN
...

an implicit cursor is implented directly in a code block:

...
BEGIN
   SELECT columns INTO variables FROM table where condition;
END;
...

How does Java resolve a relative path in new File()?

There is a concept of a working directory.
This directory is represented by a . (dot).
In relative paths, everything else is relative to it.

Simply put the . (the working directory) is where you run your program.
In some cases the working directory can be changed but in general this is
what the dot represents. I think this is C:\JavaForTesters\ in your case.

So test\..\test.txt means: the sub-directory test
in my working directory, then one level up, then the
file test.txt. This is basically the same as just test.txt.

For more details check here.

http://docs.oracle.com/javase/7/docs/api/java/io/File.html

http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

Given a URL to a text file, what is the simplest way to read the contents of the text file?

The requests library has a simpler interface and works with both Python 2 and 3.

import requests

response = requests.get(target_url)
data = response.text

How can I compile a Java program in Eclipse without running it?

In the case that you delete your .class file in Eclipse and then try to build it again from the .java file it will do nothing. If you try to run the .java file without the .class file you will get an error that it can not find the main class.

You will either have to change and re-save the .java file then build it again, or else you have to run Clean on the project then build again.

Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

I had the same warning using the raster package.

> my_mask[my_mask[] != 1] <- NA
Error: cannot allocate vector of size 5.4 Gb

The solution is really simple and consist in increasing the storage capacity of R, here the code line:

##To know the current storage capacity
> memory.limit()
[1] 8103
## To increase the storage capacity
> memory.limit(size=56000)
[1] 56000    
## I did this to increase my storage capacity to 7GB

Hopefully, this will help you to solve the problem Cheers

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

Am using Mountain Lion. What I did was Look for /usr/local and Get Info. On it there is Sharing and Permissions. Make sure that its only the user and Admin are the only ones who have read and write permissions. Anyone else should have read access only. That sorted my problem.

Its normally helpful is your Run disk utilities and repair permissions too.

Android get image from gallery into ImageView

parag-chauhan and devrim answers are perfect, but i change the onActivityResult without cursor, and it makes the code much more better.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
        Uri selectedImage = data.getData();
        try {
           ImageView imageView = (ImageView) findViewById(R.id.imgView);
           imageView.setImageBitmap(getScaledBitmap(selectedImage,800,800));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

private Bitmap getScaledBitmap(Uri selectedImage, int width, int height) throws FileNotFoundException {
    BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
    sizeOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, sizeOptions);

    int inSampleSize = calculateInSampleSize(sizeOptions, width, height);

    sizeOptions.inJustDecodeBounds = false;
    sizeOptions.inSampleSize = inSampleSize;

    return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, sizeOptions);
}

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

    if (height > reqHeight || width > reqWidth) {
        // Calculate ratios of height and width to requested one
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }
    return inSampleSize;
}

How to call webmethod in Asp.net C#

There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.

Script example:

$.ajax({
    type: "POST",
    url: '/Default.aspx/TestMethod',
    data: '{message: "HAI" }',
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        console.log(data);
    },
    failure: function (response) {
        alert(response.d);
    }
});

WebMethod example:

[WebMethod]
public static string TestMethod(string message)
{
     return "The message" + message;
}

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

R: Print list to a text file

Here's another way using sink:

sink(sink_dir_and_file_name); print(yourList); sink()

What is the difference between dynamic and static polymorphism in Java?

  • Method overloading would be an example of static polymorphism

  • whereas overriding would be an example of dynamic polymorphism.

    Because, in case of overloading, at compile time the compiler knows which method to link to the call. However, it is determined at runtime for dynamic polymorphism

Is there a way to access the "previous row" value in a SELECT statement?

select t2.col from (
select col,MAX(ID) id from 
(
select ROW_NUMBER() over(PARTITION by col order by col) id ,col from testtab t1) as t1
group by col) as t2

Query for documents where array size is greater than 1

You can MongoDB aggregation to do the task:

db.collection.aggregate([
  {
    $addFields: {
      arrayLength: {$size: '$array'}
    },
  },
  {
    $match: {
      arrayLength: {$gt: 1}
    },
  },
])

Excel VBA date formats

To ensure that a cell will return a date value and not just a string that looks like a date, first you must set the NumberFormat property to a Date format, then put a real date into the cell's content.

Sub test_date_or_String()
 Set c = ActiveCell
 c.NumberFormat = "@"
 c.Value = CDate("03/04/2014")
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a String
 c.NumberFormat = "m/d/yyyy"
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is still a String
 c.Value = CDate("03/04/2014")
   Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a date    
End Sub

Last Run Date on a Stored Procedure in SQL Server

If you enable Query Store on SQL Server 2016 or newer you can use the following query to get last SP execution. The history depends on the Query Store Configuration.

SELECT 
      ObjectName = '[' + s.name + '].[' + o.Name  + ']'
    , LastModificationDate  = MAX(o.modify_date)
    , LastExecutionTime     = MAX(q.last_execution_time)
FROM sys.query_store_query q 
    INNER JOIN sys.objects o
        ON q.object_id = o.object_id
    INNER JOIN sys.schemas s
        ON o.schema_id = s.schema_id
WHERE o.type IN ('P')
GROUP BY o.name , + s.name 

how to define variable in jquery

Here's are some examples:

var name = 'india';
alert(name);  


var name = $("#txtname").val();
alert(name);

Taken from http://way2finder.blogspot.in/2013/09/how-to-create-variable-in-jquery.html

Get yesterday's date using Date

Try this;

   public String toDate() {
       DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
       Calendar cal = Calendar.getInstance();
       cal.add(Calendar.DATE, -1);
       return dateFormat.format(cal.getTime());
  }

How do I remove a substring from the end of a string in Python?

Python >= 3.9:

'abcdc.com'.removesuffix('.com')

Python < 3.9:

def remove_suffix(text, suffix):
    if text.endswith(suffix):
        text = text[:-len(suffix)]
    return text

remove_suffix('abcdc.com', '.com')

Splitting strings in PHP and get last part

Since explode() returns an array, you can add square brackets directly to the end of that function, if you happen to know the position of the last array item.

$email = '[email protected]';
$provider = explode('@', $email)[1];
echo $provider; // example.com

Or another way is list():

$email = '[email protected]';
list($prefix, $provider) = explode('@', $email);
echo $provider; // example.com

If you don't know the position:

$path = 'one/two/three/four';
$dirs = explode('/', $path);
$last_dir = $dirs[count($dirs) - 1];
echo $last_dir; // four

Aligning rotated xticklabels with their respective xticks

Rotating the labels is certainly possible. Note though that doing so reduces the readability of the text. One alternative is to alternate label positions using a code like this:

import numpy as np
n=5

x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]


fig, ax = plt.subplots()
ax.plot(x,y, 'o-')
ax.set_xticks(x)
labels = ax.set_xticklabels(xlabels)
for i, label in enumerate(labels):
    label.set_y(label.get_position()[1] - (i % 2) * 0.075)

enter image description here

For more background and alternatives, see this post on my blog

The import android.support cannot be resolved

Android Studio 2.2.3 Linux Mint 18.1

Inside your 'project view' open Gradle Scripts -> build.gradle(Module:app) and put your mouse pointer inside the word dependencies.

Click on the light bulb and click "add library dependency" and for me all the libraries I wanted were listed there.

example libraries that came up for me: compile 'com.android.support:gridlayout-v7:25.1.0' compile 'com.android.support:support-v13:25.1.0'

I am now looking to add android support by default in Gradles default configuration.

Can't create handler inside thread that has not called Looper.prepare()

Here is the solution for Kotlin using Coroutine:

Extend your class with CoroutineScope by MainScope():

class BootstrapActivity :  CoroutineScope by MainScope() {}

Then simply do this:

launch {
        // whatever you want to do in the main thread
    }

Don't forget to add the dependencies for coroutine:

org.jetbrains.kotlinx:kotlinx-coroutines-core:${Versions.kotlinCoroutines}
org.jetbrains.kotlinx:kotlinx-coroutines-android:${Versions.kotlinCoroutines}

Make Bootstrap Popover Appear/Disappear on Hover instead of Click

After trying a few of these answers and finding they don't scale well with multiple links (for example the accepted answer requires a line of jquery for every link you have), I came across a way that requires minimal code to get working, and it also appears to work perfectly, at least on Chrome.

You add this line to activate it:

$('[data-toggle="popover"]').popover();

And these settings to your anchor links:

data-toggle="popover" data-trigger="hover"

See it in action here, I'm using the same imports as the accepted answer so it should work fine on older projects.

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

You should use:

URLEncoder.encode("NAME", "UTF-8");

Auto-loading lib files in Rails 4

This might help someone like me that finds this answer when searching for solutions to how Rails handles the class loading ... I found that I had to define a module whose name matched my filename appropriately, rather than just defining a class:

In file lib/development_mail_interceptor.rb (Yes, I'm using code from a Railscast :))

module DevelopmentMailInterceptor
  class DevelopmentMailInterceptor
    def self.delivering_email(message)
      message.subject = "intercepted for: #{message.to} #{message.subject}"
      message.to = "[email protected]"
    end
  end
end

works, but it doesn't load if I hadn't put the class inside a module.

JDBC connection to MSSQL server in windows authentication mode

For the current MS SQL JDBC driver (6.4.0) tested under Windows 7 from within DataGrip:

  1. as per documentation on authenticationScheme use fully qualified domain name as host e.g. server.your.domain not just server; the documentation also mentions the possibility to specify serverSpn=MSSQLSvc/fqdn:port@REALM, but I can not provide you with details on how to use this. When specifying a fqdn as host the spn is auto-generated.
  2. set authenticationScheme=JavaKerberos
  3. set integratedSecurity=true
  4. use your unqualified user-name (and password) to log in

As this is using JavaKerberos I would appreciate feedback on whether or not this works from outside Windows. I believe that no .dll is needed, but as I used DataGrip to create the connection I am uncertain; I would also appreciate Feedback on this!

Non-recursive depth first search algorithm

Just wanted to add my python implementation to the long list of solutions. This non-recursive algorithm has discovery and finished events.


worklist = [root_node]
visited = set()
while worklist:
    node = worklist[-1]
    if node in visited:
        # Node is finished
        worklist.pop()
    else:
        # Node is discovered
        visited.add(node)
        for child in node.children:
            worklist.append(child)

How to place div in top right hand corner of page

You can use css float

<div style='float: left;'><a href="login.php">Log in</a></div>

<div style='float: right;'><a href="home.php">Back to Home</a></div>

Have a look at this CSS Positioning

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

They are the same thing. If you use the set transaction isolation level statement, it will apply to all the tables in the connection, so if you only want a nolock on one or two tables use that; otherwise use the other.

Both will give you dirty reads. If you are okay with that, then use them. If you can't have dirty reads, then consider snapshot or serializable hints instead.

Set selected radio from radio group with a value

$('input[name="mygroup"]').val([5])

PHP foreach change original array values

Use &:

foreach($arr as &$value) {
    $value = $newVal;
}

& passes a value of the array as a reference and does not create a new instance of the variable. Thus if you change the reference the original value will change.

PHP documentation for Passing by Reference

Edit 2018

This answer seems to be favored by a lot of people on the internet, which is why I decided to add more information and words of caution.
While pass by reference in foreach (or functions) is a clean and short solution, for many beginners this might be a dangerous pitfall.

  1. Loops in PHP don't have their own scope. - @Mark Amery

    This could be a serious problem when the variables are being reused in the same scope. Another SO question nicely illustrates why that might be a problem.

  2. As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior. - PHP docs for foreach.

    Unsetting a record or changing the hash value (the key) during the iteration on the same loop could lead to potentially unexpected behaviors in PHP < 7. The issue gets even more complicated when the array itself is a reference.

  3. Foreach performance.
    In general, PHP prefers pass by value due to the copy-on-write feature. It means that internally PHP will not create duplicate data unless the copy of it needs to be changed. It is debatable whether pass by reference in foreach would offer a performance improvement. As it is always the case, you need to test your specific scenario and determine which option uses less memory and CPU time. For more information see the SO post linked below by NikiC.

  4. Code readability.
    Creating references in PHP is something that quickly gets out of hand. If you are a novice and don't have full control of what you are doing, it is best to stay away from references. For more information about & operator take a look at this guide: Reference — What does this symbol mean in PHP?
    For those who want to learn more about this part of PHP language: PHP References Explained

A very nice technical explanation by @NikiC of the internal logic of PHP foreach loops:
How does PHP 'foreach' actually work?

round() doesn't seem to be rounding properly

You can switch the data type to an integer:

>>> n = 5.59
>>> int(n * 10) / 10.0
5.5
>>> int(n * 10 + 0.5)
56

And then display the number by inserting the locale's decimal separator.

However, Jimmy's answer is better.

How do I validate a date in this format (yyyy-mm-dd) using jquery?

try this Here is working Demo:

$(function() {
    $('#btnSubmit').bind('click', function(){
        var txtVal =  $('#txtDate').val();
        if(isDate(txtVal))
            alert('Valid Date');
        else
            alert('Invalid Date');
    });

function isDate(txtDate)
{
    var currVal = txtDate;
    if(currVal == '')
        return false;

    var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
    var dtArray = currVal.match(rxDatePattern); // is format OK?

    if (dtArray == null) 
        return false;

    //Checks for mm/dd/yyyy format.
    dtMonth = dtArray[3];
    dtDay= dtArray[5];
    dtYear = dtArray[1];        

    if (dtMonth < 1 || dtMonth > 12) 
        return false;
    else if (dtDay < 1 || dtDay> 31) 
        return false;
    else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31) 
        return false;
    else if (dtMonth == 2) 
    {
        var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
        if (dtDay> 29 || (dtDay ==29 && !isleap)) 
                return false;
    }
    return true;
}

});

changed regex is:

var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex

How to change sa password in SQL Server 2008 express?

This may help you to reset your sa password for SQL 2008 and 2012

EXEC sp_password NULL, 'yourpassword', 'sa'

Call a React component method from outside

class AppProvider extends Component {
  constructor() {
    super();

    window.alertMessage = this.alertMessage.bind(this);
  }

  alertMessage() {
    console.log('Hello World');
 }
}

You can call this method from the window by using window.alertMessage().

How to get std::vector pointer to the raw data?

&something gives you the address of the std::vector object, not the address of the data it holds. &something.begin() gives you the address of the iterator returned by begin() (as the compiler warns, this is not technically allowed because something.begin() is an rvalue expression, so its address cannot be taken).

Assuming the container has at least one element in it, you need to get the address of the initial element of the container, which you can get via

  • &something[0] or &something.front() (the address of the element at index 0), or

  • &*something.begin() (the address of the element pointed to by the iterator returned by begin()).

In C++11, a new member function was added to std::vector: data(). This member function returns the address of the initial element in the container, just like &something.front(). The advantage of this member function is that it is okay to call it even if the container is empty.

Why do I need an IoC container as opposed to straightforward DI code?

You would need an IoC container if you needed to centralize the configuration of your dependencies so that they may be easily swapped out en mass. This makes the most sense in TDD, where many dependencies are swapped out, but where there is little interdependence between the dependencies. This is done at the cost of obfuscating the flow of control of object construction to some degree, so having a well organized and reasonably documented configuration is important. It is also good to have a reason to do this, otherwise, it is mere abstraction gold-plating. I have seen it done so poorly that it was dragged down to being the equivalent to a goto statement for constructors.

java IO Exception: Stream Closed

You call writer.close(); in writeToFile so the writer has been closed the second time you call writeToFile.

Why don't you merge FileStatus into writeToFile?

How to import the class within the same directory or sub directory?

If you have filename.py in the same folder, you can easily import it like this:

import filename

I am using python3.7

Copying a HashMap in Java

Since the OP has mentioned he does not have access to the base class inside of which exists a HashMap - I am afraid there are very few options available.

One (painfully slow and resource intensive) way of performing a deep copy of an object in Java is to abuse the 'Serializable' interface which many classes either intentionally - or unintentionally extend - and then utilise this to serialise your class to ByteStream. Upon de-serialisation you will have a deep copy of the object in question.

A guide for this can be found here: https://www.avajava.com/tutorials/lessons/how-do-i-perform-a-deep-clone-using-serializable.html

Linq Select Group By

You should try it like this:

var result =
        from priceLog in PriceLogList
        group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
        select new {
            LogDateTime = dateGroup.Key,
            AvgPrice = dateGroup.Average(priceLog => priceLog.Price)
        };

Edittext change border color with shape.xml

Use root tag as shape instead of selector in your shape.xml file, and it will resolve your problem!

How to JOIN three tables in Codeigniter

   Check bellow code it`s working fine and  common model function also 
    supported more then one join and also supported  multiple where condition
 order by ,limit.it`s EASY TO USE and REMOVE CODE REDUNDANCY.

   ================================================================
    *Album.php
   //put bellow code in your controller
   =================================================================

    $album_id='';//album id 

   //pass join table value in bellow format
    $join_str[0]['table'] = 'Category';
    $join_str[0]['join_table_id'] = 'Category.cat_id';
    $join_str[0]['from_table_id'] = 'Album.cat_id';
    $join_str[0]['join_type'] = 'left';

    $join_str[1]['table'] = 'Soundtrack';
    $join_str[1]['join_table_id'] = 'Soundtrack.album_id';
    $join_str[1]['from_table_id'] = 'Album.album_id';
    $join_str[1]['join_type'] = 'left';


    $selected = "Album.*,Category.cat_name,Category.cat_title,Soundtrack.track_title,Soundtrack.track_url";

   $albumData= $this->common->select_data_by_condition('Album', array('Soundtrack.album_id' => $album_id), $selected, '', '', '', '', $join_str);
                               //call common model function

    if (!empty($albumData)) {
        print_r($albumData); // print album data
    } 

 =========================================================================
   Common.php
    //put bellow code in your common model file
 ========================================================================

   function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
    $this->db->select($data);
    //if join_str array is not empty then implement the join query
    if (!empty($join_str)) {
        foreach ($join_str as $join) {
            if ($join['join_type'] == '') {
                $this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
            } else {
                $this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
            }
        }
    }

    //condition array pass to where condition
    $this->db->where($condition_array);


    //Setting Limit for Paging
    if ($limit != '' && $offset == 0) {
        $this->db->limit($limit);
    } else if ($limit != '' && $offset != 0) {
        $this->db->limit($limit, $offset);
    }
    //order by query
    if ($sortby != '' && $orderby != '') {
        $this->db->order_by($sortby, $orderby);
    }

    $query = $this->db->get($tablename);
    //if limit is empty then returns total count
    if ($limit == '') {
        $query->num_rows();
    }
    //if limit is not empty then return result array
    return $query->result_array();
}

Uploading Laravel Project onto Web Server

I believe - your Laravel files/folders should not be placed in root directory.

e.g. If your domain is pointed to public_html directory then all content should placed in that directory. How ? let me tell you

  1. Copy all files and folders ( including public folder ) in public html
  2. Copy all content of public folder and paste it in document root ( i.e. public_html )
  3. Remove the public folder
  4. Open your bootstrap/paths.php and then changed 'public' => __DIR__.'/../public', into 'public' => __DIR__.'/..',

  5. and finally in index.php,

    Change

require __DIR__.'/../bootstrap/autoload.php';

$app = require_once __DIR__.'/../bootstrap/start.php';

into

require __DIR__.'/bootstrap/autoload.php';

$app = require_once __DIR__.'/bootstrap/start.php';

Your Laravel application should work now.

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

As others have already mentioned you are required to provide a default constructor public Employee(){} in your Employee class.

What happens is that the compiler automatically provides a no-argument, default constructor for any class without constructors. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor. In this case you are declaring a constructor in your class Employee therefore you must provide also the no-argument constructor.

Having said that Employee class should look like this:

Your class Employee

import java.util.Date;

public class Employee
{
      private String name, number;
      private Date date;

      public Employee(){} // No-argument Constructor

      public Employee(String name, String number, Date date)
      {
            setName(name);
            setNumber(number);
            setDate(date);
      }

      public void setName(String n)
      {
            name = n;
      }
      public void setNumber(String n)
      {
            number = n;
            // you can check the format here for correctness
      }
      public void setDate(Date d)
      {
            date = d;
      }

      public String getName()
      {
            return name;
      }
      public String getNumber()
      {
            return number;
      }
      public Date getDate()
      {
            return date;
      }
}

Here is the Java Oracle tutorial - Providing Constructors for Your Classes chapter. Go through it and you will have a clearer idea of what is going on.

compareTo with primitives -> Integer / int

If you need just logical value (as it almost always is), the following one-liner will help you:

boolean ifIntsEqual = !((Math.max(a,b) - Math.min(a, b)) > 0);

And it works even in Java 1.5+, maybe even in 1.1 (i don't have one). Please tell us, if you can test it in 1.5-.

This one will do too:

boolean ifIntsEqual = !((Math.abs(a-b)) > 0);

How to use global variables in React Native?

If you just want to pass some data from one screen to the next, you can pass them with the navigation.navigate method like this:

<Button onPress={()=> {this.props.navigation.navigate('NextScreen',{foo:bar)} />

and in 'NextScreen' you can access them with the navigation.getParam() method:

let foo=this.props.navigation.getParam(foo);

But it can get really "messy" if you have more than a couple of variables to pass..

How can I tell jaxb / Maven to generate multiple schema packages?

You can use also JAXB bindings to specify different package for each schema, e.g.

<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0" schemaLocation="book.xsd">

    <jaxb:globalBindings>
        <xjc:serializable uid="1" />
    </jaxb:globalBindings>

    <jaxb:schemaBindings>
        <jaxb:package name="com.stackoverflow.book" />
    </jaxb:schemaBindings>

</jaxb:bindings>

Then just use the new maven-jaxb2-plugin 0.8.0 <schemas> and <bindings> elements in the pom.xml. Or specify the top most directory in <schemaDirectory> and <bindingDirectory> and by <include> your schemas and bindings:

<schemaDirectory>src/main/resources/xsd</schemaDirectory>
<schemaIncludes>
    <include>book/*.xsd</include>
    <include>person/*.xsd</include>
</schemaIncludes>
<bindingDirectory>src/main/resources</bindingDirectory>
<bindingIncludes>
    <include>book/*.xjb</include>
    <include>person/*.xjb</include>
</bindingIncludes>

I think this is more convenient solution, because when you add a new XSD you do not need to change Maven pom.xml, just add a new XJB binding file to the same directory.

Check if list contains element that contains a string and get that element

you can use

var match=myList.Where(item=>item.Contains("Required String"));
foreach(var i in match)
{
//do something with the matched items
}

LINQ provides you with capabilities to "query" any collection of data. You can use syntax like a database query (select, where, etc) on a collection (here the collection (list) of strings).

so you are doing like "get me items from the list Where it satisfies a given condition"

inside the Where you are using a "lambda expression"

to tell briefly lambda expression is something like (input parameter => return value)

so for a parameter "item", it returns "item.Contains("required string")" . So it returns true if the item contains the string and thereby it gets selected from the list since it satisfied the condition.

error LNK2005, already defined?

And if you want these translation units to share this variable, define int k; in A.cpp and put extern int k; in B.cpp.

Is there a goto statement in Java?

James Gosling created the original JVM with support of goto statements, but then he removed this feature as needless. The main reason goto is unnecessary is that usually it can be replaced with more readable statements (like break/continue) or by extracting a piece of code into a method.

Source: James Gosling, Q&A session

Deep copy in ES6 using the spread syntax

const a = {
  foods: {
    dinner: 'Pasta'
  }
}
let b = JSON.parse(JSON.stringify(a))
b.foods.dinner = 'Soup'
console.log(b.foods.dinner) // Soup
console.log(a.foods.dinner) // Pasta

Using JSON.stringify and JSON.parse is the best way. Because by using the spread operator we will not get the efficient answer when the json object contains another object inside it. we need to manually specify that.

Setting a width and height on an A tag

You need to make your anchor display: block or display: inline-block; and then it will accept the width and height values.

Java Regex Capturing Groups

Your understanding is correct. However, if we walk through:

  • (.*) will swallow the whole string;
  • it will need to give back characters so that (\\d+) is satistifed (which is why 0 is captured, and not 3000);
  • the last (.*) will then capture the rest.

I am not sure what the original intent of the author was, however.

ORA-00984: column not allowed here

Replace double quotes with single ones:

INSERT
INTO    MY.LOGFILE
        (id,severity,category,logdate,appendername,message,extrainfo)
VALUES  (
       'dee205e29ec34',
       'FATAL',
       'facade.uploader.model',
       '2013-06-11 17:16:31',
       'LOGDB',
       NULL,
       NULL
       )

In SQL, double quotes are used to mark identifiers, not string constants.

How to disable text selection using jQuery?

This can easily be done using JavaScript This is applicable to all Browsers

<script type="text/javascript">

/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE 
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
    target.style.MozUserSelect="none"
else //All other route (For Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}
 </script>

Call to this function

<script type="text/javascript">
   disableSelection(document.body)
</script>

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

Difference between String replace() and replaceAll()

To add to the already selected "Best Answer" (and others that are just as good like Suragch's), String.replace() is constrained by replacing characters that are sequential (thus taking CharSequence). However, String.replaceAll() is not constrained by replacing sequential characters only. You could replace non-sequential characters as well as long as your regular expression is constructed in such a way.

Also (most importantly and painfully obvious), replace() can only replace literal values; whereas replaceAll can replace 'like' sequences (not necessarily identical).

How to check if my string is equal to null?

If myString is in fact null, then any call to the reference will fail with a Null Pointer Exception (NPE). Since java 6, use #isEmpty instead of length check (in any case NEVER create a new empty String with the check).

if (myString != null &&  !myString.isEmpty()){
    doSomething();
}

Incidentally if comparing with String literals as you do, would reverse the statement so as not to have to have a null check, i.e,

if ("some string to check".equals(myString)){
  doSomething();
} 

instead of :

if (myString != null &&  myString.equals("some string to check")){
    doSomething();
}

Automapper missing type map configuration or unsupported mapping - Error

Check your Global.asax.cs file and be sure that this line be there

 AutoMapperConfig.Configure();

how does unix handle full path name with space and arguments?

You can quote if you like, or you can escape the spaces with a preceding \, but most UNIX paths (Mac OS X aside) don't have spaces in them.

/Applications/Image\ Capture.app/Contents/MacOS/Image\ Capture

"/Applications/Image Capture.app/Contents/MacOS/Image Capture"

/Applications/"Image Capture.app"/Contents/MacOS/"Image Capture"

All refer to the same executable under Mac OS X.

I'm not sure what you mean about recognizing a path - if any of the above paths are passed as a parameter to a program the shell will put the entire string in one variable - you don't have to parse multiple arguments to get the entire path.

Is jQuery $.browser Deprecated?

From the documentation:

The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery.

So, yes, it is deprecated, but your existing implementations will continue to work. If the functionality is removed, it will likely be easily accessible using a plugin.

As to whether there is an alternative... The answer is "yes, probably". It is far, far better to do feature detection using $.support rather than browser detection: detect the actual feature you need, not the browser that provides it. Most important features that vary from browser to browser are detected with that.


Update 16 February 2013: In jQuery 1.9, this feature was removed (docs). It is far better not to use it. If you really, really must use its functionality, you can restore it with the jQuery Migrate plugin.

Chrome doesn't delete session cookies

I just had this problem of Chrome storing a Session ID but I do not like the idea of disabling the option to continue where I left off. I looked at the cookies for the website and found a Session ID cookie for the login page. Deleting that did not correct my problem. I search for the domain and found there was another Session ID cookie on the domain. Deleting both Session ID cookies manually fixed the problem and I did not close and reopen the browser which could have restored the cookies.

Can I get "&&" or "-and" to work in PowerShell?

If your command is available in cmd.exe (something like python ./script.py, but not PowerShell command like ii . (this means to open the current directory by Windows Explorer)), you can run cmd.exe within PowerShell. The syntax is like this:

cmd /c "command1 && command2"

Here, && is provided by cmd syntax described in this question.

Babel 6 regeneratorRuntime is not defined

Using stage-2 preset before react preset helped me:

npx babel --watch src --out-dir . --presets stage-2,react

The above code works when the following modules are installed:

npm install babel-cli babel-core babel-preset-react babel-preset-stage-2 --save-dev

How can I convert a long to int in Java?

You can use the Long wrapper instead of long primitive and call

Long.intValue()

Java7 intValue() docs

It rounds/truncate the long value accordingly to fit in an int.

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

You can flip it around and list the dependencies in setup.py and have a single character — a dot . — in requirements.txt instead.


Alternatively, even if not advised, it is still possible to parse the requirements.txt file (if it doesn't refer any external requirements by URL) with the following hack (tested with pip 9.0.1):

install_reqs = parse_requirements('requirements.txt', session='hack')

This doesn't filter environment markers though.


In old versions of pip, more specifically older than 6.0, there is a public API that can be used to achieve this. A requirement file can contain comments (#) and can include some other files (--requirement or -r). Thus, if you really want to parse a requirements.txt you can use the pip parser:

from pip.req import parse_requirements

# parse_requirements() returns generator of pip.req.InstallRequirement objects
install_reqs = parse_requirements(<requirements_path>)

# reqs is a list of requirement
# e.g. ['django==1.5.1', 'mezzanine==1.4.6']
reqs = [str(ir.req) for ir in install_reqs]

setup(
    ...
    install_requires=reqs
)

How to read all rows from huge table?

I did it like below. Not the best way i think, but it works :)

    Connection c = DriverManager.getConnection("jdbc:postgresql://....");
    PreparedStatement s = c.prepareStatement("select * from " + tabName + " where id > ? order by id");
    s.setMaxRows(100);
    int lastId = 0;
    for (;;) {
        s.setInt(1, lastId);
        ResultSet rs = s.executeQuery();

        int lastIdBefore = lastId;
        while (rs.next()) {
            lastId = Integer.parseInt(rs.getObject(1).toString());
            // ...
        }

        if (lastIdBefore == lastId) {
            break;
        }
    }

how to use sqltransaction in c#

Well, I don't understand why are you used transaction in case when you make a select.

Transaction is useful when you make changes (add, edit or delete) data from database.

Remove transaction unless you use insert, update or delete statements

Explicit Return Type of Lambda

You can explicitly specify the return type of a lambda by using -> Type after the arguments list:

[]() -> Type { }

However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.

How do I remove  from the beginning of a file?

For those with shell access here is a little command to find all files with the BOM set in the public_html directory - be sure to change it to what your correct path on your server is

Code:

grep -rl $'\xEF\xBB\xBF' /home/username/public_html

and if you are comfortable with the vi editor, open the file in vi:

vi /path-to-file-name/file.php

And enter the command to remove the BOM:

set nobomb

Save the file:

wq

How do I create a Java string from the contents of a file?

If you do not have access to the Files class, you can use a native solution.

static String readFile(File file, String charset)
        throws IOException
{
    FileInputStream fileInputStream = new FileInputStream(file);
    byte[] buffer = new byte[fileInputStream.available()];
    int length = fileInputStream.read(buffer);
    fileInputStream.close();
    return new String(buffer, 0, length, charset);
}

How do I concatenate two strings in C?

#include <stdio.h>

int main(){
    char name[] =  "derp" "herp";
    printf("\"%s\"\n", name);//"derpherp"
    return 0;
}

Common MySQL fields and their appropriate data types

Someone's going to post a much better answer than this, but just wanted to make the point that personally I would never store a phone number in any kind of integer field, mainly because:

  1. You don't need to do any kind of arithmetic with it, and
  2. Sooner or later someone's going to try to (do something like) put brackets around their area code.

In general though, I seem to almost exclusively use:

  • INT(11) for anything that is either an ID or references another ID
  • DATETIME for time stamps
  • VARCHAR(255) for anything guaranteed to be under 255 characters (page titles, names, etc)
  • TEXT for pretty much everything else.

Of course there are exceptions, but I find that covers most eventualities.

Javascript Image Resize

Here is my cover fill solution (similar to background-size: cover, but it supports old IE browser)

<div class="imgContainer" style="height:100px; width:500px; overflow:hidden; background-color: black">
    <img src="http://dev.isaacsonwebdevelopment.com/sites/development/files/views-slideshow-settings-jquery-cycle-custom-options-message.png" id="imgCat">
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script>
    $(window).load(function() {
        var heightRate =$("#imgCat").height() / $("#imgCat").parent(".imgContainer").height();
        var widthRate = $("#imgCat").width() / $("#imgCat").parent(".imgContainer").width();

        if (window.console) {
            console.log($("#imgCat").height());
            console.log(heightRate);
            console.log(widthRate);
            console.log(heightRate > widthRate);
        }
        if (heightRate <= widthRate) {
            $("#imgCat").height($("#imgCat").parent(".imgContainer").height());
        } else {
            $("#imgCat").width($("#imgCat").parent(".imgContainer").width());
        }
    });
</script>

how to create a logfile in php?

You could use built-in function trigger_error() to trigger user errors/warnings/notices and set_error_handler() to handle them. Inside your error handler you might want to use error_log() or file_put_contents() to store all records on files. To have a single file for every day just use something like sprintf('%s.log', date('Y-m-d')) as filename. And now you should know where to start... :)

How to destroy a DOM element with jQuery?

Is $target.remove(); what you're looking for?

https://api.jquery.com/remove/

Fixed footer in Bootstrap

You can do this by wrapping the page contents in a div with the following id styling applied:

<style>
#wrap {
   min-height: 100%;
   height: auto !important;
   height: 100%;
   margin: 0 auto -60px;
}
</style>

<div id="wrap">
    <!-- Your page content here... -->
</div>

Worked for me.

Javascript onclick hide div

HTML

<div id='hideme'><strong>Warning:</strong>These are new products<a href='#' class='close_notification' title='Click to Close'><img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="hide('hideme')" /></a

Javascript:

function hide(obj) {

    var el = document.getElementById(obj);

        el.style.display = 'none';

}

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

When I added module: 'jsr305' as an additional exclude statement, it all worked out fine for me.

 androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
exclude module: 'jsr305'

})

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

You can take a look at this. One of the examples says:

var d = new Date(dateString);

Once you have Date object you can fairly easy play with it. You can either call toLocaleDateString, toLocaleTimeString or you can test if getHours is bigger than 12 and then just calculate AM/PM time.

Java foreach loop: for (Integer i : list) { ... }

One way to do that is to use a counter:

ArrayList<Integer> list = new ArrayList<Integer>();
...
int size = list.size();
for (Integer i : list) { 
    ...
    if (--size == 0) {
        // Last item.
        ...
    }
}

Edit

Anyway, as Tom Hawtin said, it is sometimes better to use the "old" syntax when you need to get the current index information, by using a for loop or the iterator, as everything you win when using the Java5 syntax will be lost in the loop itself...

for (int i = 0; i < list.size(); i++) {
    ...

    if (i == (list.size() - 1)) {
        // Last item...
    }
}

or

for (Iterator it = list.iterator(); it.hasNext(); ) {
    ...

    if (!it.hasNext()) {
        // Last item...
    }
}

How to make the Facebook Like Box responsive?

The answer you're looking for as of June, 2013 can be found here:

https://gist.github.com/dineshcooper/2111366

It's accomplished using jQuery to rewrite the inner HTML of the parent container that holds the facebook widget.

Hope this helps!

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

This exception can occur when you try to execute HTTPS request from client on endpoint which isn't HTTPS enabled. Client will encrypt request data when server is expecting raw data.

Get driving directions using Google Maps API v2

This is what I am using,

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
Uri.parse("http://maps.google.com/maps?saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );     
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);

Mockito: List Matchers with generics

Before Java 8 (versions 7 or 6) I use the new method ArgumentMatchers.anyList:

import static org.mockito.Mockito.*;
import org.mockito.ArgumentMatchers;

verify(mock, atLeastOnce()).process(ArgumentMatchers.<Bar>anyList());

Detect a finger swipe through JavaScript on the iPhone and Android

I reworked @givanse's solution to function as a React hook. Input is some optional event listeners, output is a functional ref (needs to be functional so the hook can re-run when/if the ref changes).

Also added in vertical/horizontal swipe threshold param, so that small motions don't accidentally trigger the event listeners, but these can be set to 0 to mimic original answer more closely.

Tip: for best performance, the event listener input functions should be memoized.

function useSwipeDetector({
    // Event listeners.
    onLeftSwipe,
    onRightSwipe,
    onUpSwipe,
    onDownSwipe,

    // Threshold to detect swipe.
    verticalSwipeThreshold = 50,
    horizontalSwipeThreshold = 30,
}) {
    const [domRef, setDomRef] = useState(null);
    const xDown = useRef(null);
    const yDown = useRef(null);

    useEffect(() => {
        if (!domRef) {
            return;
        }

        function handleTouchStart(evt) {
            const [firstTouch] = evt.touches;
            xDown.current = firstTouch.clientX;
            yDown.current = firstTouch.clientY;
        };

        function handleTouchMove(evt) {
            if (!xDown.current || !yDown.current) {
                return;
            }

            const [firstTouch] = evt.touches;
            const xUp = firstTouch.clientX;
            const yUp = firstTouch.clientY;
            const xDiff = xDown.current - xUp;
            const yDiff = yDown.current - yUp;

            if (Math.abs(xDiff) > Math.abs(yDiff)) {/*most significant*/
                if (xDiff > horizontalSwipeThreshold) {
                    if (onRightSwipe) onRightSwipe();
                } else if (xDiff < -horizontalSwipeThreshold) {
                    if (onLeftSwipe) onLeftSwipe();
                }
            } else {
                if (yDiff > verticalSwipeThreshold) {
                    if (onUpSwipe) onUpSwipe();
                } else if (yDiff < -verticalSwipeThreshold) {
                    if (onDownSwipe) onDownSwipe();
                }
            }
        };

        function handleTouchEnd() {
            xDown.current = null;
            yDown.current = null;
        }

        domRef.addEventListener("touchstart", handleTouchStart, false);
        domRef.addEventListener("touchmove", handleTouchMove, false);
        domRef.addEventListener("touchend", handleTouchEnd, false);

        return () => {
            domRef.removeEventListener("touchstart", handleTouchStart);
            domRef.removeEventListener("touchmove", handleTouchMove);
            domRef.removeEventListener("touchend", handleTouchEnd);
        };
    }, [domRef, onLeftSwipe, onRightSwipe, onUpSwipe, onDownSwipe, verticalSwipeThreshold, horizontalSwipeThreshold]);

    return (ref) => setDomRef(ref);
};

Delete all Duplicate Rows except for One in MySQL?

If you want to keep the row with the lowest id value:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MIN(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

If you want the id value that is the highest:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MAX(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

The subquery in a subquery is necessary for MySQL, or you'll get a 1093 error.

Return HTML content as a string, given URL. Javascript Function

after you get the response just do call this function to append data to your body element

function createDiv(responsetext)
{
    var _body = document.getElementsByTagName('body')[0];
    var _div = document.createElement('div');
    _div.innerHTML = responsetext;
    _body.appendChild(_div);
}

@satya code modified as below

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            createDiv(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", theUrl, false);
    xmlhttp.send();    
}

Disabling radio buttons with jQuery

just use jQuery prop

 $(".radio-button").prop("disabled", false);
 $(".radio-button").prop("disabled", true); // disable

CSS @font-face not working with Firefox, but working with Chrome and IE

In my case, I sloved problem with inserting font-face style code

<style type="text/css">
@font-face { 
font-family: 'Amazone';font-style: normal; 
/*font-weight:100; -webkit-font-smoothing: antialiased; font-smooth:always;*/ 
src: local('Amazone'), url(font/Amazone.woff) format('woff');} 
</style>

direclty in header on your index.html or php page, in style tag. Works for me!

Clang vs GCC - which produces faster binaries?

The fact that Clang compiles code faster may not be as important as the speed of the resulting binary. However, here is a series of benchmarks.

Command line to remove an environment variable from the OS level configuration

You can also create a small VBScript script:

Set env = CreateObject("WScript.Shell").Environment("System")
If env(WScript.Arguments(0)) <> vbNullString Then env.Remove WScript.Arguments(0)

Then call it like %windir%\System32\cscript.exe //Nologo "script_name.vbs" FOOBAR.

The disadvantage is you need an extra script, but it does not require a reboot.

Excel - Shading entire row based on change of value

This one has puzzled me for ages. Don't like the idea of creating an extra (irrelevant) row/column just to calculate formatting. Finally came up with the following rule:

=INDIRECT("A"&ROW())<>INDIRECT("A"&(ROW()-1))

This creates the reference A2<>A1 for row 2, A3<>A2 for row 3 etc. Adjust the letter "A" to be the column you wish to compare

How can I retrieve the remote git address of a repo?

If you have the name of the remote, you will be able with git 2.7 (Q4 2015), to use the new git remote get-url command:

git remote get-url origin

(nice pendant of git remote set-url origin <newurl>)

See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf).
(Merged by Junio C Hamano -- gitster -- in commit e437cbd, 05 Oct 2015)

remote: add get-url subcommand

Expanding insteadOf is a part of ls-remote --url and there is no way to expand pushInsteadOf as well.
Add a get-url subcommand to be able to query both as well as a way to get all configured urls.

How to hide a div with jQuery?

$('#myDiv').hide();

or

$('#myDiv').slideUp();

or

$('#myDiv').fadeOut();

Python non-greedy regexes

You seek the all-powerful *?

From the docs, Greedy versus Non-Greedy

the non-greedy qualifiers *?, +?, ??, or {m,n}? [...] match as little text as possible.

Eclipse reports rendering library more recent than ADT plug-in

Change android version while rendering layout.

enter image description here

Change in API version 18 to 17 work for me.

Edit: Solution worked for Android Studio too.

Calculating width from percent to pixel then minus by pixel in LESS CSS

You can escape the calc arguments in order to prevent them from being evaluated on compilation.

Using your example, you would simply surround the arguments, like this:

calc(~'100% - 10px')

Demo : http://jsfiddle.net/c5aq20b6/


I find that I use this in one of the following three ways:

Basic Escaping

Everything inside the calc arguments is defined as a string, and is totally static until it's evaluated by the client:

LESS Input

div {
    > span {
        width: calc(~'100% - 10px');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Interpolation of Variables

You can insert a LESS variable into the string:

LESS Input

div {
    > span {
        @pad: 10px;
        width: calc(~'100% - @{pad}');
    }
}

CSS Output

div > span {
  width: calc(100% - 10px);
}

Mixing Escaped and Compiled Values

You may want to escape a percentage value, but go ahead and evaluate something on compilation:

LESS Input

@btnWidth: 40px;
div {
    > span {
        @pad: 10px;
        width: calc(~'(100% - @{pad})' - (@btnWidth * 2));
    }
}

CSS Output

div > span {
  width: calc((100% - 10px) - 80px);
}

Source: http://lesscss.org/functions/#string-functions-escape.

C# Clear Session

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want him to relogin for example) and reset all his session specific data.

What is the difference between Session.Abandon() and Session.Clear()

Clear - Removes all keys and values from the session-state collection.

Abandon - removes all the objects stored in a Session. If you do not call the Abandon method explicitly, the server removes these objects and destroys the session when the session times out. It also raises events like Session_End.

Session.Clear can be compared to removing all books from the shelf, while Session.Abandon is more like throwing away the whole shelf.

...

Generally, in most cases you need to use Session.Clear. You can use Session.Abandon if you are sure the user is going to leave your site.

So back to the differences:

  • Abandon raises Session_End request.
  • Clear removes items immediately, Abandon does not.
  • Abandon releases the SessionState object and its items so it can garbage collected.
  • Clear keeps SessionState and resources associated with it.

Session.Clear() or Session.Abandon() ?

You use Session.Clear() when you don't want to end the session but rather just clear all the keys in the session and reinitialize the session.

Session.Clear() will not cause the Session_End eventhandler in your Global.asax file to execute.

But on the other hand Session.Abandon() will remove the session altogether and will execute Session_End eventhandler.

Session.Clear() is like removing books from the bookshelf

Session.Abandon() is like throwing the bookshelf itself.

Question

I check on some sessions if not equal null in the page load. if one of them equal null i wanna to clear all the sessions and redirect to the login page?

Answer

If you want the user to login again, use Session.Abandon.

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

This code will work like charm and use the restTemple object for rest of the code.

  RestTemplate restTemplate = new RestTemplate();   
  TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) {
                return true;
            }

        };

        SSLContext sslContext = null;
        try {
            sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy)
                    .build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        restTemplate.setRequestFactory(requestFactory);
}

Renaming columns in Pandas

As documented in Working with text data:

df.columns = df.columns.str.replace('$', '')

What does this format means T00:00:00.000Z?

Please use DateTimeFormatter ISO_DATE_TIME = DateTimeFormatter.ISO_DATE_TIME; instead of DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss") or any pattern

This fixed my problem Below

java.time.format.DateTimeParseException: Text '2019-12-18T19:00:00.000Z' could not be parsed at index 10

CSS scrollbar style cross browser

Scrollbar CSS styles are an oddity invented by Microsoft developers. They are not part of the W3C standard for CSS and therefore most browsers just ignore them.

Git pull after forced update

This won't fix branches that already have the code you don't want in them (see below for how to do that), but if they had pulled some-branch and now want it to be clean (and not "ahead" of origin/some-branch) then you simply:

git checkout some-branch   # where some-branch can be replaced by any other branch
git branch base-branch -D  # where base-branch is the one with the squashed commits
git checkout -b base-branch origin/base-branch  # recreating branch with correct commits

Note: You can combine these all by putting && between them

Note2: Florian mentioned this in a comment, but who reads comments when looking for answers?

Note3: If you have contaminated branches, you can create new ones based off the new "dumb branch" and just cherry-pick commits over.

Ex:

git checkout feature-old  # some branch with the extra commits
git log                   # gives commits (write down the id of the ones you want)
git checkout base-branch  # after you have already cleaned your local copy of it as above
git checkout -b feature-new # make a new branch for your feature
git cherry-pick asdfasd   # where asdfasd is one of the commit ids you want
# repeat previous step for each commit id
git branch feature-old -D # delete the old branch

Now feature-new is your branch without the extra (possibly bad) commits!

What character represents a new line in a text area

By HTML specifications, browsers are required to canonicalize line breaks in user input to CR LF (\r\n), and I don’t think any browser gets this wrong. Reference: clause 17.13.4 Form content types in the HTML 4.01 spec.

In HTML5 drafts, the situation is more complicated, since they also deal with the processes inside a browser, not just the data that gets sent to a server-side form handler when the form is submitted. According to them (and browser practice), the textarea element value exists in three variants:

  1. the raw value as entered by the user, unnormalized; it may contain CR, LF, or CR LF pair;
  2. the internal value, called “API value”, where line breaks are normalized to LF (only);
  3. the submission value, where line breaks are normalized to CR LF pairs, as per Internet conventions.

What is the convention for word separator in Java package names?

Concatenation of words in the package name is something most developers don't do.

You can use something like.

com.stackoverflow.mypackage

Refer JLS Name Declaration

How can I trim beginning and ending double quotes from a string?

private static String removeQuotesFromStartAndEndOfString(String inputStr) {
    String result = inputStr;
    int firstQuote = inputStr.indexOf('\"');
    int lastQuote = result.lastIndexOf('\"');
    int strLength = inputStr.length();
    if (firstQuote == 0 && lastQuote == strLength - 1) {
        result = result.substring(1, strLength - 1);
    }
    return result;
}

How to remove jar file from local maven repository which was added with install:install-file?

  1. cd ~/.m2
  2. git init
  3. git commit -am "some comments"
  4. cd /path/to/your/project
  5. mvn install
  6. cd ~/.m2
  7. git reset --hard

getting the screen density programmatically in android?

If you want to retrieve the density from a Service it works like this:

WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

My situation was a little different. The solution was to strip the .pem from everything outside of the CERTIFICATE and PRIVATE KEY sections and to invert the order which they appeared. After converting from pfx to pem file, the certificate looked like this:

Bag Attributes
localKeyID: ...
issuer=...
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
Bag Attributes
more garbage...
-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----

After correcting the file, it was just:

-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----

"Initializing" variables in python?

I know you have already accepted another answer, but I think the broader issue needs to addressed - programming style that is suitable to the current language.

Yes, 'initialization' isn't needed in Python, but what you are doing isn't initialization. It is just an incomplete and erroneous imitation of initialization as practiced in other languages. The important thing about initialization in static typed languages is that you specify the nature of the variables.

In Python, as in other languages, you do need to give variables values before you use them. But giving them values at the start of the function isn't important, and even wrong if the values you give have nothing to do with values they receive later. That isn't 'initialization', it's 'reuse'.

I'll make some notes and corrections to your code:

def main():
   # doc to define the function
   # proper Python indentation
   # document significant variables, especially inputs and outputs
   # grade_1, grade_2, grade_3, average - id these
   # year - id this
   # fName, lName, ID, converted_ID 

   infile = open("studentinfo.txt", "r") 
   # you didn't 'intialize' this variable

   data = infile.read()  
   # nor this  

   fName, lName, ID, year = data.split(",")
   # this will produce an error if the file does not have the right number of strings
   # 'year' is now a string, even though you 'initialized' it as 0

   year = int(year)
   # now 'year' is an integer
   # a language that requires initialization would have raised an error
   # over this switch in type of this variable.

   # Prompt the user for three test scores
   grades = eval(input("Enter the three test scores separated by a comma: "))
   # 'eval' ouch!
   # you could have handled the input just like you did the file input.

   grade_1, grade_2, grade_3 = grades   
   # this would work only if the user gave you an 'iterable' with 3 values
   # eval() doesn't ensure that it is an iterable
   # and it does not ensure that the values are numbers. 
   # What would happen with this user input: "'one','two','three',4"?

   # Create a username 
   uName = (lName[:4] + fName[:2] + str(year)).lower()

   converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
   # earlier you 'initialized' converted_ID
   # initialization in a static typed language would have caught this typo
   # pseudo-initialization in Python does not catch typos
   ....

Is Google Play Store supported in avd emulators?

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

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

Official Source

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

Creating files in C++

use c methods FILE *fp =fopen("filename","mode"); fclose(fp); mode means a for appending r for reading ,w for writing

   / / using ofstream constructors.
      #include <iostream>
       #include <fstream>  
      std::string input="some text to write"
     std::ofstream outfile ("test.txt");

    outfile <<input << std::endl;

       outfile.close();

How do I encode/decode HTML entities in Ruby?

<% str="<h1> Test </h1>" %>

result: &lt; h1 &gt; Test &lt; /h1 &gt;

<%= CGI.unescapeHTML(str).html_safe %>

Android ImageView Fixing Image Size

In your case you need to

  1. Fix the ImageView's size. You need to use dp unit so that it will look the same in all devices.
  2. Set android:scaleType to fitXY

Below is an example:

<ImageView
    android:id="@+id/photo"
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:src="@drawable/iclauncher" 
    android:scaleType="fitXY"/>

For more information regarding ImageView scaleType please refer to the developer website.

File Upload in WebView

this is the only solution that i found that works!

WebView webview;

private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;

@Override
protected void onActivityResult(int requestCode, int resultCode,
        Intent intent) {
    if (requestCode == FILECHOOSER_RESULTCODE) {
        if (null == mUploadMessage)
            return;
        Uri result = intent == null || resultCode != RESULT_OK ? null
                : intent.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;

    }
}

// Next part 

class MyWebChromeClient extends WebChromeClient {
    // The undocumented magic method override
    // Eclipse will swear at you if you try to put @Override here
    public void openFileChooser(ValueCallback<Uri> uploadMsg) {

        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        Cv5appActivity.this.startActivityForResult(
                Intent.createChooser(i, "Image Browser"),
                FILECHOOSER_RESULTCODE);
    }
}

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

Giving graphs a subtitle in matplotlib

This is a pandas code example that implements Floris van Vugt's answer (Dec 20, 2010). He said:

>What I do is use the title() function for the subtitle and the suptitle() for the >main title (they can take different fontsize arguments). Hope that helps!

import pandas as pd
import matplotlib.pyplot as plt

d = {'series a' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
      'series b' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)

title_string = "This is the title"
subtitle_string = "This is the subtitle"

plt.figure()
df.plot(kind='bar')
plt.suptitle(title_string, y=1.05, fontsize=18)
plt.title(subtitle_string, fontsize=10)

Note: I could not comment on that answer because I'm new to stackoverflow.

How to name an object within a PowerPoint slide?

Yes. Click on the object (textbox, shape, etc.) to select the object and in the Drawing Tools | Format tab, click on Selection Pane in the Arrange group. From there, you'll see names of objects - you can double click (or press F2) on any name and rename it. By deselecting it, it becomes renamed. You can also get to this from the Home tab -> Drawing group -> Arrange drop-down -> Selection pane or by pressing ALT + F10.

A CORS POST request works from plain JavaScript, but why not with jQuery?

Cors change the request method before it's done, from POST to OPTIONS, so, your post data will not be sent. The way that worked to handle this cors issue, is performing the request with ajax, which does not support the OPTIONS method. example code:

        $.ajax({
            type: "POST",
            crossdomain: true,
            url: "http://localhost:1415/anything",
            dataType: "json",
            data: JSON.stringify({
                anydata1: "any1",
                anydata2: "any2",
            }),
            success: function (result) {
                console.log(result)
            },
            error: function (xhr, status, err) {
                console.error(xhr, status, err);
            }
        });

with this headers on c# server:

                    if (request.HttpMethod == "OPTIONS")
                    {
                          response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
                          response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                          response.AddHeader("Access-Control-Max-Age", "1728000");
                    }
                    response.AppendHeader("Access-Control-Allow-Origin", "*");

How do I get indices of N maximum values in a NumPy array?

bottleneck has a partial sort function, if the expense of sorting the entire array just to get the N largest values is too great.

I know nothing about this module; I just googled numpy partial sort.

Composer: how can I install another dependency without updating old ones?

In my case, I had a repo with:

  • requirements A,B,C,D in .json
  • but only A,B,C in the .lock

In the meantime, A,B,C had newer versions with respect when the lock was generated.

For some reason, I deleted the "vendors" and wanted to do a composer install and failed with the message:

Warning: The lock file is not up to date with the latest changes in composer.json.
You may be getting outdated dependencies. Run update to update them.
Your requirements could not be resolved to an installable set of packages.

I tried to run the solution from Seldaek issuing a composer update vendorD/libraryD but composer insisted to update more things, so .lock had too changes seen my my git tool.

The solution I used was:

  1. Delete all the vendors dir.
  2. Temporarily remove the requirement VendorD/LibraryD from the .json.
  3. run composer install.
  4. Then delete the file .json and checkout it again from the repo (equivalent to re-adding the file, but avoiding potential whitespace changes).
  5. Then run Seldaek's solution composer update vendorD/libraryD

It did install the library, but in addition, git diff showed me that in the .lock only the new things were added without editing the other ones.

(Thnx Seldaek for the pointer ;) )

What method in the String class returns only the first N characters?

You can use LINQ str.Take(n) or str.SubString(0, n), where the latter will throw an ArgumentOutOfRangeException exception for n > str.Length.

Mind that the LINQ version returns a IEnumerable<char>, so you'd have to convert the IEnumerable<char> to string: new string(s.Take(n).ToArray()).

jQuery javascript regex Replace <br> with \n

a cheap and nasty would be:

jQuery("#myDiv").html().replace("<br>", "\n").replace("<br />", "\n")

EDIT

jQuery("#myTextArea").val(
    jQuery("#myDiv").html()
        .replace(/\<br\>/g, "\n")
        .replace(/\<br \/\>/g, "\n")
);

Also created a jsfiddle if needed: http://jsfiddle.net/2D3xx/

Best way to get value from Collection by index

You can get the value from collection using for-each loop or using iterator interface. For a Collection c for (<ElementType> elem: c) System.out.println(elem); or Using Iterator Interface

 Iterator it = c.iterator(); 
        while (it.hasNext()) 
        System.out.println(it.next()); 

How to make an embedded Youtube video automatically start playing?

<iframe title='YouTube video player' class='youtube-player' type='text/html'
        width='030' height='030'
        src='http://www.youtube.com/embed/ZFo8b9DbcMM?rel=0&border=&autoplay=1'
        type='application/x-shockwave-flash'
        allowscriptaccess='always' allowfullscreen='true'
        frameborder='0'></iframe>

just insert your code after embed/

Two decimal places using printf( )

Try using a format like %d.%02d

int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);

Another approach is to type cast it to double before printing it using %f like this:

printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);

My 2 cents :)

Modify the legend of pandas bar plot

This is slightly an edge case but I think it can add some value to the other answers.

If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.

For instance the following script:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))

ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line

Will give you this figure, which is wrong: enter image description here

While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);

# do potentially more stuff here

h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)

This is what you'll get:

enter image description here

Check if table exists without using "select from"

Here is a table that is not a SELECT * FROM

SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = not exist

Got this from a database pro, here is what I was told:

select 1 from `tablename`; //avoids a function call
select * from INFORMATION_SCHEMA.tables where schema = 'db' and table = 'table' // slow. Field names not accurate
SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = does not exist

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

Most of time it happen because two mysql-connector-java-3.0.14-production-bin.jar file. One in lib folder of tomcat and another in classpath of the project.

Just try to remove mysql-connector-java-3.0.14-production-bin.jar from lib folder.

This way it is working for me.

Perfect 100% width of parent container for a Bootstrap input?

If you're using C# ASP.NET MVC's default template you may find that site.css overrides some of Bootstraps styles. If you want to use Bootstrap, as I did, having M$ override this (without your knowledge) can be a source of great frustration! Feel free to remove any of the unwanted styles...

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

How to convert milliseconds into human readable form?

I'm not able to comment first answer to your question, but there's a small mistake. You should use parseInt or Math.floor to convert floating point numbers to integer, i

var days, hours, minutes, seconds, x;
x = ms / 1000;
seconds = Math.floor(x % 60);
x /= 60;
minutes = Math.floor(x % 60);
x /= 60;
hours = Math.floor(x % 24);
x /= 24;
days = Math.floor(x);

Personally, I use CoffeeScript in my projects and my code looks like that:

getFormattedTime : (ms)->
        x = ms / 1000
        seconds = Math.floor x % 60
        x /= 60
        minutes = Math.floor x % 60
        x /= 60
        hours = Math.floor x % 24
        x /= 24
        days = Math.floor x
        formattedTime = "#{seconds}s"
        if minutes then formattedTime = "#{minutes}m " + formattedTime
        if hours then formattedTime = "#{hours}h " + formattedTime
        formattedTime 

Safest way to run BAT file from Powershell script

Assuming my-app is a subdirectory under the current directory. The $LASTEXITCODE should be there from the last command:

.\my-app\my-fle.bat

If it was from a fileshare:

\\server\my-file.bat

Java collections maintaining insertion order

Why is it necessary to maintain the order of insertion? If you use HashMap, you can get the entry by key. It does not mean it does not provide classes that do what you want.

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

Step 1. Install "Apache_OpenOffice_4.1.2" in your system Step 2. Download "unoconv" library from github or any where else.

-> C:\Program Files (x86)\OpenOffice 4\program\python.exe = Path of open office install directory

-> D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv = Path of library folder

-> D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' = path and file name of pdf

-> D:/wamp/www/doc_to_pdf/files/'.$doc_file_name = Path of your document file.

If pdf not created than last step is Go to ->Control Panel\All Control Panel Items\Administrative Tools-> services-> find "wampapache" -> right click and click on property -> click on logon tab Than check checkbox of allow service to interact with desktop

Create sample .php file and put below code and run on wamp or xampp server

$result = exec('"C:\Program Files (x86)\OpenOffice 4\program\python.exe" D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv -f pdf -o D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' D:/wamp/www/doc_to_pdf/files/'.$doc_file_name);

This code working for me in windows-8 operating system

Scripting Language vs Programming Language

Programming Language : Is compiled to machine code and run on the hardware of the underlying Operating System.

Scripting Language : Is unstructure subset of programming language. It is generally interpreted. it basically "scripts" other things to do stuff. The primary focus isn't primarily building your own apps but getting an existing app to act the way you want, e.g. JavaScript for browsers, TCL etc.,

*** But there are situation where a programming language is converted to interpreter and vice-verse like use have a C interpreter where you can 'C' Script. Scripts are generally written to control an application behaviour where as Programming Language is use to build applications. But beware that the demarcation is blurring day - by - day as an example of Python it depends on how one uses the language.

How to delete row in gridview using rowdeleting event?

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
    SqlCommand cmd = new SqlCommand("Delete From userTable (userName,age,birthPLace)");
    GridView1.DataBind();
}

Store output of subprocess.Popen call in a string

subprocess.Popen: http://docs.python.org/2/library/subprocess.html#subprocess.Popen

import subprocess

command = "ntpq -p"  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)

#Launch the shell command:
output = process.communicate()

print output[0]

In the Popen constructor, if shell is True, you should pass the command as a string rather than as a sequence. Otherwise, just split the command into a list:

command = ["ntpq", "-p"]  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)

If you need to read also the standard error, into the Popen initialization, you can set stderr to subprocess.PIPE or to subprocess.STDOUT:

import subprocess

command = "ntpq -p"  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

#Launch the shell command:
output, error = process.communicate()

Installing RubyGems in Windows

Use chocolatey in PowerShell

choco install ruby -y
refreshenv
gem install bundler

ADB not recognising Nexus 4 under Windows 7

Follow Google's instructions for this, OEM USB Drivers.

Can't install any packages in Node.js using "npm install"

The repository is not down, it looks like they've changed how they host files (I guess they have restored some old code):

Now you have to add the /package-name/ before the -

Eg:

http://registry.npmjs.org/-/npm-1.1.48.tgz
http://registry.npmjs.org/npm/-/npm-1.1.48.tgz

There are 3 ways to solve it:

  • Use a complete mirror:
  • Use a public proxy:

    --registry http://165.225.128.50:8000

  • Host a local proxy:

    https://github.com/hughsk/npm-quickfix

git clone https://github.com/hughsk/npm-quickfix.git
cd npm-quickfix
npm set registry http://localhost:8080/
node index.js

I'd personally go with number 3 and revert to npm set registry http://registry.npmjs.org/ as soon as this get resolved.

Stay tuned here for more info: https://github.com/isaacs/npm/issues/2694

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

I had the same issue. In this case imports [...] is crucial, because it won't work if you don't import NgbModalModule.

Error description says that components should be added to entryComponents array and it is obvious, but make sure you have added this one in the first place:

imports: [
    ...
    NgbModalModule,
    ...
  ],

Java 8 - Difference between Optional.flatMap and Optional.map

  • Optional.map():

Takes every element and if the value exists, it is passed to the function:

Optional<T> optionalValue = ...;
Optional<Boolean> added = optionalValue.map(results::add);

Now added has one of three values: true or false wrapped into an Optional , if optionalValue was present, or an empty Optional otherwise.

If you don't need to process the result you can simply use ifPresent(), it doesn't have return value:

optionalValue.ifPresent(results::add); 
  • Optional.flatMap():

Works similar to the same method of streams. Flattens out the stream of streams. With the difference that if the value is presented it is applied to function. Otherwise, an empty optional is returned.

You can use it for composing optional value functions calls.

Suppose we have methods:

public static Optional<Double> inverse(Double x) {
    return x == 0 ? Optional.empty() : Optional.of(1 / x);
}

public static Optional<Double> squareRoot(Double x) {
    return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
}

Then you can compute the square root of the inverse, like:

Optional<Double> result = inverse(-4.0).flatMap(MyMath::squareRoot);

or, if you prefer:

Optional<Double> result = Optional.of(-4.0).flatMap(MyMath::inverse).flatMap(MyMath::squareRoot);

If either the inverse() or the squareRoot() returns Optional.empty(), the result is empty.

how to use json file in html code

use jQuery's $.getJSON

$.getJSON('mydata.json', function(data) {
    //do stuff with your data here
});

How to code a BAT file to always run as admin mode?

convert your batch file into .exe with this tool: http://www.battoexeconverter.com/ then you can run it as administrator

How to check if input file is empty in jQuery

Just check the length of files property, which is a FileList object contained on the input element

if( document.getElementById("videoUploadFile").files.length == 0 ){
    console.log("no files selected");
}

How to generate a git patch for a specific commit?

This command (as suggested already by @Naftuli Tzvi Kay):

git format-patch -1 HEAD

Replace HEAD with specific hash or range.

will generate the patch file for the latest commit formatted to resemble UNIX mailbox format.

-<n> - Prepare patches from the topmost commits.

Then you can re-apply the patch file in a mailbox format by:

git am -3k 001*.patch

See: man git-format-patch.

How to draw a filled circle in Java?

/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
    g.setColor(Color.RED);
    g.fillOval(50,50,20,20);
}

g.fillOval(x-axis,y-axis,width,height);

How to make the corners of a button round?

Create an XML file like below one. Set it as background for the button. Change the radius attribute to your wish, if you need more curve for the button.

button_background.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/primary" />
    <corners android:radius="5dp" />
</shape>

Set background to your button:

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_background"/>

Ruby on Rails: Clear a cached page

This line in development.rb ensures that caching is not happening.

config.action_controller.perform_caching             = false

You can clear the Rails cache with

Rails.cache.clear

That said - I am not convinced this is a caching issue. Are you making changes to the page and not seeing them reflected? You aren't perhaps looking at the live version of that page? I have done that once (blush).

Update:

You can call that command from in the console. Are you sure you are running the application in development?

The only alternative is that the page that you are trying to render isn't the page that is being rendered.

If you watch the server output you should be able to see the render command when the page is rendered similar to this:

Rendered shared_partials/_latest_featured_video (31.9ms)
Rendered shared_partials/_s_invite_friends (2.9ms)
Rendered layouts/_sidebar (2002.1ms)
Rendered layouts/_footer (2.8ms)
Rendered layouts/_busy_indicator (0.6ms)

Counting null and non-null values in a single query

SELECT
    ALL_VALUES
    ,COUNT(ALL_VALUES)
FROM(
        SELECT 
        NVL2(A,'NOT NULL','NULL') AS ALL_VALUES 
        ,NVL(A,0)
        FROM US
)
GROUP BY ALL_VALUES

Set new id with jQuery

What happens when you set all of the attributes in one attr() command like so

$(this).attr({
               id : this.id + '_' + new_id,
               name: this.name + '_' + new_id,
               value: 'test' 
             });

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

In my case I solved the problem editing [tomcat]/Catalina/localhost/[mywebapp_name].xml instead of META-INF/context.xml.

Using setTimeout to delay timing of jQuery actions

You can also use jQuery's delay() method instead of setTimeout(). It'll give you much more readable code. Here's an example from the docs:

$( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );

The only limitation (that I'm aware of) is that it doesn't give you a way to clear the timeout. If you need to do that then you're better off sticking with all the nested callbacks that setTimeout thrusts upon you.

Formatting struct timespec

You can pass the tv_sec parameter to some of the formatting function. Have a look at gmtime, localtime(). Then look at snprintf.

Change MySQL root password in phpMyAdmin

I had to do 2 steps:

  • follow Tiep Phan solution ... edit config.inc.php file ...

  • follow Mahmoud Zalt solution ... change password within phpmyadmin

WordPress - Check if user is logged in

get_current_user_id() will return the current user id (an integer), or will return 0 if the user is not logged in.

if (get_current_user_id()) {
   // display navbar here
}

More details here get_current_user_id().

Insertion sort vs Bubble Sort Algorithms

insertion sort:

1.In the insertion sort swapping is not required.

2.the time complexity of insertion sort is O(n)for best case and O(n^2) worst case.

3.less complex as compared to bubble sort.

4.example: insert books in library, arrange cards.

bubble sort: 1.Swapping required in bubble sort.

2.the time complexity of bubble sort is O(n)for best case and O(n^2) worst case.

3.more complex as compared to insertion sort.

Typing the Enter/Return key using Python and Selenium

For Ruby:

driver.find_element(:id, "XYZ").send_keys:return

Checking if a string is empty or null in Java

You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.

Example:

System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true

Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str).

Example:

System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true

What is the use of the JavaScript 'bind' method?

From the MDN docs on Function.prototype.bind() :

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

So, what does that mean?!

Well, let's take a function that looks like this :

var logProp = function(prop) {
    console.log(this[prop]);
};

Now, let's take an object that looks like this :

var Obj = {
    x : 5,
    y : 10
};

We can bind our function to our object like this :

Obj.log = logProp.bind(Obj);

Now, we can run Obj.log anywhere in our code :

Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10

This works, because we bound the value of this to our object Obj.


Where it really gets interesting, is when you not only bind a value for this, but also for its argument prop :

Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');

We can now do this :

Obj.logX(); // Output : 5
Obj.logY(); // Output : 10

Unlike with Obj.log, we do not have to pass x or y, because we passed those values when we did our binding.

Changing background color of text box input not working when empty

Don't add styles to value of input so use like

function checkFilled() {
    var inputElem = document.getElementById("subEmail");
    if (inputElem.value == "") {
        inputElem.style.backgroundColor = "yellow";
                }
        }

How do I remove the space between inline/inline-block elements?

Add display: flex; to the parent element. Here is the solution with a prefix:

Simplified version

_x000D_
_x000D_
p {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
span {_x000D_
  width: 100px;_x000D_
  background: tomato;_x000D_
  font-size: 30px;_x000D_
  color: white;_x000D_
  text-align: center;_x000D_
}
_x000D_
<p>_x000D_
  <span> Foo </span>_x000D_
  <span> Bar </span>_x000D_
</p>
_x000D_
_x000D_
_x000D_


Fix with prefix

_x000D_
_x000D_
p {_x000D_
  display: -webkit-box;_x000D_
  display: -webkit-flex;_x000D_
  display: -ms-flexbox;_x000D_
  display: flex;_x000D_
}_x000D_
span {_x000D_
  float: left;_x000D_
  display: inline-block;_x000D_
  width: 100px;_x000D_
  background: blue;_x000D_
  font-size: 30px;_x000D_
  color: white;_x000D_
  text-align: center;_x000D_
}
_x000D_
<p>_x000D_
  <span> Foo </span>_x000D_
  <span> Bar </span>_x000D_
</p>
_x000D_
_x000D_
_x000D_

How to check if a string is numeric?

If you are allowed to use third party libraries, suggest the following.

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html

NumberUtils.isDigits(str:String):boolean
NumberUtils.isNumber(str:String):boolean

JOptionPane Input to int

This because the input that the user inserts into the JOptionPane is a String and it is stored and returned as a String.

Java cannot convert between strings and number by itself, you have to use specific functions, just use:

int ans = Integer.parseInt(JOptionPane.showInputDialog(...))

Dynamically load JS inside JS

To author my plugin I needed to load external scripts and styles inside a JS file, all of which were predefined. To achieve this, I did the following:

    this.loadRequiredFiles = function (callback) {
        var scripts = ['xx.js', 'yy.js'];
        var styles = ['zz.css'];
        var filesloaded = 0;
        var filestoload = scripts.length + styles.length;
        for (var i = 0; i < scripts.length; i++) {
            log('Loading script ' + scripts[i]);
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = scripts[i];
            script.onload = function () {
                log('Loaded script');
                log(this);
                filesloaded++;  // (This means increment, i.e. add one)
                finishLoad();
            };
            document.head.appendChild(script);
        }
        for (var i = 0; i < styles.length; i++) {
            log('Loading style ' + styles[i]);
            var style = document.createElement('link');
            style.rel = 'stylesheet';
            style.href = styles[i];
            style.type = 'text/css';
            style.onload = function () {
                log('Loaded style');
                log(this);
                filesloaded++;
                finishLoad();
            };
            document.head.appendChild(style);
        }
        function finishLoad() {
            if (filesloaded === filestoload) {
                callback();
            }
        }
    };

More of the script in context:

function myPlugin() {

    var opts = {
        verbose: false
    };                          ///< The options required to run this function
    var self = this;            ///< An alias to 'this' in case we're in jQuery                         ///< Constants required for this function to work

    this.getOptions = function() {
        return opts;
    };

    this.setOptions = function(options) {
        for (var x in options) {
            opts[x] = options[x];
        }
    };

    /**
     * @brief Load the required files for this plugin
     * @param {Function} callback A callback function to run when all files have been loaded
     */
    this.loadRequiredFiles = function (callback) {
        var scripts = ['xx.js', 'yy.js'];
        var styles = ['zz.css'];
        var filesloaded = 0;
        var filestoload = scripts.length + styles.length;
        for (var i = 0; i < scripts.length; i++) {
            log('Loading script ' + scripts[i]);
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = scripts[i];
            script.onload = function () {
                log('Loaded script');
                log(this);
                filesloaded++;
                finishLoad();
            };
            document.head.appendChild(script);
        }
        for (var i = 0; i < styles.length; i++) {
            log('Loading style ' + styles[i]);
            var style = document.createElement('link');
            style.rel = 'stylesheet';
            style.href = styles[i];
            style.type = 'text/css';
            style.onload = function () {
                log('Loaded style');
                log(this);
                filesloaded++;
                finishLoad();
            };
            document.head.appendChild(style);
        }
        function finishLoad() {
            if (filesloaded === filestoload) {
                callback();
            }
        }
    };

    /**
     * @brief Enable user-controlled logging within this function
     * @param {String} msg The message to log
     * @param {Boolean} force True to log message even if user has set logging to false
     */
    function log(msg, force) {
        if (opts.verbose || force) {
            console.log(msg);
        }
    }

    /**
     * @brief Initialise this function
     */
    this.init = function() {
        self.loadRequiredFiles(self.afterLoadRequiredFiles);
    };

    this.afterLoadRequiredFiles = function () {
        // Do stuff
    };

}

BigDecimal equals() versus compareTo()

The answer is in the JavaDoc of the equals() method:

Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

In other words: equals() checks if the BigDecimal objects are exactly the same in every aspect. compareTo() "only" compares their numeric value.

As to why equals() behaves this way, this has been answered in this SO question.

How to restore PostgreSQL dump file into Postgres databases?

By using pg_restore command you can restore postgres database

First open terminal type

sudo su postgres

Create new database

createdb [database name] -O [owner]

createdb test_db [-O openerp]

pg_restore -d [Database Name] [path of dump file]

pg_restore -d test_db /home/sagar/Download/sample_dbump

Wait for completion of database restoring.

Remember that dump file should have read, write, execute access, so for that you can apply chmod command

Send File Attachment from Form Using phpMailer and PHP

Use this code for sending attachment with upload file option using html form in phpmailer

 <form method="post" action="" enctype="multipart/form-data">


                    <input type="text" name="name" placeholder="Your Name *">
                    <input type="email" name="email" placeholder="Email *">
                    <textarea name="msg" placeholder="Your Message"></textarea>


                    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
                    <input type="file" name="userfile"  />


                <input name="contact" type="submit" value="Submit Enquiry" />
   </form>


    <?php




        if(isset($_POST["contact"]))
        {

            /////File Upload

            // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
            // of $_FILES.

            $uploaddir = 'uploads/';
            $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

            echo '<pre>';
            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
                echo "File is valid, and was successfully uploaded.\n";
            } else {
                echo "Possible invalid file upload !\n";
            }

            echo 'Here is some more debugging info:';
            print_r($_FILES);

            print "</pre>";


            ////// Email


            require_once("class.phpmailer.php");
            require_once("class.smtp.php");



            $mail_body = array($_POST['name'], $_POST['email'] , $_POST['msg']);
            $new_body = "Name: " . $mail_body[0] . ", Email " . $mail_body[1] . " Description: " . $mail_body[2];



            $d=strtotime("today"); 

            $subj = 'New enquiry '. date("Y-m-d h:i:sa", $d);

            $mail = new PHPMailer(); // create a new object


            //$mail->IsSMTP(); // enable SMTP
            $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only ,false = Disable 
            $mail->Host = "mail.yourhost.com";
            $mail->Port = '465';
            $mail->SMTPAuth = true; // enable 
            $mail->SMTPSecure = true;
            $mail->IsHTML(true);
            $mail->Username = "[email protected]"; //[email protected]
            $mail->Password = "password";
            $mail->SetFrom("[email protected]", "Your Website Name");
            $mail->Subject = $subj;
            $mail->Body    = $new_body;

            $mail->AddAttachment($uploadfile);

            $mail->AltBody = 'Upload';
            $mail->AddAddress("[email protected]");
             if(!$mail->Send())
                {
                echo "Mailer Error: " . $mail->ErrorInfo;
                }
                else
                {

                echo '<p>       Success              </p> ';

                }

        }



?>

Use this link for reference.

How do I count the number of occurrences of a char in a String?

I see a lot of tricks and such being used. Now I'm not against beautiful tricks but personally I like to simply call the methods that are meant to do the work, so I've created yet another answer.

Note that if performance is any issue, use Jon Skeet's answer instead. This one is a bit more generalized and therefore slightly more readable in my opinion (and of course, reusable for strings and patterns).

public static int countOccurances(char c, String input) {
    return countOccurancesOfPattern(Pattern.quote(Character.toString(c)), input);
}

public static int countOccurances(String s, String input) {
    return countOccurancesOfPattern(Pattern.quote(s), input);
}

public static int countOccurancesOfPattern(String pattern, String input) {
    Matcher m = Pattern.compile(pattern).matcher(input);
    int count = 0;
    while (m.find()) {
        count++;
    }
    return count;
}

WPF Data Binding and Validation Rules Best Practices

You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF). It shows how to use validation in WPF and how to control the Save button when validation errors exists.