Programs & Examples On #Fontmetrics

Measuring text height to be drawn on Canvas ( Android )

You can simply get the text size for a Paint object using getTextSize() method. For example:

Paint mTextPaint = new Paint (Paint.ANTI_ALIAS_FLAG);
//use densityMultiplier to take into account different pixel densities
final float densityMultiplier = getContext().getResources()
            .getDisplayMetrics().density;  
mTextPaint.setTextSize(24.0f*densityMultiplier);

//...

float size = mTextPaint.getTextSize();

How to access custom attributes from event object in React?

<div className='btn' onClick={(e) =>
     console.log(e.currentTarget.attributes['tag'].value)}
     tag='bold'>
    <i className='fa fa-bold' />
</div>

so e.currentTarget.attributes['tag'].value works for me

HTML5 Video Autoplay not working correctly

Working solution October 2018, for videos including audio channel

 $(document).ready(function() {
     $('video').prop('muted',true).play()
 });

Have a look at another of mine, more in-depth answer: https://stackoverflow.com/a/57723549/3049675

How to search for rows containing a substring?

Well, you can always try WHERE textcolumn LIKE "%SUBSTRING%" - but this is guaranteed to be pretty slow, as your query can't do an index match because you are looking for characters on the left side.

It depends on the field type - a textarea usually won't be saved as VARCHAR, but rather as (a kind of) TEXT field, so you can use the MATCH AGAINST operator.

To get the columns that don't match, simply put a NOT in front of the like: WHERE textcolumn NOT LIKE "%SUBSTRING%".

Whether the search is case-sensitive or not depends on how you stock the data, especially what COLLATION you use. By default, the search will be case-insensitive.

Updated answer to reflect question update:

I say that doing a WHERE field LIKE "%value%" is slower than WHERE field LIKE "value%" if the column field has an index, but this is still considerably faster than getting all values and having your application filter. Both scenario's:

1/ If you do SELECT field FROM table WHERE field LIKE "%value%", MySQL will scan the entire table, and only send the fields containing "value".

2/ If you do SELECT field FROM table and then have your application (in your case PHP) filter only the rows with "value" in it, MySQL will also scan the entire table, but send all the fields to PHP, which then has to do additional work. This is much slower than case #1.

Solution: Please do use the WHERE clause, and use EXPLAIN to see the performance.

How do you hide the Address bar in Google Chrome for Chrome Apps?

Even though the question is about gaining some space removing the address bar, you can also gain some space by toggling the bookmark bar on and off, using Ctrl + Shift + B, or ? Cmd + Shift + B, in Mac OS.

getting file size in javascript

Try this one.

_x000D_
_x000D_
function showFileSize() {_x000D_
  let file = document.getElementById("file").files[0];_x000D_
  if(file) {_x000D_
    alert(file.size + " in bytes"); _x000D_
  } else { _x000D_
    alert("select a file... duh"); _x000D_
  }_x000D_
}
_x000D_
<input type="file" id="file"/>_x000D_
<button onclick="showFileSize()">show file size</button>
_x000D_
_x000D_
_x000D_

Android Studio - Auto complete and other features not working

Most of the times i have seen that the problem is that Power Save Mode is enabled, to disable go to Current inspection profile (lower right corner in Android Studio).

enter image description here

Python - use list as function parameters

This has already been answered perfectly, but since I just came to this page and did not understand immediately I am just going to add a simple but complete example.

def some_func(a_char, a_float, a_something):
    print a_char

params = ['a', 3.4, None]
some_func(*params)

>> a

ScrollTo function in AngularJS

I used andrew joslin's answer, which works great but triggered an angular route change, which created a jumpy looking scroll for me. If you want to avoid triggering a route change,

myApp.directive('scrollOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, $elm, attrs) {
      var idToScroll = attrs.href;
      $elm.on('click', function(event) {
        event.preventDefault();
        var $target;
        if (idToScroll) {
          $target = $(idToScroll);
        } else {
          $target = $elm;
        }
        $("body").animate({scrollTop: $target.offset().top}, "slow");
        return false;
      });
    }
  }
});

Excel VBA, How to select rows based on data in a column?

Yes using Option Explicit is a good habit. Using .Select however is not :) it reduces the speed of the code. Also fully justify sheet names else the code will always run for the Activesheet which might not be what you actually wanted.

Is this what you are trying?

Option Explicit

Sub Sample()
    Dim lastRow As Long, i As Long
    Dim CopyRange As Range

    '~~> Change Sheet1 to relevant sheet name
    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 2 To lastRow
            If Len(Trim(.Range("A" & i).Value)) <> 0 Then
                If CopyRange Is Nothing Then
                    Set CopyRange = .Rows(i)
                Else
                    Set CopyRange = Union(CopyRange, .Rows(i))
                End If
            Else
                Exit For
            End If
        Next

        If Not CopyRange Is Nothing Then
            '~~> Change Sheet2 to relevant sheet name
            CopyRange.Copy Sheets("Sheet2").Rows(1)
        End If
    End With
End Sub

NOTE

If if you have data from Row 2 till Row 10 and row 11 is blank and then you have data again from Row 12 then the above code will only copy data from Row 2 till Row 10

If you want to copy all rows which have data then use this code.

Option Explicit

Sub Sample()
    Dim lastRow As Long, i As Long
    Dim CopyRange As Range

    '~~> Change Sheet1 to relevant sheet name
    With Sheets("Sheet1")
        lastRow = .Range("A" & .Rows.Count).End(xlUp).Row

        For i = 2 To lastRow
            If Len(Trim(.Range("A" & i).Value)) <> 0 Then
                If CopyRange Is Nothing Then
                    Set CopyRange = .Rows(i)
                Else
                    Set CopyRange = Union(CopyRange, .Rows(i))
                End If
            End If
        Next

        If Not CopyRange Is Nothing Then
            '~~> Change Sheet2 to relevant sheet name
            CopyRange.Copy Sheets("Sheet2").Rows(1)
        End If
    End With
End Sub

Hope this is what you wanted?

Sid

Why use String.Format?

I can see a number of reasons:

Readability

string s = string.Format("Hey, {0} it is the {1}st day of {2}.  I feel {3}!", _name, _day, _month, _feeling);

vs:

string s = "Hey," + _name + " it is the " + _day + "st day of " + _month + ".  I feel " + feeling + "!";

Format Specifiers (and this includes the fact you can write custom formatters)

string s = string.Format("Invoice number: {0:0000}", _invoiceNum);

vs:

string s = "Invoice Number = " + ("0000" + _invoiceNum).Substr(..... /*can't even be bothered to type it*/)

String Template Persistence

What if I want to store string templates in the database? With string formatting:

_id         _translation
  1         Welcome {0} to {1}.  Today is {2}.
  2         You have {0} products in your basket.
  3         Thank-you for your order.  Your {0} will arrive in {1} working days.

vs:

_id         _translation
  1         Welcome
  2         to
  3         .  Today is
  4         . 
  5         You have
  6         products in your basket.
  7         Someone
  8         just shoot
  9         the developer.

Add views in UIStackView programmatically

UIStackView uses constraints internally to position its arranged subviews. Exactly what constraints are created depends on how the stack view itself is configured. By default, a stack view will create constraints that lay out its arranged subviews in a horizontal line, pinning the leading and trailing views to its own leading and trailing edges. So your code would produce a layout that looks like this:

|[view1][view2]|

The space that is allocated to each subview is determined by a number of factors including the subview's intrinsic content size and it's compression resistance and content hugging priorities. By default, UIView instances don't define an intrinsic content size. This is something that is generally provided by a subclass, such as UILabel or UIButton.

Since the content compression resistance and content hugging priorities of two new UIView instances will be the same, and neither view provides an intrinsic content size, the layout engine must make its best guess as to what size should be allocated to each view. In your case, it is assigning the first view 100% of the available space, and nothing to the second view.

If you modify your code to use UILabel instances instead, you will get better results:

UILabel *label1 = [UILabel new];
label1.text = @"Label 1";
label1.backgroundColor = [UIColor blueColor];

UILabel *label2 = [UILabel new];
label2.text = @"Label 2";
label2.backgroundColor = [UIColor greenColor];

[self.stack1 addArrangedSubview:label1];
[self.stack1 addArrangedSubview:label2];

Note that it is not necessary to explictly create any constraints yourself. This is the main benefit of using UIStackView - it hides the (often ugly) details of constraint management from the developer.

How to convert an iterator to a stream?

Great suggestion! Here's my reusable take on it:

public class StreamUtils {

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
        return asStream(sourceIterator, false);
    }

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator, boolean parallel) {
        Iterable<T> iterable = () -> sourceIterator;
        return StreamSupport.stream(iterable.spliterator(), parallel);
    }
}

And usage (make sure to statically import asStream):

List<String> aPrefixedStrings = asStream(sourceIterator)
                .filter(t -> t.startsWith("A"))
                .collect(toList());

Difference between pre-increment and post-increment in a loop?

Since you ask about the difference in a loop, i guess you mean

for(int i=0; i<10; i++) 
    ...;

In that case, you have no difference in most languages: The loop behaves the same regardless of whether you write i++ and ++i. In C++, you can write your own versions of the ++ operators, and you can define separate meanings for them, if the i is of a user defined type (your own class, for example).

The reason why it doesn't matter above is because you don't use the value of i++. Another thing is when you do

for(int i=0, a = 0; i<10; a = i++) 
    ...;

Now, there is a difference, because as others point out, i++ means increment, but evaluate to the previous value, but ++i means increment, but evaluate to i (thus it would evaluate to the new value). In the above case, a is assigned the previous value of i, while i is incremented.

How can I see the raw SQL queries Django is running?

The following returns the query as valid SQL, based on https://code.djangoproject.com/ticket/17741:

def str_query(qs):
    """
    qs.query returns something that isn't valid SQL, this returns the actual
    valid SQL that's executed: https://code.djangoproject.com/ticket/17741
    """
    cursor = connections[qs.db].cursor()
    query, params = qs.query.sql_with_params()
    cursor.execute('EXPLAIN ' + query, params)
    res = str(cursor.db.ops.last_executed_query(cursor, query, params))
    assert res.startswith('EXPLAIN ')
    return res[len('EXPLAIN '):]

How to display Wordpress search results?

Check whether your template in theme folder contains search.php and searchform.php or not.

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

Have a look at the GROUP_CONCAT project on Github, I think I does exactly what you are searching for:

This project contains a set of SQLCLR User-defined Aggregate functions (SQLCLR UDAs) that collectively offer similar functionality to the MySQL GROUP_CONCAT function. There are multiple functions to ensure the best performance based on the functionality required...

Install a Windows service using a Windows command prompt?

If the directory's name has a space like c:\program files\abc 123, then you must use double quotes around the path.

installutil.exe "c:\program files\abc 123\myservice.exe"

Install windows service from command prompt

It makes things much easier if you set up a bat file like following,

e.g. To install a service, create a "myserviceinstaller.bat" and "Run as Administrator"

@echo off
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
installutil.exe "C:\Services\myservice.exe"

if ERRORLEVEL 1 goto error
exit
:error
echo There was a problem
pause

to uninstall service,

Just add a -u to the installutil command.

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe -u "C:\Services\myservice.exe"

Encoding as Base64 in Java

On Android, use the static methods of the android.util.Base64 utility class. The referenced documentation says that the Base64 class was added in API level 8 (Android 2.2 (Froyo)).

import android.util.Base64;

byte[] encodedBytes = Base64.encode("Test".getBytes());
Log.d("tag", "encodedBytes " + new String(encodedBytes));

byte[] decodedBytes = Base64.decode(encodedBytes);
Log.d("tag", "decodedBytes " + new String(decodedBytes));

MySQL: Get column name or alias from query

You can also do this to just get the field titles:

table = cursor.description
check = 0
for fields in table:
    for name in fields:
        if check < 1:
            print(name),
        check +=1
    check =0

Constants in Objective-C

I am generally using the way posted by Barry Wark and Rahul Gupta.

Although, I do not like repeating the same words in both .h and .m file. Note, that in the following example the line is almost identical in both files:

// file.h
extern NSString* const MyConst;

//file.m
NSString* const MyConst = @"Lorem ipsum";

Therefore, what I like to do is to use some C preprocessor machinery. Let me explain through the example.

I have a header file which defines the macro STR_CONST(name, value):

// StringConsts.h
#ifdef SYNTHESIZE_CONSTS
# define STR_CONST(name, value) NSString* const name = @ value
#else
# define STR_CONST(name, value) extern NSString* const name
#endif

The in my .h/.m pair where I want to define the constant I do the following:

// myfile.h
#import <StringConsts.h>

STR_CONST(MyConst, "Lorem Ipsum");
STR_CONST(MyOtherConst, "Hello world");

// myfile.m
#define SYNTHESIZE_CONSTS
#import "myfile.h"

et voila, I have all the information about the constants in .h file only.

How to combine two byte arrays

You're just trying to concatenate the two byte arrays?

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

for (int i = 0; i < combined.length; ++i)
{
    combined[i] = i < one.length ? one[i] : two[i - one.length];
}

Or you could use System.arraycopy:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

System.arraycopy(one,0,combined,0         ,one.length);
System.arraycopy(two,0,combined,one.length,two.length);

Or you could just use a List to do the work:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();

List<Byte> list = new ArrayList<Byte>(Arrays.<Byte>asList(one));
list.addAll(Arrays.<Byte>asList(two));

byte[] combined = list.toArray(new byte[list.size()]);

Or you could simply use ByteBuffer with the advantage of adding many arrays.

byte[] allByteArray = new byte[one.length + two.length + three.length];

ByteBuffer buff = ByteBuffer.wrap(allByteArray);
buff.put(one);
buff.put(two);
buff.put(three);

byte[] combined = buff.array();

What is the difference between const and readonly in C#?

Another gotcha.

Since const really only works with basic data types, if you want to work with a class, you may feel "forced" to use ReadOnly. However, beware of the trap! ReadOnly means that you can not replace the object with another object (you can't make it refer to another object). But any process that has a reference to the object is free to modify the values inside the object!

So don't be confused into thinking that ReadOnly implies a user can't change things. There is no simple syntax in C# to prevent an instantiation of a class from having its internal values changed (as far as I know).

How to get setuptools and easy_install?

For Amazon Linux AMI

yum install -y python-setuptools 

How to printf a 64-bit integer as hex?

Edit: Use printf("val = 0x%" PRIx64 "\n", val); instead.

Try printf("val = 0x%llx\n", val);. See the printf manpage:

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t is not always a unsigned long long: PRIx64 see also this stackoverflow answer

How to stop Python closing immediately when executed in Microsoft Windows

I think I am too late to answer this question but anyways here goes nothing.

I have run in to the same problem before and I think there are two alternative solutions you can choose from.

  1. using sleep(_sometime)

from time import * sleep(10)

  1. using a prompt message (note that I am using python 2.7)

exit_now = raw_input("Do you like to exit now (Y)es (N)o ? ")'

if exit_now.lower() = 'n'

//more processing here

Alternatively you can use a hybrid of those two methods as well where you can prompt for a message and use sleep(sometime) to delay the window closing as well. choice is yours.

please note the above are just ideas and if you want to use any of those in practice you might have to think about your application logic a bit.

Is there possibility of sum of ArrayList without looping

Then write it yourself:

public int sum(List<Integer> list) {
     int sum = 0; 

     for (int i : list)
         sum = sum + i;

     return sum;
}

Launch a shell command with in a python script, wait for the termination and return to the script

The os.exec*() functions replace the current programm with the new one. When this programm ends so does your process. You probably want os.system().

Expand a div to fill the remaining width

Im not sure if this is the answer you are expecting but, why don't you set the width of Tree to 'auto' and width of 'View' to 100% ?

NodeJS / Express: what is "app.use"?

app.use() handles all the middleware functions.
What is middleware?
Middlewares are the functions which work like a door between two all the routes.

For instance:

app.use((req, res, next) => {
    console.log("middleware ran");
    next();
});

app.get("/", (req, res) => {
    console.log("Home route");
});

When you visit / route in your console the two message will be printed. The first message will be from middleware function. If there is no next() function passed then only middleware function runs and other routes are blocked.

How to get distinct values for non-key column fields in Laravel?

In Eloquent you can also query like this:

$users = User::select('name')->distinct()->get();

How to get height of <div> in px dimension

Use height():

var result = $("#myDiv").height();
alert(result);

This will give you the unit-less computed height in pixels. "px" will be stripped from the result. I.e. if the height is 400px, the result will be 400, but the result will be in pixels.

If you want to do it without jQuery, you can use plain JavaScript:

var result = document.getElementById("myDiv").offsetHeight;

Delayed function calls

public static class DelayedDelegate
{

    static Timer runDelegates;
    static Dictionary<MethodInvoker, DateTime> delayedDelegates = new Dictionary<MethodInvoker, DateTime>();

    static DelayedDelegate()
    {

        runDelegates = new Timer();
        runDelegates.Interval = 250;
        runDelegates.Tick += RunDelegates;
        runDelegates.Enabled = true;

    }

    public static void Add(MethodInvoker method, int delay)
    {

        delayedDelegates.Add(method, DateTime.Now + TimeSpan.FromSeconds(delay));

    }

    static void RunDelegates(object sender, EventArgs e)
    {

        List<MethodInvoker> removeDelegates = new List<MethodInvoker>();

        foreach (MethodInvoker method in delayedDelegates.Keys)
        {

            if (DateTime.Now >= delayedDelegates[method])
            {
                method();
                removeDelegates.Add(method);
            }

        }

        foreach (MethodInvoker method in removeDelegates)
        {

            delayedDelegates.Remove(method);

        }


    }

}

Usage:

DelayedDelegate.Add(MyMethod,5);

void MyMethod()
{
     MessageBox.Show("5 Seconds Later!");
}

Posting raw image data as multipart/form-data in curl

As of PHP 5.6 @$filePath will not work in CURLOPT_POSTFIELDS without CURLOPT_SAFE_UPLOAD being set and it is completely removed in PHP 7. You will need to use a CurlFile object, RFC here.

$fields = [
    'name' => new \CurlFile($filePath, 'image/png', 'filename.png')
];
curl_setopt($resource, CURLOPT_POSTFIELDS, $fields);

Fatal error: "No Target Architecture" in Visual Studio

Use #include <windows.h> instead of #include <windef.h>.

From the windows.h wikipedia page:

There are a number of child header files that are automatically included with windows.h. Many of these files cannot simply be included by themselves (they are not self-contained), because of dependencies.

windef.h is one of the files automatically included with windows.h.

How do I use the includes method in lodash to check if an object is in the collection?

The includes (formerly called contains and include) method compares objects by reference (or more precisely, with ===). Because the two object literals of {"b": 2} in your example represent different instances, they are not equal. Notice:

({"b": 2} === {"b": 2})
> false

However, this will work because there is only one instance of {"b": 2}:

var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true

On the other hand, the where(deprecated in v4) and find methods compare objects by their properties, so they don't require reference equality. As an alternative to includes, you might want to try some (also aliased as any):

_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true

Parse json string to find and element (key / value)

Use a JSON parser, like JSON.NET

string json = "{ \"Atlantic/Canary\": \"GMT Standard Time\", \"Europe/Lisbon\": \"GMT Standard Time\", \"Antarctica/Mawson\": \"West Asia Standard Time\", \"Etc/GMT+3\": \"SA Eastern Standard Time\", \"Etc/GMT+2\": \"UTC-02\", \"Etc/GMT+1\": \"Cape Verde Standard Time\", \"Etc/GMT+7\": \"US Mountain Standard Time\", \"Etc/GMT+6\": \"Central America Standard Time\", \"Etc/GMT+5\": \"SA Pacific Standard Time\", \"Etc/GMT+4\": \"SA Western Standard Time\", \"Pacific/Wallis\": \"UTC+12\", \"Europe/Skopje\": \"Central European Standard Time\", \"America/Coral_Harbour\": \"SA Pacific Standard Time\", \"Asia/Dhaka\": \"Bangladesh Standard Time\", \"America/St_Lucia\": \"SA Western Standard Time\", \"Asia/Kashgar\": \"China Standard Time\", \"America/Phoenix\": \"US Mountain Standard Time\", \"Asia/Kuwait\": \"Arab Standard Time\" }";
var data = (JObject)JsonConvert.DeserializeObject(json);
string timeZone = data["Atlantic/Canary"].Value<string>();

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

It might be.. you have to identify it is tablet or phone by programmatically... First check device is phone or tablet

Determine if the device is a smartphone or tablet?

Tablet or Phone - Android

Then......

if(isTablet)
{
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);      
}else
{
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

Points to remember when extending SQLiteOpenHelper

  1. super(context, DBName, null, DBversion); - This should be invoked first line of constructor
  2. override onCreate and onUpgrade (if needed)
  3. onCreate will be invoked only when getWritableDatabase() or getReadableDatabase() is executed. And this will only invoked once when a DBName specified in the first step is not available. You can add create table query on onCreate method
  4. Whenever you want to add new table just change DBversion and do the queries in onUpgrade table or simply uninstall then install the app.

Behaviour of increment and decrement operators in Python

In python 3.8+ you can do :

(a:=a+1) #same as ++a (increment, then return new value)
(a:=a+1)-1 #same as a++ (return the incremented value -1) (useless)

You can do a lot of thinks with this.

>>> a = 0
>>> while (a:=a+1) < 5:
    print(a)

    
1
2
3
4

Or if you want write somthing with more sophisticated syntaxe (the goal is not optimization):

>>> del a
>>> while (a := (a if 'a' in locals() else 0) + 1) < 5:
    print(a)

    
1
2
3
4

It will return 0 even if 'a' doesn't exist without errors, and then will set it to 1

MySQL Error 1215: Cannot add foreign key constraint

when try to make foreign key when using laravel migration

like this example:

user table

    public function up()
{
    Schema::create('flights', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->TinyInteger('color_id')->unsigned();
        $table->foreign('color_id')->references('id')->on('colors');
        $table->timestamps();
    });
}

colors table

    public function up()
{
    Schema::create('flights', function (Blueprint $table) {
        $table->increments('id');
        $table->string('color');
        $table->timestamps();
    });
}

sometimes properties didn't work

[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

this error happened because the foreign key (type) in [user table] is deferent from primary key (type) in [colors table]

To solve this problem should change the primary key in [colors table]

$table->tinyIncrements('id');


When you use primary key $table->Increments('id');

you should use Integer as a foreign key

    $table-> unsignedInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

When you use primary key $table->tinyIncrements('id');

you should use unsignedTinyInteger as a foreign key

    $table-> unsignedTinyInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

When you use primary key $table->smallIncrements('id');

you should use unsignedSmallInteger as a foreign key

    $table-> unsignedSmallInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

When you use primary key $table->mediumIncrements('id');

you should use unsignedMediumInteger as a foreign key

    $table-> unsignedMediumInteger('fk_id');
    $table->foreign('fk_id')->references('id')->on('table_name');

Where does Chrome store extensions?

Another alternative is to do right click on the chrome icon and then go to shortcut tab (according to windows 10). You will see there "Target", copy the path and remove "chrome.exe".

How do I turn off Unicode in a VC++ project?

you can go to project properties --> configuration properties --> General -->Project default and there change the "Character set" from "Unicode" to "Not set".

How do I hide an element when printing a web page?

The best practice is to use a style sheet specifically for printing, and and set its media attribute to print.

In it, show/hide the elements that you want to be printed on paper.

<link rel="stylesheet" type="text/css" href="print.css" media="print" />

How can I find a specific file from a Linux terminal?

find /the_path_you_want_to_find -name index.html

How to create PDF files in Python

I believe that matplotlib has the ability to serialize graphics, text and other objects to a pdf document.

Representing Directory & File Structure in Markdown Syntax

If you are concerned about Unicode characters you can use ASCII to build the structures, so your example structure becomes

.
+-- _config.yml
+-- _drafts
|   +-- begin-with-the-crazy-ideas.textile
|   +-- on-simplicity-in-technology.markdown
+-- _includes
|   +-- footer.html
|   +-- header.html
+-- _layouts
|   +-- default.html
|   +-- post.html
+-- _posts
|   +-- 2007-10-29-why-every-programmer-should-play-nethack.textile
|   +-- 2009-04-26-barcamp-boston-4-roundup.textile
+-- _data
|   +-- members.yml
+-- _site
+-- index.html

Which is similar to the format tree uses if you select ANSI output.

Is there a Google Chrome-only CSS hack?

Sure is:

@media screen and (-webkit-min-device-pixel-ratio:0)
{ 
    #element { properties:value; } 
}

And a little fiddle to see it in action - http://jsfiddle.net/Hey7J/

Must add tho... this is generally bad practice, you shouldn't really be at the point where you start to need individual browser hacks to make you CSS work. Try using reset style sheets at the start of your project, to help avoid this.

Also, these hacks may not be future proof.

setInterval in a React app

Updated 10-second countdown using class Clock extends Component

import React, { Component } from 'react';

class Clock extends Component {
  constructor(props){
    super(props);
    this.state = {currentCount: 10}
  }
  timer() {
    this.setState({
      currentCount: this.state.currentCount - 1
    })
    if(this.state.currentCount < 1) { 
      clearInterval(this.intervalId);
    }
  }
  componentDidMount() {
    this.intervalId = setInterval(this.timer.bind(this), 1000);
  }
  componentWillUnmount(){
    clearInterval(this.intervalId);
  }
  render() {
    return(
      <div>{this.state.currentCount}</div>
    );
  }
}

module.exports = Clock;

Transform only one axis to log10 scale with ggplot2

The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:

m + geom_boxplot() + scale_y_continuous(trans='log10')

EDIT: Or if you don't like that, then either of these appears to give different but useful results:

m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot() 
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()

EDIT2 & 3: Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):

fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) + 
  geom_boxplot() + 
  scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)

alt text

Note added mid 2017 in comment about package syntax change:

scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)

For loop in Oracle SQL

You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:

-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
  k NUMBER:= 0;
BEGIN
  FOR i IN 1..10 LOOP
    k:= k+1;
    dbms_output.put_line(i||' '||k);
 END LOOP;
END;
/

-- Cursor FOR loop --
set serveroutput on
DECLARE
   CURSOR c1 IS SELECT * FROM scott.emp;
   i NUMBER:= 0;
BEGIN
  FOR e_rec IN c1 LOOP
  i:= i+1;
    dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
  END LOOP;
END;
/

-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
  FROM dual
CONNECT BY LEVEL <= 10
/

Generating random numbers with Swift

Update with swift 4.2 :

let randomInt = Int.random(in: 1..<5)
let randomFloat = Float.random(in: 1..<10)
let randomDouble = Double.random(in: 1...100)
let randomCGFloat = CGFloat.random(in: 1...1000)

Accessing JSON object keys having spaces

The way to do this is via the bracket notation.

_x000D_
_x000D_
var test = {_x000D_
    "id": "109",_x000D_
    "No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
_x000D_
_x000D_

For more info read out here:

Remove border from IFrame

Style property can be used For HTML5 if you want to remove the boder of your frame or anything you can use the style property. as given below

Code goes here

<iframe src="demo.htm" style="border:none;"></iframe>

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

In my case, there was no string on which i was calling appendChild, the object i was passing on appendChild argument was wrong, it was an array and i had pass an element object, so i used divel.appendChild(childel[0]) instead of divel.appendChild(childel) and it worked. Hope it help someone.

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

Just if someone is having this issue and hadn't done list[index, sub-index], you could be having the problem because you're missing a comma between two arrays in an array of arrays (It happened to me).

Spring MVC Controller redirect using URL parameters instead of in response

http://jira.springframework.org/browse/SPR-6464 provided me with what I needed to get things working until Spring MVC offers the functionality (potentially in the 3.0.2 release). Although I simply implemented the classes they have temporarily and added the filter to my web application context. Works great!

Combine Date and Time columns using python pandas

My dataset had 1second resolution data for a few days and parsing by the suggested methods here was very slow. Instead I used:

dates = pandas.to_datetime(df.Date, cache=True)
times = pandas.to_timedelta(df.Time)
datetimes  = dates + times

Note the use of cache=True makes parsing the dates very efficient since there are only a couple unique dates in my files, which is not true for a combined date and time column.

Angular 4 img src is not found

You must use this code in angular to add the image path. if your images are under assets folder then.

<img src="../assets/images/logo.png" id="banner-logo" alt="Landing Page"/>

if not under the assets folder then you can use this code.

<img src="../images/logo.png" id="banner-logo" alt="Landing Page"/>

if var == False

Python uses not instead of ! for negation.

Try

if not var: 
    print "learnt stuff"

instead

Insert ellipsis (...) into HTML tag if content too wide

I rewrote Alex's function to use to the MooTools library. I changed it a bit to word jump rather than add the ellipsis in the middle of a word.

Element.implement({
ellipsis: function() {
    if(this.getStyle("overflow") == "hidden") {
        var text = this.get('html');
        var multiline = this.hasClass('multiline');
        var t = this.clone()
            .setStyle('display', 'none')
            .setStyle('position', 'absolute')
            .setStyle('overflow', 'visible')
            .setStyle('width', multiline ? this.getSize().x : 'auto')
            .setStyle('height', multiline ? 'auto' : this.getSize().y)
            .inject(this, 'after');

        function height() { return t.measure(t.getSize).y > this.getSize().y; };
        function width() { return t.measure(t.getSize().x > this.getSize().x; };

        var func = multiline ? height.bind(this) : width.bind(this);

        while (text.length > 0 && func()) {
            text = text.substr(0, text.lastIndexOf(' '));
            t.set('html', text + "...");
        }

        this.set('html', t.get('html'));
        t.dispose();
    }
}
});

how do you pass images (bitmaps) between android activities using bundles?

If you pass it as a Parcelable, you're bound to get a JAVA BINDER FAILURE error. So, the solution is this: If the bitmap is small, like, say, a thumbnail, pass it as a byte array and build the bitmap for display in the next activity. For instance:

in your calling activity...

Intent i = new Intent(this, NextActivity.class);
Bitmap b; // your bitmap
ByteArrayOutputStream bs = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 50, bs);
i.putExtra("byteArray", bs.toByteArray());
startActivity(i);

...and in your receiving activity

if(getIntent().hasExtra("byteArray")) {
    ImageView previewThumbnail = new ImageView(this);
    Bitmap b = BitmapFactory.decodeByteArray(
        getIntent().getByteArrayExtra("byteArray"),0,getIntent().getByteArrayExtra("byteArray").length);        
    previewThumbnail.setImageBitmap(b);
}

new Date() is working in Chrome but not Firefox

In Firefox, any invalid Date is returned as a Date object as Date 1899-11-29T19:00:00.000Z, therefore check if browser is Firefox then get Date object of string "1899-11-29T19:00:00.000Z".getDate(). Finally compare it with the date.

How to succinctly write a formula with many variables from a data frame?

Yes of course, just add the response y as first column in the dataframe and call lm() on it:

d2<-data.frame(y,d)
> d2
  y x1 x2 x3
1 1  4  3  4
2 4 -1  9 -4
3 6  3  8 -2
> lm(d2)

Call:
lm(formula = d2)

Coefficients:
(Intercept)           x1           x2           x3  
    -5.6316       0.7895       1.1579           NA  

Also, my information about R points out that assignment with <- is recommended over =.

Convert YYYYMMDD to DATE

Use SELECT CONVERT(date, '20140327')

In your case,

SELECT [FIRST_NAME],
       [MIDDLE_NAME],
       [LAST_NAME],
       CONVERT(date, [GRADUATION_DATE])     
FROM mydb

Extracting specific selected columns to new DataFrame as a copy

There is a way of doing this and it actually looks similar to R

new = old[['A', 'C', 'D']].copy()

Here you are just selecting the columns you want from the original data frame and creating a variable for those. If you want to modify the new dataframe at all you'll probably want to use .copy() to avoid a SettingWithCopyWarning.

An alternative method is to use filter which will create a copy by default:

new = old.filter(['A','B','D'], axis=1)

Finally, depending on the number of columns in your original dataframe, it might be more succinct to express this using a drop (this will also create a copy by default):

new = old.drop('B', axis=1)

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

Using Enum values as String literals

As Benny Neugebauer mentions, you could overwrite the toString(). However instead overwriting the toString for each enum field I like more something like this:

public enum Country{
    SPAIN("España"),
    ITALY("Italia"),
    PORTUGAL("Portugal");


    private String value;

    Country(final String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return this.getValue();
    }
}

You could also add a static method to retrieve all the fields, to print them all, etc. Simply call getValue to obtain the string associated to each Enum item

Reading HTTP headers in a Spring REST controller

Instead of taking the HttpServletRequest object in every method, keep in controllers' context by auto-wiring via the constructor. Then you can access from all methods of the controller.

public class OAuth2ClientController {
    @Autowired
    private OAuth2ClientService oAuth2ClientService;

    private HttpServletRequest request;

    @Autowired
    public OAuth2ClientController(HttpServletRequest request) {
        this.request = request;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<String> createClient(@RequestBody OAuth2Client client) {
        System.out.println(request.getRequestURI());
        System.out.println(request.getHeader("Content-Type"));

        return ResponseEntity.ok();
    }
}

Java Synchronized list

You can have 2 diffent problems with lists :
1) If you do a modification within an iteration even though in a mono thread environment, you will have ConcurrentModificationException like in this following example :

List<String> list = new ArrayList<String>();
for (int i=0;i<5;i++)
   list.add("Hello "+i);

for(String msg:list)
   list.remove(msg);

So, to avoid this problem, you can do :

for(int i=list.size()-1;i>=0;i--)
   list.remove(i);

2)The second problem could be multi threading environment. As mentioned above, you can use synchronized(list) to avoid exceptions.

HTML Table cell background image alignment

This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:

<table>
    <tr>
        <td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
            Hello World
        </td>
    </tr>
</table>

SQLite UPSERT / UPDATE OR INSERT

Q&A Style

Well, after researching and fighting with the problem for hours, I found out that there are two ways to accomplish this, depending on the structure of your table and if you have foreign keys restrictions activated to maintain integrity. I'd like to share this in a clean format to save some time to the people that may be in my situation.


Option 1: You can afford deleting the row

In other words, you don't have foreign key, or if you have them, your SQLite engine is configured so that there no are integrity exceptions. The way to go is INSERT OR REPLACE. If you are trying to insert/update a player whose ID already exists, the SQLite engine will delete that row and insert the data you are providing. Now the question comes: what to do to keep the old ID associated?

Let's say we want to UPSERT with the data user_name='steven' and age=32.

Look at this code:

INSERT INTO players (id, name, age)

VALUES (
    coalesce((select id from players where user_name='steven'),
             (select max(id) from drawings) + 1),
    32)

The trick is in coalesce. It returns the id of the user 'steven' if any, and otherwise, it returns a new fresh id.


Option 2: You cannot afford deleting the row

After monkeying around with the previous solution, I realized that in my case that could end up destroying data, since this ID works as a foreign key for other table. Besides, I created the table with the clause ON DELETE CASCADE, which would mean that it'd delete data silently. Dangerous.

So, I first thought of a IF clause, but SQLite only has CASE. And this CASE can't be used (or at least I did not manage it) to perform one UPDATE query if EXISTS(select id from players where user_name='steven'), and INSERT if it didn't. No go.

And then, finally I used the brute force, with success. The logic is, for each UPSERT that you want to perform, first execute a INSERT OR IGNORE to make sure there is a row with our user, and then execute an UPDATE query with exactly the same data you tried to insert.

Same data as before: user_name='steven' and age=32.

-- make sure it exists
INSERT OR IGNORE INTO players (user_name, age) VALUES ('steven', 32); 

-- make sure it has the right data
UPDATE players SET user_name='steven', age=32 WHERE user_name='steven'; 

And that's all!

EDIT

As Andy has commented, trying to insert first and then update may lead to firing triggers more often than expected. This is not in my opinion a data safety issue, but it is true that firing unnecessary events makes little sense. Therefore, a improved solution would be:

-- Try to update any existing row
UPDATE players SET age=32 WHERE user_name='steven';

-- Make sure it exists
INSERT OR IGNORE INTO players (user_name, age) VALUES ('steven', 32); 

ActiveMQ connection refused

I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:

Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused

& I resolved it following way.

   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();

  connectionFactory.setBrokerURL("tcp://hostname:61616");
  connectionFactory.setUserName("admin");
  connectionFactory.setPassword("admin");

Cast object to T

You can presumably pass-in, as a parameter, a delegate which will convert from string to T.

How to use onClick() or onSelect() on option tag in a JSP page?

The answer you gave above works but it is confusing because you have used two names twice and you have an unnecessary line of code. you are doing a process that is not necessary.

it's a good idea when debugging code to get pen and paper and draw little boxes to represent memory spaces (i.e variables being stored) and then to draw arrows to indicate when a variable goes into a little box and when it comes out, if it gets overwritten or is a copy made etc.

if you do this with the code below you will see that

var selectBox = document.getElementById("selectBox");

gets put in a box and stays there you don't do anything with it afterwards.

and

var selectBox = document.getElementById("selectBox");

is hard to debug and is confusing when you have a select id of selectBox for the options list . ---- which selectBox do you want to manipulate / query / etc is it the local var selectBox that will disappear or is it the selectBox id you have assigned to the select tag

your code works until you add to it or modify it then you can easily loose track and get all mixed up

<html>
<head>
<script type="text/javascript">

function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}

</script>
</head>

<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>

a leaner way that works also is:

<html>
<head>
<script type="text/javascript">

function changeFunc() {

var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}

</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>

and it's a good idea to use descriptive names that match the program and task you are working on am currently writing a similar program to accept and process postcodes using your code and modifying it with descriptive names the object is to make computer language as close to natural language as possible.

<script type="text/javascript">

function Mapit(){

var actualPostcode=getPostcodes.options[getPostcodes.selectedIndex].value;

alert(actualPostcode);

// alert is for debugging only next we go on to process and do something
// in this developing program it will placing markers on a map

}

</script>

<select id="getPostcodes" onchange="Mapit();">

<option>London North Inner</option>

<option>N1</option>

<option>London North Outer</option>

<option>N2</option>
<option>N3</option>
<option>N4</option>

// a lot more options follow 
// with text in options to divide into areas and nothing will happen 
// if visitor clicks on the text function Mapit() will ignore
// all clicks on the divider text inserted into option boxes

</select>

Pycharm and sys.argv arguments

I believe it's included even in Edu version. Just right click the solid green arrow button (Run) and choose "Add parameters".

how to check if a datareader is null or empty

Try this simpler equivalent syntax:

ltlAdditional.Text = (myReader["Additional"] == DBNull.Value) ? "is null" : "contains data";

delete image from folder PHP

There are a few routes. One, the most simple, would involve making that into a form; when it submits you react to POST data and delete the image using unlink

DISCLAIMER: This is not secure. An attacker could use this code to delete any file on your server. You must expand on this demonstration code to add some measure of security, otherwise you can expect bad things.

Each image's display markup would contain a form something like this:

echo '<form method="post">';
  echo '<input type="hidden" value="'.$file.'" name="delete_file" />';
  echo '<input type="submit" value="Delete image" />';
echo '</form>';

...and at at the top of that same PHP file:

if (array_key_exists('delete_file', $_POST)) {
  $filename = $_POST['delete_file'];
  if (file_exists($filename)) {
    unlink($filename);
    echo 'File '.$filename.' has been deleted';
  } else {
    echo 'Could not delete '.$filename.', file does not exist';
  }
}
// existing code continues below...

You can elaborate on this by using javascript: instead of submitting the form, you could send an AJAX request. The server-side code would look rather similar to this.

Documentation and Related Reading

How do I get a background location update every n minutes in my iOS application?

In iOS 9 and watchOS 2.0 there's a new method on CLLocationManager that lets you request the current location: CLLocationManager:requestLocation(). This completes immediately and then returns the location to the CLLocationManager delegate.

You can use an NSTimer to request a location every minute with this method now and don't have to work with startUpdatingLocation and stopUpdatingLocation methods.

However if you want to capture locations based on a change of X meters from the last location, just set the distanceFilter property of CLLocationManger and to X call startUpdatingLocation().

How do I get the position selected in a RecyclerView?

A different method - using setTag() and getTag() methods of the View class.

  1. use setTag() in the onBindViewHolder method of your adapter

    @Override
    public void onBindViewHolder(myViewHolder viewHolder, int position) {
        viewHolder.mCardView.setTag(position);
    }
    

    where mCardView is defined in the myViewHolder class

    private class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
               public View mCardView;
    
               public myViewHolder(View view) {
                   super(view);
                   mCardView = (CardView) view.findViewById(R.id.card_view);
    
                   mCardView.setOnClickListener(this);
               }
           }
    
  2. use getTag() in your OnClickListener implementation

    @Override
    public void onClick(View view) {
        int position = (int) view.getTag();           
    
    //display toast with position of cardview in recyclerview list upon click
    Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
    }
    

see https://stackoverflow.com/a/33027953/4658957 for more details

How to query values from xml nodes?

Try this:

SELECT RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationReportReferenceIdentifier/node())[1]','varchar(50)') AS ReportIdentifierNumber,
       RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationNumber/node())[1]','int') AS OrginazationNumber
FROM Batches

How to run multiple DOS commands in parallel?

I suggest you to see "How do I run a bat file in the background from another bat file?"

Also, good answer (of using start command) was given in "Parallel execution of shell processes" question page here;

But my recommendation is to use PowerShell. I believe it will perfectly suit your needs.

How to calculate the time interval between two time strings

Yes, definitely datetime is what you need here. Specifically, the strptime function, which parses a string into a time object.

from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)

That gets you a timedelta object that contains the difference between the two times. You can do whatever you want with that, e.g. converting it to seconds or adding it to another datetime.

This will return a negative result if the end time is earlier than the start time, for example s1 = 12:00:00 and s2 = 05:00:00. If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code:

if tdelta.days < 0:
    tdelta = timedelta(days=0,
                seconds=tdelta.seconds, microseconds=tdelta.microseconds)

(of course you need to include from datetime import timedelta somewhere). Thanks to J.F. Sebastian for pointing out this use case.

How to sort a dataFrame in python pandas by two or more columns?

As of pandas 0.17.0, DataFrame.sort() is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values

As such, the answer to your question would now be

df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)

forward declaration of a struct in C?

A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

struct A;                      // forward declaration
void function( struct A *a );  // using the 'incomplete' type only as pointer

If you typedef your struct you can leave out the struct keyword.

typedef struct A A;          // forward declaration *and* typedef
void function( A *a );

Note that it is legal to reuse the struct name

Try changing the forward declaration to this in your code:

typedef struct context context;

It might be more readable to do add a suffix to indicate struct name and type name:

typedef struct context_s context_t;

Autocompletion of @author in Intellij

You can work around that via a Live Template. Go to Settings -> Live Template, click the "Add"-Button (green plus on the right).

In the "Abbreviation" field, enter the string that should activate the template (e.g. @a), and in the "Template Text" area enter the string to complete (e.g. @author - My Name). Set the "Applicable context" to Java (Comments only maybe) and set a key to complete (on the right).

I tested it and it works fine, however IntelliJ seems to prefer the inbuild templates, so "@a + Tab" only completes "author". Setting the completion key to Space worked however.

To change the user name that is automatically inserted via the File Templates (when creating a class for example), can be changed by adding

-Duser.name=Your name

to the idea.exe.vmoptions or idea64.exe.vmoptions (depending on your version) in the IntelliJ/bin directory.

enter image description here

Restart IntelliJ

Easy way to print Perl array? (with a little formatting)

If you're coding for the kind of clarity that would be understood by someone who is just starting out with Perl, the traditional this construct says what it means, with a high degree of clarity and legibility:

$string = join ', ', @array;
print "$string\n";

This construct is documented in perldoc -fjoin.

However, I've always liked how simple $, makes it. The special variable $" is for interpolation, and the special variable $, is for lists. Combine either one with dynamic scope-constraining 'local' to avoid having ripple effects throughout the script:

use 5.012_002;
use strict;
use warnings;

my @array = qw/ 1 2 3 4 5 /;

{
    local $" = ', ';
    print "@array\n"; # Interpolation.
}

OR with $,:

use feature q(say);
use strict;
use warnings;

my @array = qw/ 1 2 3 4 5 /;
{
    local $, = ', ';
    say @array; # List
}

The special variables $, and $" are documented in perlvar. The local keyword, and how it can be used to constrain the effects of altering a global punctuation variable's value is probably best described in perlsub.

Enjoy!

Use Font Awesome Icon in Placeholder

If you're using FontAwesome 4.7 this should be enough:

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<input type="text" placeholder="&#xF002; Search" style="font-family:Arial, FontAwesome" />
_x000D_
_x000D_
_x000D_

A list of hex codes can be found in the Font Awesome cheatsheet. However, in the lastest FontAwesome 5.0 this method does not work (even if you use the CSS approach combined with the updated font-family).

Convert data.frame column format from character to factor

Hi welcome to the world of R.

mtcars  #look at this built in data set
str(mtcars) #allows you to see the classes of the variables (all numeric)

#one approach it to index with the $ sign and the as.factor function
mtcars$am <- as.factor(mtcars$am)
#another approach
mtcars[, 'cyl'] <- as.factor(mtcars[, 'cyl'])
str(mtcars)  # now look at the classes

This also works for character, dates, integers and other classes

Since you're new to R I'd suggest you have a look at these two websites:

R reference manuals: http://cran.r-project.org/manuals.html

R Reference card: http://cran.r-project.org/doc/contrib/Short-refcard.pdf

What does the variable $this mean in PHP?

Generally, this keyword is used inside a class, generally with in the member functions to access non-static members of a class(variables or functions) for the current object.

  1. this keyword should be preceded with a $ symbol.
  2. In case of this operator, we use the -> symbol.
  3. Whereas, $this will refer the member variables and function for a particular instance.

Let's take an example to understand the usage of $this.

<?php
class Hero {
    // first name of hero
    private $name;
    
    // public function to set value for name (setter method)
    public function setName($name) {
        $this->name = $name;
    }
    
    // public function to get value of name (getter method)
    public function getName() {
        return $this->name;
    }
}

// creating class object
$stark = new Hero();

// calling the public function to set fname
$stark->setName("IRON MAN");

// getting the value of the name variable
echo "I Am " . $stark->getName();
?>

OUTPUT: I am IRON MAN

NOTE: A static variable acts as a global variable and is shared among all the objects of the class. A non-static variables are specific to instance object in which they are created.

How to merge a transparent png image with another image using PIL

Image.paste does not work as expected when the background image also contains transparency. You need to use real Alpha Compositing.

Pillow 2.0 contains an alpha_composite function that does this.

background = Image.open("test1.png")
foreground = Image.open("test2.png")

Image.alpha_composite(background, foreground).save("test3.png")

EDIT: Both images need to be of the type RGBA. So you need to call convert('RGBA') if they are paletted, etc.. If the background does not have an alpha channel, then you can use the regular paste method (which should be faster).

pandas dataframe columns scaling with sklearn

I know it's a very old comment, but still:

Instead of using single bracket (dfTest['A']), use double brackets (dfTest[['A']]).

i.e: min_max_scaler.fit_transform(dfTest[['A']]).

I believe this will give the desired result.

How to use glOrtho() in OpenGL?

Minimal runnable example

glOrtho: 2D games, objects close and far appear the same size:

enter image description here

glFrustrum: more real-life like 3D, identical objects further away appear smaller:

enter image description here

main.c

#include <stdlib.h>

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

static int ortho = 0;

static void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();
    if (ortho) {
    } else {
        /* This only rotates and translates the world around to look like the camera moved. */
        gluLookAt(0.0, 0.0, -3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    }
    glColor3f(1.0f, 1.0f, 1.0f);
    glutWireCube(2);
    glFlush();
}

static void reshape(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    if (ortho) {
        glOrtho(-2.0, 2.0, -2.0, 2.0, -1.5, 1.5);
    } else {
        glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
    }
    glMatrixMode(GL_MODELVIEW);
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    if (argc > 1) {
        ortho = 1;
    }
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(100, 100);
    glutCreateWindow(argv[0]);
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_FLAT);
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile:

gcc -ggdb3 -O0 -o main -std=c99 -Wall -Wextra -pedantic main.c -lGL -lGLU -lglut

Run with glOrtho:

./main 1

Run with glFrustrum:

./main

Tested on Ubuntu 18.10.

Schema

Ortho: camera is a plane, visible volume a rectangle:

enter image description here

Frustrum: camera is a point,visible volume a slice of a pyramid:

enter image description here

Image source.

Parameters

We are always looking from +z to -z with +y upwards:

glOrtho(left, right, bottom, top, near, far)
  • left: minimum x we see
  • right: maximum x we see
  • bottom: minimum y we see
  • top: maximum y we see
  • -near: minimum z we see. Yes, this is -1 times near. So a negative input means positive z.
  • -far: maximum z we see. Also negative.

Schema:

Image source.

How it works under the hood

In the end, OpenGL always "uses":

glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

If we use neither glOrtho nor glFrustrum, that is what we get.

glOrtho and glFrustrum are just linear transformations (AKA matrix multiplication) such that:

  • glOrtho: takes a given 3D rectangle into the default cube
  • glFrustrum: takes a given pyramid section into the default cube

This transformation is then applied to all vertexes. This is what I mean in 2D:

Image source.

The final step after transformation is simple:

  • remove any points outside of the cube (culling): just ensure that x, y and z are in [-1, +1]
  • ignore the z component and take only x and y, which now can be put into a 2D screen

With glOrtho, z is ignored, so you might as well always use 0.

One reason you might want to use z != 0 is to make sprites hide the background with the depth buffer.

Deprecation

glOrtho is deprecated as of OpenGL 4.5: the compatibility profile 12.1. "FIXED-FUNCTION VERTEX TRANSFORMATIONS" is in red.

So don't use it for production. In any case, understanding it is a good way to get some OpenGL insight.

Modern OpenGL 4 programs calculate the transformation matrix (which is small) on the CPU, and then give the matrix and all points to be transformed to OpenGL, which can do the thousands of matrix multiplications for different points really fast in parallel.

Manually written vertex shaders then do the multiplication explicitly, usually with the convenient vector data types of the OpenGL Shading Language.

Since you write the shader explicitly, this allows you to tweak the algorithm to your needs. Such flexibility is a major feature of more modern GPUs, which unlike the old ones that did a fixed algorithm with some input parameters, can now do arbitrary computations. See also: https://stackoverflow.com/a/36211337/895245

With an explicit GLfloat transform[] it would look something like this:

glfw_transform.c

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#define GLEW_STATIC
#include <GL/glew.h>

#include <GLFW/glfw3.h>

static const GLuint WIDTH = 800;
static const GLuint HEIGHT = 600;
/* ourColor is passed on to the fragment shader. */
static const GLchar* vertex_shader_source =
    "#version 330 core\n"
    "layout (location = 0) in vec3 position;\n"
    "layout (location = 1) in vec3 color;\n"
    "out vec3 ourColor;\n"
    "uniform mat4 transform;\n"
    "void main() {\n"
    "    gl_Position = transform * vec4(position, 1.0f);\n"
    "    ourColor = color;\n"
    "}\n";
static const GLchar* fragment_shader_source =
    "#version 330 core\n"
    "in vec3 ourColor;\n"
    "out vec4 color;\n"
    "void main() {\n"
    "    color = vec4(ourColor, 1.0f);\n"
    "}\n";
static GLfloat vertices[] = {
/*   Positions          Colors */
     0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
    -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
     0.0f,  0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};

/* Build and compile shader program, return its ID. */
GLuint common_get_shader_program(
    const char *vertex_shader_source,
    const char *fragment_shader_source
) {
    GLchar *log = NULL;
    GLint log_length, success;
    GLuint fragment_shader, program, vertex_shader;

    /* Vertex shader */
    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
    glCompileShader(vertex_shader);
    glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &log_length);
    log = malloc(log_length);
    if (log_length > 0) {
        glGetShaderInfoLog(vertex_shader, log_length, NULL, log);
        printf("vertex shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("vertex shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Fragment shader */
    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
    glCompileShader(fragment_shader);
    glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetShaderInfoLog(fragment_shader, log_length, NULL, log);
        printf("fragment shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("fragment shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Link shaders */
    program = glCreateProgram();
    glAttachShader(program, vertex_shader);
    glAttachShader(program, fragment_shader);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &success);
    glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetProgramInfoLog(program, log_length, NULL, log);
        printf("shader link log:\n\n%s\n", log);
    }
    if (!success) {
        printf("shader link error");
        exit(EXIT_FAILURE);
    }

    /* Cleanup. */
    free(log);
    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);
    return program;
}

int main(void) {
    GLint shader_program;
    GLint transform_location;
    GLuint vbo;
    GLuint vao;
    GLFWwindow* window;
    double time;

    glfwInit();
    window = glfwCreateWindow(WIDTH, HEIGHT, __FILE__, NULL, NULL);
    glfwMakeContextCurrent(window);
    glewExperimental = GL_TRUE;
    glewInit();
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glViewport(0, 0, WIDTH, HEIGHT);

    shader_program = common_get_shader_program(vertex_shader_source, fragment_shader_source);

    glGenVertexArrays(1, &vao);
    glGenBuffers(1, &vbo);
    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    /* Position attribute */
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    /* Color attribute */
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(1);
    glBindVertexArray(0);

    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shader_program);
        transform_location = glGetUniformLocation(shader_program, "transform");
        /* THIS is just a dummy transform. */
        GLfloat transform[] = {
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 1.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 1.0f,
        };
        time = glfwGetTime();
        transform[0] = 2.0f * sin(time);
        transform[5] = 2.0f * cos(time);
        glUniformMatrix4fv(transform_location, 1, GL_FALSE, transform);

        glBindVertexArray(vao);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);
        glfwSwapBuffers(window);
    }
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo);
    glfwTerminate();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile and run:

gcc -ggdb3 -O0 -o glfw_transform.out -std=c99 -Wall -Wextra -pedantic glfw_transform.c -lGL -lGLU -lglut -lGLEW -lglfw -lm
./glfw_transform.out

Output:

enter image description here

The matrix for glOrtho is really simple, composed only of scaling and translation:

scalex, 0,      0,      translatex,
0,      scaley, 0,      translatey,
0,      0,      scalez, translatez,
0,      0,      0,      1

as mentioned in the OpenGL 2 docs.

The glFrustum matrix is not too hard to calculate by hand either, but starts getting annoying. Note how frustum cannot be made up with only scaling and translations like glOrtho, more info at: https://gamedev.stackexchange.com/a/118848/25171

The GLM OpenGL C++ math library is a popular choice for calculating such matrices. http://glm.g-truc.net/0.9.2/api/a00245.html documents both an ortho and frustum operations.

SQL not a single-group group function

Maybe you find this simpler

select * from (
    select ssn, sum(time) from downloads
    group by ssn
    order by sum(time) desc
) where rownum <= 10 --top 10 downloaders

Regards
K

PostgreSQL create table if not exists

Try this:

CREATE TABLE IF NOT EXISTS app_user (
  username varchar(45) NOT NULL,
  password varchar(450) NOT NULL,
  enabled integer NOT NULL DEFAULT '1',
  PRIMARY KEY (username)
)

Find where python is installed (if it isn't default dir)

  1. First search for PYTHON IDLE from search bar
  2. Open the IDLE and use below commands.

    import sys print(sys.path)

  3. It will give you the path where the python.exe is installed. For eg: C:\Users\\...\python.exe

  4. Add the same path to system environment variable.

Use of document.getElementById in JavaScript

Here in your code demo is id where you want to display your result after click event has occur and just nothing.

You can take anything

<p id="demo">

or

<div id="demo"> 

It is just node in a document where you just want to display your result.

Google OAuth 2 authorization - Error: redirect_uri_mismatch

In my case I added

https://websitename.com/sociallogin/social/callback/?hauth.done=Google

in Authorized redirect URIs section and it worked for me

Bash script prints "Command Not Found" on empty lines

for executing that you must provide full path of that for example

/home/Manuel/mywrittenscript

html select option separator

You could use the em dash "—". It has no visible spaces between each character.
(In some fonts!)

In HTML:

<option value="—————————————" disabled>—————————————</option>

Or in XHTML:

<option value="—————————————" disabled="disabled">—————————————</option>

How to conclude your merge of a file?

I just did:

git merge --continue

At which point vi launched to edit a merge comment. A quick :wq and the merge was done.

When is each sorting algorithm used?

Quicksort is usually the fastest on average, but It has some pretty nasty worst-case behaviors. So if you have to guarantee no bad data gives you O(N^2), you should avoid it.

Merge-sort uses extra memory, but is particularly suitable for external sorting (i.e. huge files that don't fit into memory).

Heap-sort can sort in-place and doesn't have the worst case quadratic behavior, but on average is slower than quicksort in most cases.

Where only integers in a restricted range are involved, you can use some kind of radix sort to make it very fast.

In 99% of the cases, you'll be fine with the library sorts, which are usually based on quicksort.

draw diagonal lines in div background with CSS

If you'd like the cross to be partially transparent, the naive approach would be to make linear-gradient colors semi-transparent. But that doesn't work out good due to the alpha blending at the intersection, producing a differently colored diamond. The solution to this is to leave the colors solid but add transparency to the gradient container instead:

_x000D_
_x000D_
.cross {_x000D_
  position: relative;_x000D_
}_x000D_
.cross::after {_x000D_
  pointer-events: none;_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0; bottom: 0; left: 0; right: 0;_x000D_
}_x000D_
_x000D_
.cross1::after {_x000D_
  background:_x000D_
    linear-gradient(to top left, transparent 45%, rgba(255,0,0,0.35) 46%, rgba(255,0,0,0.35) 54%, transparent 55%),_x000D_
    linear-gradient(to top right, transparent 45%, rgba(255,0,0,0.35) 46%, rgba(255,0,0,0.35) 54%, transparent 55%);_x000D_
}_x000D_
_x000D_
.cross2::after {_x000D_
  background:_x000D_
    linear-gradient(to top left, transparent 45%, rgb(255,0,0) 46%, rgb(255,0,0) 54%, transparent 55%),_x000D_
    linear-gradient(to top right, transparent 45%, rgb(255,0,0) 46%, rgb(255,0,0) 54%, transparent 55%);_x000D_
  opacity: 0.35;_x000D_
}_x000D_
_x000D_
div { width: 180px; text-align: justify; display: inline-block; margin: 20px; }
_x000D_
<div class="cross cross1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et dui imperdiet, dapibus augue quis, molestie libero. Cras nisi leo, sollicitudin nec eros vel, finibus laoreet nulla. Ut sit amet leo dui. Praesent rutrum rhoncus mauris ac ornare. Donec in accumsan turpis, pharetra eleifend lorem. Ut vitae aliquet mi, id cursus purus.</div>_x000D_
_x000D_
<div class="cross cross2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et dui imperdiet, dapibus augue quis, molestie libero. Cras nisi leo, sollicitudin nec eros vel, finibus laoreet nulla. Ut sit amet leo dui. Praesent rutrum rhoncus mauris ac ornare. Donec in accumsan turpis, pharetra eleifend lorem. Ut vitae aliquet mi, id cursus purus.</div>
_x000D_
_x000D_
_x000D_

How to get first and last day of previous month (with timestamp) in SQL Server

Solution

The date format that you requested is called ODBC format (code 120).

To actually calculate the values that you requested, include the following in your SQL.

Copy, paste...

DECLARE
    @FirstDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, -1, GETDATE() - 2)) ), DATEADD(m, -1, GETDATE() - 1)))
    , @LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE()) ), GETDATE()))

...and use in your code:

  • @FirstDayOfLastMonth
  • @LastDayOfLastMonth

Be aware that it has to be pasted earlier than any statements that reference the parameters, but from that point on you can reference @FirstDayOfLastMonth and @LastDayOfLastMonth in your code.

Example

Let's see some code in action:

DECLARE
    @FirstDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, -1, GETDATE() - 2)) ), DATEADD(m, -1, GETDATE() - 1)))
    , @LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE()) ), GETDATE()))

SELECT
    'First day of last month' AS Title, CONVERT(VARCHAR, @FirstDayOfLastMonth , 120) AS [ODBC]
UNION 

SELECT 
    'Last day of last month' AS Title, CONVERT(VARCHAR, @LastDayOfLastMonth , 120) AS [ODBC]

Run the above code to produce the following output:

Figure a

Note: Bear in mind that today's date for me is 12th September, 2016.

More (for completeness' sake)

Common date parameters

Are you left wanting more?

To set up a more comprehensive range of handy date related parameters, include the following in your SQL:

DECLARE
    @FirstDayOfCurrentWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0))
    , @LastDayOfCurrentWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 6))
    , @FirstDayOfLastWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 7, GETDATE()), 0))
    , @LastDayOfLastWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 7, GETDATE()), 6))
    , @FirstDayOfNextWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 7))
    , @LastDayOfNextWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 13))
    , @FirstDayOfCurrentMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE() - 1) ), GETDATE()))
    , @LastDayOfCurrentMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, 1, GETDATE())) ), DATEADD(m, 1, GETDATE())))
    , @FirstDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, -1, GETDATE() - 2)) ), DATEADD(m, -1, GETDATE() - 1)))
    , @LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE()) ), GETDATE()))
    , @FirstDayOfNextMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, 1, GETDATE() - 1)) ), DATEADD(m, 1, GETDATE())))
    , @LastDayOfNextMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, 2, GETDATE())) ), DATEADD(m, 2, GETDATE())))
    , @FirstDayOfCurrentYear DATETIME = CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0))
    , @LastDayOfCurrentYear DATETIME = CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))))
    , @FirstDayOfLastYear DATETIME = CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) - 1, 0))
    , @LastDayOfLastYear DATETIME = CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0))))
    , @FirstDayOfNextYear DATETIME = CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))
    , @LastDayOfNextYear DATETIME = CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 2, 0))))

It would make most sense to include it earlier on, preferably at the top of your procedure or SQL query.

Once declared, the parameters can be referenced anywhere in your code, as many times as you need them.

Example

Let's see some code in action:

DECLARE
    @FirstDayOfCurrentWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0))
    , @LastDayOfCurrentWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 6))
    , @FirstDayOfLastWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 7, GETDATE()), 0))
    , @LastDayOfLastWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 7, GETDATE()), 6))
    , @FirstDayOfNextWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 7))
    , @LastDayOfNextWeek DATETIME = CONVERT(DATE, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 13))
    , @FirstDayOfCurrentMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE() - 1) ), GETDATE()))
    , @LastDayOfCurrentMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, 1, GETDATE())) ), DATEADD(m, 1, GETDATE())))
    , @FirstDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, -1, GETDATE() - 2)) ), DATEADD(m, -1, GETDATE() - 1)))
    , @LastDayOfLastMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(GETDATE()) ), GETDATE()))
    , @FirstDayOfNextMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, 1, GETDATE() - 1)) ), DATEADD(m, 1, GETDATE())))
    , @LastDayOfNextMonth DATETIME = CONVERT(DATE, DATEADD(d, -( DAY(DATEADD(m, 2, GETDATE())) ), DATEADD(m, 2, GETDATE())))
    , @FirstDayOfCurrentYear DATETIME = CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0))
    , @LastDayOfCurrentYear DATETIME = CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))))
    , @FirstDayOfLastYear DATETIME = CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) - 1, 0))
    , @LastDayOfLastYear DATETIME = CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0))))
    , @FirstDayOfNextYear DATETIME = CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))
    , @LastDayOfNextYear DATETIME = CONVERT(DATE, DATEADD(ms, -2, DATEADD(YEAR, 0, DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 2, 0))))

SELECT  
    'a) FirstDayOfCurrentWeek.' AS [Title] ,
    @FirstDayOfCurrentWeek AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 104) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 105) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 111) + ' ' + CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentWeek, 120) AS [ODBC]
UNION
SELECT  
    'b) LastDayOfCurrentWeek.' AS [Title] ,
    @LastDayOfCurrentWeek AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @LastDayOfCurrentWeek, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @LastDayOfCurrentWeek, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @LastDayOfCurrentWeek, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @LastDayOfCurrentWeek, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @LastDayOfCurrentWeek, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @LastDayOfCurrentWeek, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @LastDayOfCurrentWeek, 120) AS [ODBC]
UNION
SELECT  
    'c) FirstDayOfLastWeek.' AS [Title] ,
    @FirstDayOfLastWeek AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @FirstDayOfLastWeek, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @FirstDayOfLastWeek, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @FirstDayOfLastWeek, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @FirstDayOfLastWeek, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @FirstDayOfLastWeek, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @FirstDayOfLastWeek, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @FirstDayOfLastWeek, 120) AS [ODBC]
UNION
SELECT  
    'd) LastDayOfLastWeek.' AS [Title] ,
    @LastDayOfLastWeek AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @LastDayOfLastWeek, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @LastDayOfLastWeek, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @LastDayOfLastWeek, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @LastDayOfLastWeek, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @LastDayOfLastWeek, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @LastDayOfLastWeek, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @LastDayOfLastWeek, 120) AS [ODBC]
UNION
SELECT  
    'e) FirstDayOfNextWeek.' AS [Title] ,
    @FirstDayOfNextWeek AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @FirstDayOfNextWeek, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @FirstDayOfNextWeek, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @FirstDayOfNextWeek, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @FirstDayOfNextWeek, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @FirstDayOfNextWeek, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @FirstDayOfNextWeek, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @FirstDayOfNextWeek, 120) AS [ODBC]
UNION
SELECT  
    'f) LastDayOfNextWeek.' AS [Title] ,
    @LastDayOfNextWeek AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @LastDayOfNextWeek, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @LastDayOfNextWeek, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @LastDayOfNextWeek, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @LastDayOfNextWeek, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @LastDayOfNextWeek, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @LastDayOfNextWeek, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @LastDayOfNextWeek, 120) AS [ODBC]
UNION
SELECT  
    'g) FirstDayOfCurrentMonth.' AS [Title] ,
    @FirstDayOfCurrentMonth AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentMonth, 120) AS [ODBC]
UNION
SELECT  
    'h) LastDayOfCurrentMonth.' AS [Title] ,
    @LastDayOfCurrentMonth AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @LastDayOfCurrentMonth, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @LastDayOfCurrentMonth, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @LastDayOfCurrentMonth, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @LastDayOfCurrentMonth, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @LastDayOfCurrentMonth, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @LastDayOfCurrentMonth, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @LastDayOfCurrentMonth, 120) AS [ODBC]
UNION
SELECT  
    'i) FirstDayOfLastMonth.' AS [Title] ,
    @FirstDayOfLastMonth AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @FirstDayOfLastMonth, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @FirstDayOfLastMonth, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @FirstDayOfLastMonth, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @FirstDayOfLastMonth, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @FirstDayOfLastMonth, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @FirstDayOfLastMonth, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @FirstDayOfLastMonth, 120) AS [ODBC]
UNION
SELECT  
    'j) LastDayOfLastMonth.' AS [Title] ,
    @LastDayOfLastMonth AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @LastDayOfLastMonth, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @LastDayOfLastMonth, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @LastDayOfLastMonth, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @LastDayOfLastMonth, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @LastDayOfLastMonth, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @LastDayOfLastMonth, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @LastDayOfLastMonth, 120) AS [ODBC]
UNION
SELECT  
    'k) FirstDayOfNextMonth.' AS [Title] ,
    @FirstDayOfNextMonth AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @FirstDayOfNextMonth, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @FirstDayOfNextMonth, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @FirstDayOfNextMonth, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @FirstDayOfNextMonth, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @FirstDayOfNextMonth, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @FirstDayOfNextMonth, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @FirstDayOfNextMonth, 120) AS [ODBC]
UNION
SELECT  
    'l) LastDayOfNextMonth.' AS [Title] ,
    @LastDayOfNextMonth AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @LastDayOfNextMonth, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @LastDayOfNextMonth, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @LastDayOfNextMonth, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @LastDayOfNextMonth, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @LastDayOfNextMonth, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @LastDayOfNextMonth, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @LastDayOfNextMonth, 120) AS [ODBC]
UNION
SELECT  
    'm) FirstDayOfCurrentYear.' AS [Title] ,
    @FirstDayOfCurrentYear AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentYear, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentYear, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentYear, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentYear, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentYear, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentYear, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @FirstDayOfCurrentYear, 120) AS [ODBC]
UNION
SELECT  
    'n) LastDayOfCurrentYear.' AS [Title] ,
    @LastDayOfCurrentYear AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @LastDayOfCurrentYear, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @LastDayOfCurrentYear, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @LastDayOfCurrentYear, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @LastDayOfCurrentYear, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @LastDayOfCurrentYear, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @LastDayOfCurrentYear, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @LastDayOfCurrentYear, 120) AS [ODBC]
UNION
SELECT  
    'o) FirstDayOfLastYear.' AS [Title] ,
    @FirstDayOfLastYear AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @FirstDayOfLastYear, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @FirstDayOfLastYear, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @FirstDayOfLastYear, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @FirstDayOfLastYear, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @FirstDayOfLastYear, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @FirstDayOfLastYear, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @FirstDayOfLastYear, 120) AS [ODBC]
UNION
SELECT  
    'p) LastDayOfLastYear.' AS [Title] ,
    @LastDayOfLastYear AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @LastDayOfLastYear, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @LastDayOfLastYear, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @LastDayOfLastYear, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @LastDayOfLastYear, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @LastDayOfLastYear, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @LastDayOfLastYear, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @LastDayOfLastYear, 120) AS [ODBC]
UNION
SELECT  
    'q) FirstDayOfNextYear.' AS [Title] ,
    @FirstDayOfNextYear AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @FirstDayOfNextYear, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @FirstDayOfNextYear, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @FirstDayOfNextYear, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @FirstDayOfNextYear, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @FirstDayOfNextYear, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @FirstDayOfNextYear, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @FirstDayOfNextYear, 120) AS [ODBC]
UNION
SELECT  
    'r) LastDayOfNextYear.' AS [Title] ,
    @LastDayOfNextYear AS [DATE (Server default)] ,
    CONVERT(VARCHAR, @LastDayOfNextYear, 127) AS [ISO8601] ,
    CONVERT(VARCHAR, @LastDayOfNextYear, 103) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [British&French] ,
    CONVERT(VARCHAR, @LastDayOfNextYear, 104) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [German] ,
    CONVERT(VARCHAR, @LastDayOfNextYear, 105) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Italian] ,
    CONVERT(VARCHAR, @LastDayOfNextYear, 111) + ' ' +  CONVERT(CHAR(5), @FirstDayOfCurrentWeek, 108) AS [Japan] ,
    CONVERT(VARCHAR, @LastDayOfNextYear, 100) AS [U.S.] ,
    CONVERT(VARCHAR, @LastDayOfNextYear, 120) AS [ODBC];

Run the above code to produce the following output:

enter image description here

If your country is missing, then it is because I don't know the code for it. It would be most helpful and appreciated if you could please edit this answer and add a new column for your country.

Thanks in advance.

Note: Bear in mind that today's date for me is 12th September, 2016.

References

For further reading on the ISO8601 international date standard, follow this link:

For further reading on the ODBC international date standard, follow this link:

To view the list of date formats I worked from, follow this link:

For further reading on the DATETIME data type, follow this link:

The difference between "require(x)" and "import x"

new ES6:

'import' should be used with 'export' key words to share variables/arrays/objects between js files:

export default myObject;

//....in another file

import myObject from './otherFile.js';

old skool:

'require' should be used with 'module.exports'

 module.exports = myObject;

//....in another file

var myObject = require('./otherFile.js');

Remove all HTMLtags in a string (with the jquery text() function)

If you need to remove the HTML but does not know if it actually contains any HTML tags, you can't use the jQuery method directly because it returns empty wrapper for non-HTML text.

$('<div>Hello world</div>').text(); //returns "Hello world"
$('Hello world').text(); //returns empty string ""

You must either wrap the text in valid HTML:

$('<div>' + 'Hello world' + '</div>').text();

Or use method $.parseHTML() (since jQuery 1.8) that can handle both HTML and non-HTML text:

var html = $.parseHTML('Hello world'); //parseHTML return HTMLCollection
var text = $(html).text(); //use $() to get .text() method

Plus parseHTML removes script tags completely which is useful as anti-hacking protection for user inputs.

$('<p>Hello world</p><script>console.log(document.cookie)</script>').text();
//returns "Hello worldconsole.log(document.cookie)"

$($.parseHTML('<p>Hello world</p><script>console.log(document.cookie)</script>')).text();
//returns "Hello world"

jquery mobile background image

None of the above worked for me using JQM 1.2.0

This did work for me:

.ui-page.ui-body-c {
    background: url(bg.png);
    background-repeat:no-repeat;
    background-position:center center;
    background-size:cover;  
}

T-test in Pandas

I simplify the code a little bit.

from scipy.stats import ttest_ind
ttest_ind(*my_data.groupby('Category')['value'].apply(lambda x:list(x)))

Encrypt & Decrypt using PyCrypto AES 256

Grateful for the other answers which inspired but didn't work for me.

After spending hours trying to figure out how it works, I came up with the implementation below with the newest PyCryptodomex library (it is another story how I managed to set it up behind proxy, on Windows, in a virtualenv.. phew)

Working on your implementation, remember to write down padding, encoding, encrypting steps (and vice versa). You have to pack and unpack keeping in mind the order.

import base64
import hashlib
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes

__key__ = hashlib.sha256(b'16-character key').digest()

def encrypt(raw):
    BS = AES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

    raw = base64.b64encode(pad(raw).encode('utf8'))
    iv = get_random_bytes(AES.block_size)
    cipher = AES.new(key= __key__, mode= AES.MODE_CFB,iv= iv)
    return base64.b64encode(iv + cipher.encrypt(raw))

def decrypt(enc):
    unpad = lambda s: s[:-ord(s[-1:])]

    enc = base64.b64decode(enc)
    iv = enc[:AES.block_size]
    cipher = AES.new(__key__, AES.MODE_CFB, iv)
    return unpad(base64.b64decode(cipher.decrypt(enc[AES.block_size:])).decode('utf8'))

How to wait until an element is present in Selenium?

FluentWait throws a NoSuchElementException is case of the confusion

org.openqa.selenium.NoSuchElementException;     

with

java.util.NoSuchElementException

in

.ignoring(NoSuchElementException.class)

Change image in HTML page every few seconds

Change setTimeout("changeImage()", 30000); to setInterval("changeImage()", 30000); and remove var timerid = setInterval(changeImage, 30000);.

Assigning multiple styles on an HTML element

In HTML the style tag has the following syntax:

style="property1:value1;property2:value2"

so in your case:

<h2 style="text-align:center;font-family:tahoma">TITLE</h2>

Hope this helps.

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

Note that git checkout --ours|--theirs will overwrite the files entirely, by choosing either theirs or ours version, which might be or might not be what you want to do (if you have any non-conflicted changes coming from the other side, they will be lost).

If instead you want to perform a three-way merge on the file, and only resolve the conflicted hunks using --ours|--theirs, while keeping non-conflicted hunks from both sides in place, you may want to resort to git merge-file; see details in this answer.

Convert int to ASCII and back in Python

Use hex(id)[2:] and int(urlpart, 16). There are other options. base32 encoding your id could work as well, but I don't know that there's any library that does base32 encoding built into Python.

Apparently a base32 encoder was introduced in Python 2.4 with the base64 module. You might try using b32encode and b32decode. You should give True for both the casefold and map01 options to b32decode in case people write down your shortened URLs.

Actually, I take that back. I still think base32 encoding is a good idea, but that module is not useful for the case of URL shortening. You could look at the implementation in the module and make your own for this specific case. :-)

video as site background? HTML 5

Take a look at my jquery videoBG plugin

http://syddev.com/jquery.videoBG/

Make any HTML5 video a site background... has an image fallback for browsers that don't support html5

Really easy to use

Let me know if you need any help.

Inline functions in C#?

No, there is no such construct in C#, but the .NET JIT compiler could decide to do inline function calls on JIT time. But i actually don't know if it is really doing such optimizations.
(I think it should :-))

How to get Month Name from Calendar?

This worked for me

        import java.text.SimpleDateFormat;
        import java.util.Calendar;


        Calendar cal = Calendar.getInstance();
        String currentdate=new SimpleDateFormat("dd-MMM").format(cal.getTime());

Editing in the Chrome debugger

  1. Place a breakpoint
  2. Right click on the breakpoint and select 'Edit breakpoint'
  3. Insert your code. Use SHIFT+ENTER to create a new line.

enter image description here

How to get an element's top position relative to the browser's viewport?

function inViewport(element) {
    let bounds = element.getBoundingClientRect();
    let viewWidth = document.documentElement.clientWidth;
    let viewHeight = document.documentElement.clientHeight;

    if (bounds['left'] < 0) return false;
    if (bounds['top'] < 0) return false;
    if (bounds['right'] > viewWidth) return false;
    if (bounds['bottom'] > viewHeight) return false;

    return true;
}

source

What's onCreate(Bundle savedInstanceState)

onCreate(Bundle) is called when the activity first starts up. You can use it to perform one-time initialization such as creating the user interface. onCreate() takes one parameter that is either null or some state information previously saved by the onSaveInstanceState.

Git conflict markers

The line (or lines) between the lines beginning <<<<<<< and ====== here:

<<<<<<< HEAD:file.txt
Hello world
=======

... is what you already had locally - you can tell because HEAD points to your current branch or commit. The line (or lines) between the lines beginning ======= and >>>>>>>:

=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt

... is what was introduced by the other (pulled) commit, in this case 77976da35a11. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.

Dump a NumPy array into a csv file

I believe you can also accomplish this quite simply as follows:

  1. Convert Numpy array into a Pandas dataframe
  2. Save as CSV

e.g. #1:

    # Libraries to import
    import pandas as pd
    import nump as np

    #N x N numpy array (dimensions dont matter)
    corr_mat    #your numpy array
    my_df = pd.DataFrame(corr_mat)  #converting it to a pandas dataframe

e.g. #2:

    #save as csv 
    my_df.to_csv('foo.csv', index=False)   # "foo" is the name you want to give
                                           # to csv file. Make sure to add ".csv"
                                           # after whatever name like in the code

Deserialize json object into dynamic object using Json.net

Yes it is possible. I have been doing that all the while.

dynamic Obj = JsonConvert.DeserializeObject(<your json string>);

It is a bit trickier for non native type. Suppose inside your Obj, there is a ClassA, and ClassB objects. They are all converted to JObject. What you need to do is:

ClassA ObjA = Obj.ObjA.ToObject<ClassA>();
ClassB ObjB = Obj.ObjB.ToObject<ClassB>();

Detect application heap size in Android

Debug.getNativeHeapSize() will do the trick, I should think. It's been there since 1.0, though.

The Debug class has lots of great methods for tracking allocations and other performance concerns. Also, if you need to detect a low-memory situation, check out Activity.onLowMemory().

ImportError: No module named site on Windows

If somebody will find that it's still not working under non-admin users:

Example error:

ImportError: No module named iso8601

you need to set '--always-unzip' option for easy_install:

easy_install --always-unzip python-keystoneclient

It will unzip your egg files and will allow import to find em.

How to check if a folder exists

File sourceLoc=new File("/a/b/c/folderName");
boolean isFolderExisted=false;
sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

  1. Stop your Apache server from running.
  2. Download the most recent version of XAMPP that contains a release of PHP 5.2.* from the SourceForge site linked at the apachefriends website.
  3. Rename the PHP file in your current installation (MAC OSX: /xamppfiles/modules/libphp.so) to something else (just in case).
  4. Copy the PHP file located in the same directory tree from the older XAMPP installation that you just downloaded, and place it in the directory of the file you just renamed.
  5. Start the Apache server, and generate a fresh version of phpinfo().
  6. Once you confirm that the PHP version has been lowered, delete the remaining files from the older XAMPP install.
  7. Fun ensues.

I just confirmed that this works when using a version of PHP 5.2.9 from XAMPP for OS X 1.0.1 (April 2009), and surgically moving it to XAMPP for OS X 1.7.2 (August 2009).

How to get an isoformat datetime string including the default timezone?

You can do it in Python 2.7+ with python-dateutil (which is insalled on Mac by default):

>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> datetime.now(tzlocal()).isoformat()
'2016-10-22T12:45:45.353489-03:00'

Or you if you want to convert from an existed stored string:

>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> from dateutil.parser import parse
>>> parse("2016-10-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-10-21T16:33:27.696173-03:00' <-- Atlantic Daylight Time (ADT) 
>>> parse("2016-01-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-01-21T16:33:27.696173-04:00' <-- Atlantic Standard Time (AST)

How to solve npm error "npm ERR! code ELIFECYCLE"

This solution is for Windows users.

You can open the node.js installer and give the installer some time to compute space requirements and then click next and click remove. This will remove node.js from your computer and again reopen the installer and install it in this path - C:\Windows\System32

or

Cleaning Cache and Node_module will work. Follow this steps:

  • npm cache clean --force
  • delete node_modules folder
  • delete package-lock.json file
  • npm install

Write variable to file, including name

You could do:

import inspect

mydict = {'one': 1, 'two': 2}

source = inspect.getsourcelines(inspect.getmodule(inspect.stack()[0][0]))[0]
print [x for x in source if x.startswith("mydict = ")]

Also: make sure not to shadow the dict builtin!

Cross-browser custom styling for file upload button

It's also easy to style the label if you are working with Bootstrap and LESS:

label {
    .btn();
    .btn-primary();

    > input[type="file"] {
        display: none;
    }
}

List files committed for a revision

To just get the list of the changed files with the paths, use

svn diff --summarize -r<rev-of-commit>:<rev-of-commit - 1>

For example:

svn diff --summarize -r42:41

should result in something like

M       path/to/modifiedfile
A       path/to/newfile

How to get the Full file path from URI

Snippet code when you receive file path.

 Uri fileUri = data.getData();
 FilePathHelper filePathHelper = new FilePathHelper();
 String path = "";
 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
       if (filePathHelper.getPathnew(fileUri, this) != null) {
              path = filePathHelper.getPathnew(fileUri, this).toLowerCase();
       } else {
              path = filePathHelper.getFilePathFromURI(fileUri, this).toLowerCase();
       }
 } else {
       path = filePathHelper.getPath(fileUri, this).toLowerCase();
 }

Bellow is a class which can be accessed by creating new object. you will also need to add to a dependency in gradel implementation 'org.apache.directory.studio:org.apache.commons.io:2.4'

public class FilePathHelper {

    public FilePathHelper(){

    }

    public String getMimeType(String url) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(url.replace(" ", ""));
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return type;
    }

    public String getFilePathFromURI(Uri contentUri, Context context) {
        //copy file and send new file path
        String fileName = getFileName(contentUri);
        if (!TextUtils.isEmpty(fileName)) {
            File copyFile = new File(context.getExternalCacheDir() + File.separator + fileName);
            copy(context, contentUri, copyFile);
            return copyFile.getAbsolutePath();
        }
        return null;
    }

    public void copy(Context context, Uri srcUri, File dstFile) {
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
            if (inputStream == null) return;
            OutputStream outputStream = new FileOutputStream(dstFile);
            IOUtils.copy(inputStream, outputStream);
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getPath(Uri uri, Context context) {
        String filePath = null;
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        if (isKitKat) {
            filePath = generateFromKitkat(uri, context);
        }

        if (filePath != null) {
            return filePath;
        }

        Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DATA}, null, null, null);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                filePath = cursor.getString(columnIndex);
            }
            cursor.close();
        }
        return filePath == null ? uri.getPath() : filePath;
    }

    @TargetApi(19)
    private String generateFromKitkat(Uri uri, Context context) {
        String filePath = null;
        if (DocumentsContract.isDocumentUri(context, uri)) {
            String wholeID = DocumentsContract.getDocumentId(uri);

            String id = wholeID.split(":")[1];

            String[] column = {MediaStore.Video.Media.DATA};
            String sel = MediaStore.Video.Media._ID + "=?";

            Cursor cursor = context.getContentResolver().
                    query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                            column, sel, new String[]{id}, null);


            int columnIndex = cursor.getColumnIndex(column[0]);

            if (cursor.moveToFirst()) {
                filePath = cursor.getString(columnIndex);
            }

            cursor.close();
        }
        return filePath;
    }

    public String getFileName(Uri uri) {
        if (uri == null) return null;
        String fileName = null;
        String path = uri.getPath();
        int cut = path.lastIndexOf('/');
        if (cut != -1) {
            fileName = path.substring(cut + 1);
        }
        return fileName;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public String getPathnew(Uri uri, Context context) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }

    public String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Something with exception - " + e.toString());
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}

How to set default value for column of new created table from select statement in 11g

You can specify the constraints and defaults in a CREATE TABLE AS SELECT, but the syntax is as follows

create table t1 (id number default 1 not null);
insert into t1 (id) values (2);

create table t2 (id default 1 not null)
as select * from t1;

That is, it won't inherit the constraints from the source table/select. Only the data type (length/precision/scale) is determined by the select.

What is the difference between using constructor vs getInitialState in React / React Native?

These days we don't have to call the constructor inside the component - we can directly call state={something:""}, otherwise previously first we have do declare constructor with super() to inherit every thing from React.Component class then inside constructor we initialize our state.

If using React.createClass then define initialize state with the getInitialState method.

Storing Python dictionaries

For completeness, we should include ConfigParser and configparser which are part of the standard library in Python 2 and 3, respectively. This module reads and writes to a config/ini file and (at least in Python 3) behaves in a lot of ways like a dictionary. It has the added benefit that you can store multiple dictionaries into separate sections of your config/ini file and recall them. Sweet!

Python 2.7.x example.

import ConfigParser

config = ConfigParser.ConfigParser()

dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
dict3 = {'x':1, 'y':2, 'z':3}

# Make each dictionary a separate section in the configuration
config.add_section('dict1')
for key in dict1.keys():
    config.set('dict1', key, dict1[key])
   
config.add_section('dict2')
for key in dict2.keys():
    config.set('dict2', key, dict2[key])

config.add_section('dict3')
for key in dict3.keys():
    config.set('dict3', key, dict3[key])

# Save the configuration to a file
f = open('config.ini', 'w')
config.write(f)
f.close()

# Read the configuration from a file
config2 = ConfigParser.ConfigParser()
config2.read('config.ini')

dictA = {}
for item in config2.items('dict1'):
    dictA[item[0]] = item[1]

dictB = {}
for item in config2.items('dict2'):
    dictB[item[0]] = item[1]

dictC = {}
for item in config2.items('dict3'):
    dictC[item[0]] = item[1]

print(dictA)
print(dictB)
print(dictC)

Python 3.X example.

import configparser

config = configparser.ConfigParser()

dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
dict3 = {'x':1, 'y':2, 'z':3}

# Make each dictionary a separate section in the configuration
config['dict1'] = dict1
config['dict2'] = dict2
config['dict3'] = dict3

# Save the configuration to a file
f = open('config.ini', 'w')
config.write(f)
f.close()

# Read the configuration from a file
config2 = configparser.ConfigParser()
config2.read('config.ini')

# ConfigParser objects are a lot like dictionaries, but if you really
# want a dictionary you can ask it to convert a section to a dictionary
dictA = dict(config2['dict1'] )
dictB = dict(config2['dict2'] )
dictC = dict(config2['dict3'])

print(dictA)
print(dictB)
print(dictC)

Console output

{'key2': 'keyinfo2', 'key1': 'keyinfo'}
{'k1': 'hot', 'k2': 'cross', 'k3': 'buns'}
{'z': '3', 'y': '2', 'x': '1'}

Contents of config.ini

[dict1]
key2 = keyinfo2
key1 = keyinfo

[dict2]
k1 = hot
k2 = cross
k3 = buns

[dict3]
z = 3
y = 2
x = 1

Intercept page exit event

See this article. The feature you are looking for is the onbeforeunload

sample code:

  <script language="JavaScript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
  }
</script>

Format LocalDateTime with Timezone in Java8

The prefix "Local" in JSR-310 (aka java.time-package in Java-8) does not indicate that there is a timezone information in internal state of that class (here: LocalDateTime). Despite the often misleading name such classes like LocalDateTime or LocalTime have NO timezone information or offset.

You tried to format such a temporal type (which does not contain any offset) with offset information (indicated by pattern symbol Z). So the formatter tries to access an unavailable information and has to throw the exception you observed.

Solution:

Use a type which has such an offset or timezone information. In JSR-310 this is either OffsetDateTime (which contains an offset but not a timezone including DST-rules) or ZonedDateTime. You can watch out all supported fields of such a type by look-up on the method isSupported(TemporalField).. The field OffsetSeconds is supported in OffsetDateTime and ZonedDateTime, but not in LocalDateTime.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);

How to use jquery $.post() method to submit form values

Yor $.post has no data. You need to pass the form data. You can use serialize() to post the form data. Try this

$("#post-btn").click(function(){
    $.post("process.php", $('#reg-form').serialize() ,function(data){
        alert(data);
    });
});

mailto link multiple body lines

  1. Use a single body parameter within the mailto string
  2. Use %0D%0A as newline

The mailto URI Scheme is specified by by RFC2368 (July 1998) and RFC6068 (October 2010).
Below is an extract of section 5 of this last RFC:

[...] line breaks in the body of a message MUST be encoded with "%0D%0A".
Implementations MAY add a final line break to the body of a message even if there is no trailing "%0D%0A" in the body [...]

See also in section 6 the example from the same RFC:

<mailto:[email protected]?body=send%20current-issue%0D%0Asend%20index>

The above mailto body corresponds to:

send current-issue
send index

Get content of a cell given the row and column numbers

Try =index(ARRAY, ROW, COLUMN)

where: Array: select the whole sheet Row, Column: Your row and column references

That should be easier to understand to those looking at the formula.

Including one C source file in another?

Numerous other answers have more than covered how you can do this but why you probably should not in normal circumstances. That said, I will add why I've done it in the past.

In embedded development, it's common to have silicon vendor source code as part of your compiled files. The problem is those vendors likely don't have the same style guides or standard warning/error flag settings as your organization.

So, you can create a local source file that includes the vendor source code and then compile this wrapper C file instead to suppress any issues in the included source as well as any headers included by that source. As an example:

/**
 * @file   vendor_wrap.c
 * @brief  vendor source code wrapper to prevent warnings
 */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wnested-externs"
#include "vendor_source_code.c"
#pragma GCC diagnostic pop

This allows you to use less complicated Make scripting with a standard set of compiler flags and settings with specific exceptions in the code rather than have custom flags for some files in the scripting.

gcc main.c vendor_wrap.c -o $(CFLAGS) main.out

How to get the hostname of the docker host from inside a docker container on that host without env vars

Another option that worked for me was to bind the network namespace of the host to the docker.

By adding:

docker run --net host

Git credential helper - update password

Working solution for Windows:

Control Panel > User Accounts > Credential Manager > Generic Credentials

enter image description here

MySQL: selecting rows where a column is null

I had the same issue when converting databases from Access to MySQL (using vb.net to communicate with the database).

I needed to assess if a field (field type varchar(1)) was null.

This statement worked for my scenario:

SELECT * FROM [table name] WHERE [field name] = ''

Best way to serialize/unserialize objects in JavaScript?

The browser's native JSON API may not give you back your idOld function after you call JSON.stringify, however, if can stringify your JSON yourself (maybe use Crockford's json2.js instead of browser's API), then if you have a string of JSON e.g.

var person_json = "{ \"age:\" : 20, \"isOld:\": false, isOld: function() { return this.age > 60; } }";

then you can call

eval("(" + person + ")") 

, and you will get back your function in the json object.

Python Database connection Close

You can define a DB class as below. Also, as andrewf suggested, use a context manager for cursor access.I'd define it as a member function. This way it keeps the connection open across multiple transactions from the app code and saves unnecessary reconnections to the server.

import pyodbc

class MS_DB():
    """ Collection of helper methods to query the MS SQL Server database.
    """

    def __init__(self, username, password, host, port=1433, initial_db='dev_db'):
        self.username = username
        self._password = password
        self.host = host
        self.port = str(port)
        self.db = initial_db
        conn_str = 'DRIVER=DRIVER=ODBC Driver 13 for SQL Server;SERVER='+ \
                    self.host + ';PORT='+ self.port +';DATABASE='+ \
                    self.db +';UID='+ self.username +';PWD='+ \ 
                    self._password +';'
        print('Connected to DB:', conn_str)
        self._connection = pyodbc.connect(conn_str)        
        pyodbc.pooling = False

    def __repr__(self):
        return f"MS-SQLServer('{self.username}', <password hidden>, '{self.host}', '{self.port}', '{self.db}')"

    def __str__(self):
        return f"MS-SQLServer Module for STP on {self.host}"

    def __del__(self):
        self._connection.close()
        print("Connection closed.")

    @contextmanager
    def cursor(self, commit: bool = False):
        """
        A context manager style of using a DB cursor for database operations. 
        This function should be used for any database queries or operations that 
        need to be done. 

        :param commit:
        A boolean value that says whether to commit any database changes to the database. Defaults to False.
        :type commit: bool
        """
        cursor = self._connection.cursor()
        try:
            yield cursor
        except pyodbc.DatabaseError as err:
            print("DatabaseError {} ".format(err))
            cursor.rollback()
            raise err
        else:
            if commit:
                cursor.commit()
        finally:
            cursor.close()

ms_db = MS_DB(username='my_user', password='my_secret', host='hostname')
with ms_db.cursor() as cursor:
        cursor.execute("SELECT @@version;")
        print(cur.fetchall())

C - The %x format specifier

Break-down:

  • 8 says that you want to show 8 digits
  • 0 that you want to prefix with 0's instead of just blank spaces
  • x that you want to print in lower-case hexadecimal.

Quick example (thanks to Grijesh Chauhan):

#include <stdio.h>
int main() {
    int data = 29;
    printf("%x\n", data);    // just print data
    printf("%0x\n", data);   // just print data ('0' on its own has no effect)
    printf("%8x\n", data);   // print in 8 width and pad with blank spaces
    printf("%08x\n", data);  // print in 8 width and pad with 0's

    return 0;
}

Output:

1d
1d
      1d
0000001d

Also see http://www.cplusplus.com/reference/cstdio/printf/ for reference.

Reference — What does this symbol mean in PHP?

Incrementing / Decrementing Operators

++ increment operator

-- decrement operator

Example    Name              Effect
---------------------------------------------------------------------
++$a       Pre-increment     Increments $a by one, then returns $a.
$a++       Post-increment    Returns $a, then increments $a by one.
--$a       Pre-decrement     Decrements $a by one, then returns $a.
$a--       Post-decrement    Returns $a, then decrements $a by one.

These can go before or after the variable.

If put before the variable, the increment/decrement operation is done to the variable first then the result is returned. If put after the variable, the variable is first returned, then the increment/decrement operation is done.

For example:

$apples = 10;
for ($i = 0; $i < 10; ++$i) {
    echo 'I have ' . $apples-- . " apples. I just ate one.\n";
}

Live example

In the case above ++$i is used, since it is faster. $i++ would have the same results.

Pre-increment is a little bit faster because it really increments the variable and after that 'returns' the result. Post-increment creates a special variable, copies there the value of the first variable and only after the first variable is used, replaces its value with second's.

However, you must use $apples--, since first, you want to display the current number of apples, and then you want to subtract one from it.

You can also increment letters in PHP:

$i = "a";
while ($i < "c") {
    echo $i++;
}

Once z is reached aa is next, and so on.

Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.


Stack Overflow Posts:

How do I correctly clone a JavaScript object?

Here is a function you can use.

function clone(obj) {
    if(obj == null || typeof(obj) != 'object')
        return obj;    
    var temp = new obj.constructor(); 
    for(var key in obj)
        temp[key] = clone(obj[key]);    
    return temp;
}

How to set width of a div in percent in JavaScript?

Also you can use .prop() and it should be better because

Since jQuery 1.6, these properties can no longer be set with the .attr() method. They do not have corresponding attributes and are only properties.

$(elem).prop('width', '100%');
$(elem).prop('height', '100%');

Install tkinter for Python

tk-devel also needs to be installed in my case

yum install -y tkinter tk-devel

install these and rebuild python

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

try to do this command

sudo fuser -k 443/tcp
service nginx restart

How is the default submit button on an HTML form determined?

From your comments:

A consequence is that, if you have multiple forms submitting to the same script, you can't rely on submit buttons to distinguish them.

I drop an <input type="hidden" value="form_name" /> into each form.

If submitting with javascript: add submit events to forms, not click events to their buttons. Saavy users don't touch their mouse very often.

Laravel 5.4 create model, controller and migration in single artisan command

To make mode, controllers with resources, You can type CMD as follows :

 php artisan make:model Todo -mcr

or you can check by typing

php artisan help make:model

where you can get all the ideas

Easiest way to ignore blank lines when reading a file in Python

@S.Lott

The following code processes lines one at a time and produces a result that isn't memory eager:

filename = 'english names.txt'

with open(filename) as f_in:
    lines = (line.rstrip() for line in f_in)
    lines = (line for line in lines if line)
    the_strange_sum = 0
    for l in lines:
        the_strange_sum += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.find(l[0])

print the_strange_sum

So the generator (line.rstrip() for line in f_in) is quite the same acceptable than the nonblank_lines() function.

How can I limit ngFor repeat to some number of items in Angular?

In addition to @Gunter's answer, you can use trackBy to improve the performance. trackBy takes a function that has two arguments: index and item. You can return a unique value in the object from the function. It will stop re-rendering already displayed items in ngFor. In your html add trackBy as below.

<li *ngFor="let item of list; trackBy: trackByFn;let i=index" class="dropdown-item" (click)="onClick(item)">
  <template [ngIf]="i<11">{{item.text}}</template>
</li>

And write a function like this in your .ts file.

trackByfn(index, item) { 
  return item.uniqueValue;
}

Javascript swap array elements

Typescript solution that clones the array instead of mutating existing one

export function swapItemsInArray<T>(items: T[], indexA: number, indexB: number): T[] {
  const itemA = items[indexA];

  const clone = [...items];

  clone[indexA] = clone[indexB];
  clone[indexB] = itemA;

  return clone;
}

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

This error pops up, if you try to create a web worker with data URI scheme.

var w = new Worker('data:text/javascript;charset=utf-8,onmessage%20%3D%20function()%20%7B%20postMessage(%22pong%22)%3B%20%7D'); w.postMessage('ping');

It's not allowed according to the standard: http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html#dom-worker

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

I was getting the same error, for me, it was because API was just returning a string however in fetch call I was expecting json :

response => response.json()

Returning json from API resolved the issue for me, if your API is not supposed to return json then simply don't do response.json()

Failing to run jar file from command line: “no main manifest attribute”

In Eclipse: right-click on your project -> Export -> JAR file

At last page with options (when there will be no Next button active) you will see settings for Main class:. You need to set here class with main method which should be executed by default (like when JAR file will be double-clicked).

Android + Pair devices via bluetooth programmatically

Edit: I have just explained logic to pair here. If anybody want to go with the complete code then see my another answer. I have answered here for logic only but I was not able to explain properly, So I have added another answer in the same thread.

Try this to do pairing:

If you are able to search the devices then this would be your next step

ArrayList<BluetoothDevice> arrayListBluetoothDevices = NEW ArrayList<BluetoothDevice>;

I am assuming that you have the list of Bluetooth devices added in the arrayListBluetoothDevices:

BluetoothDevice bdDevice;
bdDevice = arrayListBluetoothDevices.get(PASS_THE_POSITION_TO_GET_THE_BLUETOOTH_DEVICE);

Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
    Log.i("Log","Paired");
}
} catch (Exception e) 
{
    e.printStackTrace(); 
}

The createBond() method:

public boolean createBond(BluetoothDevice btDevice)  
    throws Exception  
    { 
        Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
        Method createBondMethod = class1.getMethod("createBond");  
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
        return returnValue.booleanValue();  
    }  

Add this line into your Receiver in the ACTION_FOUND

if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    arrayListBluetoothDevices.add(device);
                }

How can I get the current date and time in UTC or GMT in Java?

SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));

//Local time zone   
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

//Time in GMT
return dateFormatLocal.parse( dateFormatGmt.format(new Date()) );

Can we call the function written in one JavaScript in another JS file?

yes you can . you need to refer both JS file to the .aspx page

<script language="javascript" type="text/javascript" src="JScript1.js">
 </script>

    <script language="javascript" type="text/javascript" src="JScript2.js">
    </script>

JScript1.js

function ani1() {
    alert("1");
    ani2();
}
JScript2.js
function ani2() {
    alert("2");
}

How to clear a data grid view

You could take this next instruction and would do the work with lack of perfomance. If you want to see the effect of that, put one of the 2 next instructions (Technically similars) where you need to clear the DataGridView into a try{} catch(...){} finally block and wait what occurs.

     while (dataGridView1.Rows.Count > 1)
    {
        dataGridView1.Rows.RemoveAt(0);
    }

    foreach (object _Cols in dataGridView1.Columns)
    {
        dataGridView1.Columns.RemoveAt(0);
    }

You improve this task but its not enough, there is a problem to reset a DataGridView, because of the colums that remains in the DataGridView object. Finally I suggest, the best way i've implemented in my home practice is to handle this gridView as a file with rows, columns: a record collection based on the match between rows and columns. If you can improve, then take your own choice a) or b): foreach or while.

     //(a): With foreach 
    foreach (object _Cols in dataGridView1.Columns)
    {
        dataGridView1.Columns.RemoveAt(0);
    }

    foreach(object _row in dataGridView1.Rows){
        dataGridView1.Rows.RemoveAt(0);
    }

    //(b): With foreach 
    while (dataGridView1.Rows.Count > 1)
    {
        dataGridView1.Rows.RemoveAt(0);
    }
    while (dataGridView1.Columns.Count > 0)
    {
        dataGridView1.Columns.RemoveAt(0);
    }

Well, as a recomendation Never in your life delete the columns first, the order is before the rows after the cols, because logically the columns where created first and then the rows.It would be a penalty in terms of correct analisys.

     foreach (object _Cols in dataGridView1.Columns)
    {
        dataGridView1.Columns.RemoveAt(0);
    }
    foreach (object _row in dataGridView1.Rows)
    {
        dataGridView1.Rows.RemoveAt(0);
    }
    while (dataGridView1.Rows.Count > 1)
    {
        dataGridView1.Rows.RemoveAt(0);
    }

    while (dataGridView1.Columns.Count > 0)
    {
        dataGridView1.Columns.RemoveAt(0);
    }

Then, Put it inside a function or method.

 private void ClearDataGridViewLoopWhile()
{           
    while (dataGridView1.Rows.Count > 1)
    {
        dataGridView1.Rows.RemoveAt(0);
    }

    while (dataGridView1.Columns.Count > 0)
    {
        dataGridView1.Columns.RemoveAt(0);
    }
}

private void ClearDataGridViewForEach()
{
    foreach (object _Cols in dataGridView1.Columns)
    {
        dataGridView1.Columns.RemoveAt(0);
    }
    foreach (object _row in dataGridView1.Rows)
    {
        dataGridView1.Rows.RemoveAt(0);
    }
}

Finally, call your new function ClearDataGridViewLoopWhile(); or ClearDataGridViewForEach(); where you need to use it, but its recomended when you are making queries and changing over severall tables that will load with diferents header names in the grieView. But if you want preserve headers here there is a solution given.

What do 'real', 'user' and 'sys' mean in the output of time(1)?

I want to mention some other scenario when the real-time is much much bigger than user + sys. I've created a simple server which respondes after a long time

real 4.784
user 0.01s
sys  0.01s

the issue is that in this scenario the process waits for the response which is not on the user site nor in the system.

Something similar happens when you run the find command. In that case, the time is spent mostly on requesting and getting a response from SSD.

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

Adding horizontal spacing between divs in Bootstrap 3

From what I understand you want to make a navigation bar or something similar to it. What I recommend doing is making a list and editing the items from there. Just try this;

<ul>
    <li class='item col-md-12 panel' id='gameplay-title'>Title</li>
    <li class='item col-md-6 col-md-offset-3 panel' id='gameplay-scoreboard'>Scoreboard</li>
</ul>

And so on... To add more categories add another ul in there. Now, for the CSS you just need this;

ul {
    list-style: none;
}
.item {
    display: inline;
    padding-right: 20px;
}

Can Selenium WebDriver open browser windows silently in the background?

For running without any browser, you can run it in headless mode.

I show you one example in Python that is working for me right now

from selenium import webdriver


options = webdriver.ChromeOptions()
options.add_argument("headless")
self.driver = webdriver.Chrome(executable_path='/Users/${userName}/Drivers/chromedriver', chrome_options=options)

I also add you a bit more of info about this in the official Google website https://developers.google.com/web/updates/2017/04/headless-chrome

changing textbox border colour using javascript

I'm agree with Vicente Plata you should try using jQuery IMHO is the best javascript library. You can create a class in your CSS file and just do the following with jquery:

$('#fName').addClass('name_of_the_class'); 

and that's all, and of course you won't be worried about incompatibility of the browsers, that's jquery's team problem :D LOL

Which Radio button in the group is checked?

You can wire the CheckedEvents of all the buttons against one handler. There you can easily get the correct Checkbox.

// Wire all events into this.
private void AllCheckBoxes_CheckedChanged(Object sender, EventArgs e) {
    // Check of the raiser of the event is a checked Checkbox.
    // Of course we also need to to cast it first.
    if (((RadioButton)sender).Checked) {
        // This is the correct control.
        RadioButton rb = (RadioButton)sender;
    }
}

Excel formula to get ranking position

Try this in your forth column

=COUNTIF(B:B; ">" & B2) + 1

Replace B2 with B3 for next row and so on.

What this does is it counts how many records have more points then current one and then this adds current record position (+1 part).

Correct location of openssl.cnf file

/usr/local/ssl/openssl.cnf

This is a local installation. You downloaded and built OpenSSL taking the default prefix, of you configured with ./config --prefix=/usr/local/ssl or ./config --openssldir=/usr/local/ssl.

You will use this if you use the OpenSSL in /usr/local/ssl/bin. That is, /usr/local/ssl/openssl.cnf will be used when you issue:

/usr/local/ssl/bin/openssl s_client -connect localhost:443 -tls1 -servername localhost

/usr/lib/ssl/openssl.cnf

This is where Ubuntu places openssl.cnf for the OpenSSL they provide.

You will use this if you use the OpenSSL in /usr/bin. That is, /usr/lib/ssl/openssl.cnf will be used when you issue:

openssl s_client -connect localhost:443 -tls1 -servername localhost

/etc/ssl/openssl.cnf

I don't know when this is used. The stuff in /etc/ssl is usually certificates and private keys, and it sometimes contains a copy of openssl.cnf. But I've never seen it used for anything.


Which is the main/correct one that I should use to make changes?

From the sounds of it, you should probably add the engine to /usr/lib/ssl/openssl.cnf. That ensures most "off the shelf" gear will use the new engine.

After you do that, add it to /usr/local/ssl/openssl.cnf also because copy/paste is easy.


Here's how to see which openssl.cnf directory is associated with a OpenSSL installation. The library and programs look for openssl.cnf in OPENSSLDIR. OPENSSLDIR is a configure option, and its set with --openssldir.

I'm on a MacBook with 3 different OpenSSL's (Apple's, MacPort's and the one I build):

# Apple    
$ /usr/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/System/Library/OpenSSL"

# MacPorts
$ /opt/local/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/opt/local/etc/openssl"

# My build of OpenSSL
$ openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/usr/local/ssl/darwin"

I have an Ubuntu system and I have installed openssl.

Just bike shedding, but be careful of Ubuntu's version of OpenSSL. It disables TLSv1.1 and TLSv1.2, so you will only have clients capable of older cipher suites; and you will not be able to use newer ciphers like AES/CTR (to replace RC4) and elliptic curve gear (like ECDHE_ECDSA_* and ECDHE_RSA_*). See Ubuntu 12.04 LTS: OpenSSL downlevel version is 1.0.0, and does not support TLS 1.2 in Launchpad.

EDIT: Ubuntu enabled TLS 1.1 and TLS 1.2 recently. See Comment 17 on the bug report.

Array versus List<T>: When to use which?

Rather than going through a comparison of the features of each data type, I think the most pragmatic answer is "the differences probably aren't that important for what you need to accomplish, especially since they both implement IEnumerable, so follow popular convention and use a List until you have a reason not to, at which point you probably will have your reason for using an array over a List."

Most of the time in managed code you're going to want to favor collections being as easy to work with as possible over worrying about micro-optimizations.

How to import js-modules into TypeScript file?

I've been facing this problem for long but what this solves my problem Go inside the tsconfig.json and add the following under compilerOptions

{
  "compilerOptions": {
      ...
      "allowJs": true
      ...
  }
}

SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN'

An expression of non-boolean type specified in a context where a condition is expected

I also got this error when I forgot to add ON condition when specifying my join clause.

How to navigate back to the last cursor position in Visual Studio Code?

With VSCode 1.43 (Q1 2020), those Alt+? / Alt+?, or Ctrl+- / Ctrl+Shift+- will also... preserve selection.

See issue 89699:

Benjamin Pasero (bpasero) adds:

going back/forward restores selections as they were.

Note that in order to get a history entry there needs to be at least 10 lines between the positions to consider the entry as new entry.

Go back/Forward selection -- https://user-images.githubusercontent.com/900690/73729489-6ca7da80-4735-11ea-9345-1228f0302110.gif

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

For CentOS, run this: sudo yum install libXext libSM libXrender

keycloak Invalid parameter: redirect_uri

If you're trying to redirect to the keycloak login page after logout (as I was), that is not allowed by default but also needs to be configured in the "Valid Redirect URIs" setting in the admin console of your client.

How to exclude 0 from MIN formula Excel

if all your value are positive, you can do -max(-n)

How to enable mbstring from php.ini?

All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.

If you have accidentally removed DLL file from php/ext folder, just add it back (get the copy from XAMPP zip archive - its downloadable).

If you have deleted the accompanying INI configuration line from php.ini file, add it back as well:

extension=php_mbstring.dll

Also, ensure to restart your webserver (Apache) using XAMPP control panel.

Additional Info on Enabling PHP Extensions

  • install extension (e.g. put php_mbstring.dll into /XAMPP/php/ext directory)
  • in php.ini, ensure extension directory specified (e.g. extension_dir = "ext")
  • ensure correct build of DLL file (e.g. 32bit thread-safe VC9 only works with DLL files built using exact same tools and configuration: 32bit thread-safe VC9)
  • ensure PHP API versions match (If not, once you restart the webserver you will receive related error.)

Crontab Day of the Week syntax

    :-) Sunday    |    0  ->  Sun
                  |  
        Monday    |    1  ->  Mon
       Tuesday    |    2  ->  Tue
     Wednesday    |    3  ->  Wed
      Thursday    |    4  ->  Thu
        Friday    |    5  ->  Fri
      Saturday    |    6  ->  Sat
                  |  
    :-) Sunday    |    7  ->  Sun

As you can see above, and as said before, the numbers 0 and 7 are both assigned to Sunday. There are also the English abbreviated days of the week listed, which can also be used in the crontab.

Examples of Number or Abbreviation Use

15 09 * * 5,6,0             command
15 09 * * 5,6,7             command
15 09 * * 5-7               command
15 09 * * Fri,Sat,Sun       command

The four examples do all the same and execute a command every Friday, Saturday, and Sunday at 9.15 o'clock.

In Detail

Having two numbers 0 and 7 for Sunday can be useful for writing weekday ranges starting with 0 or ending with 7. So you can write ranges starting with Sunday or ending with it, like 0-2 or 5-7 for example (ranges must start with the lower number and must end with the higher). The abbreviations cannot be used to define a weekday range.

Styling HTML5 input type number

Also you can replace size attribute by a style attribute:
<input type="number" name="numericInput" style="width: 50px;" min="0" max="18" value="0" />

A method to count occurrences in a list

How about something like this ...

var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };

var g = l1.GroupBy( i => i );

foreach( var grp in g )
{
  Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}

Edit per comment: I will try and do this justice. :)

In my example, it's a Func<int, TKey> because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int> (a grouping of ints keyed by an int). If I changed it to (i => i.ToString() ) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...

private string SampleMethod( int i )
{
  // magically return "One" if i == 1, "Two" if i == 2, etc.
}

So, that's a Func that would take an int and return a string, just like ...

i =>  // magically return "One" if i == 1, "Two" if i == 2, etc. 

But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.

Test file upload using HTTP PUT method

If you're using PHP you can test your PUT upload using the code below:

#Initiate cURL object
$curl = curl_init();
#Set your URL
curl_setopt($curl, CURLOPT_URL, 'https://local.simbiat.ru');
#Indicate, that you plan to upload a file
curl_setopt($curl, CURLOPT_UPLOAD, true);
#Indicate your protocol
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#Set flags for transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
#Disable header (optional)
curl_setopt($curl, CURLOPT_HEADER, false);
#Set HTTP method to PUT
curl_setopt($curl, CURLOPT_PUT, 1);
#Indicate the file you want to upload
curl_setopt($curl, CURLOPT_INFILE, fopen('path_to_file', 'rb'));
#Indicate the size of the file (it does not look like this is mandatory, though)
curl_setopt($curl, CURLOPT_INFILESIZE, filesize('path_to_file'));
#Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#Execute
curl_exec($curl);

Converting a vector<int> to string

Maybe std::ostream_iterator and std::ostringstream:

#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iostream>

int main()
{
  std::vector<int> vec;
  vec.push_back(1);
  vec.push_back(4);
  vec.push_back(7);
  vec.push_back(4);
  vec.push_back(9);
  vec.push_back(7);

  std::ostringstream oss;

  if (!vec.empty())
  {
    // Convert all but the last element to avoid a trailing ","
    std::copy(vec.begin(), vec.end()-1,
        std::ostream_iterator<int>(oss, ","));

    // Now add the last element with no delimiter
    oss << vec.back();
  }

  std::cout << oss.str() << std::endl;
}

jQuery Validate Required Select

You only need to put validate[required] as class of this select and then put a option with value=""

for example:

<select class="validate[required]">
  <option value="">Choose...</option>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

Getting multiple selected checkbox values in a string in javascript and PHP

This is a variation to get all checked checkboxes in all_location_id without using an "if" statement

var all_location_id = document.querySelectorAll('input[name="location[]"]:checked');

var aIds = [];

for(var x = 0, l = all_location_id.length; x < l;  x++)
{
    aIds.push(all_location_id[x].value);
}

var str = aIds.join(', ');

console.log(str);

no default constructor exists for class

Because you have this:

Blowfish(BlowfishAlgorithm algorithm);

It's not a default constructor. The default constructor is one which takes no parameters. i.e.

Blowfish();

BATCH file asks for file or folder

echo f | xcopy /s/y J:\"My Name"\"FILES IN TRANSIT"\JOHN20101126\"Missing file"\Shapes.atc C:\"Documents and Settings"\"His name"\"Application Data"\Autodesk\"AutoCAD 2010"\"R18.0"\enu\Support\Shapes.atc

Graphical HTTP client for windows

https://play.google.com/store/apps/details?id=com.snmba.restclient

works from Android Tablets & Phones. Flexible enough to try various combinations.

Efficiently getting all divisors of a given number

for( int i = 1; i * i <= num; i++ )
{
/* upto sqrt is because every divisor after sqrt
    is also found when the number is divided by i.
   EXAMPLE like if number is 90 when it is divided by 5
    then you can also see that 90/5 = 18
    where 18 also divides the number.
   But when number is a perfect square
    then num / i == i therefore only i is the factor
*/

Reminder - \r\n or \n\r?

\r\n

Odd to say I remember it because it is the opposite of the typewriter I used.
Well if it was normal I had no need to remember it... :-)

typewriter from wikipedia *Image from Wikipedia

In the typewriter when you finish to digit the line you use the carriage return lever, that before makes roll the drum, the newline, and after allow you to manually operate the carriage return.

You can listen from this record from freesound.org the sound of the paper feeding in the beginning, and at around -1:03 seconds from the end, after the bell warning for the end of the line sound of the drum that rolls and after the one of the carriage return.

pyplot scatter plot marker size

If the size of the circles corresponds to the square of the parameter in s=parameter, then assign a square root to each element you append to your size array, like this: s=[1, 1.414, 1.73, 2.0, 2.24] such that when it takes these values and returns them, their relative size increase will be the square root of the squared progression, which returns a linear progression.

If I were to square each one as it gets output to the plot: output=[1, 2, 3, 4, 5]. Try list interpretation: s=[numpy.sqrt(i) for i in s]

How to stop line breaking in vim

It is correct that set nowrap will allow you to paste in a long line without vi/vim adding newlines, but then the line is not visually wrapped for easy reading. It is instead just one long line that you have to scroll through.

To have the line visually wrap but not have newline characters inserted into it, have set wrap (which is probably default so not needed to set) and set textwidth=0.

On some systems the setting of textwidth=0 is default. If you don't find that to be the case, add set textwidth=0 to your .exrc file so that it becomes your user's default for all vi/vim sessions.

Decimal number regular expression, where digit after decimal is optional

What you asked is already answered so this is just an additional info for those who want only 2 decimal digits if optional decimal point is entered:

^\d+(\.\d{2})?$

^ : start of the string
\d : a digit (equal to [0-9])
+ : one and unlimited times

Capturing Group (.\d{2})?
? : zero and one times . : character .
\d : a digit (equal to [0-9])
{2} : exactly 2 times
$ : end of the string

1 : match
123 : match
123.00 : match
123. : no match
123.. : no match
123.0 : no match
123.000 : no match
123.00.00 : no match

jQuery UI accordion that keeps multiple sections open?

You just use jquery each() function ;

$(function() {
    $( ".selector_class_name" ).each(function(){
        $( this ).accordion({
          collapsible: true, 
          active:false,
          heightStyle: "content"
        });
    });
});

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

I just noticed recently that when I used write() on a socket in Windows, it almost works (the FD passed to write() isn't the same as the one passed to send(); I used _open_osfhandle() to get the FD to pass to write()). However, it didn't work when I tried to send binary data that included character 10. write() somewhere inserted character 13 before this. Changing it to send() with a flags parameter of 0 fixed that problem. read() could have the reverse problem if 13-10 are consecutive in the binary data, but I haven't tested it. But that appears to be another possible difference between send() and write().

Chart.js v2 - hiding grid lines

I found a solution that works for hiding the grid lines in a Line chart.

Set the gridLines color to be the same as the div's background color.

var options = {
    scales: {
        xAxes: [{
            gridLines: {
                color: "rgba(0, 0, 0, 0)",
            }
        }],
        yAxes: [{
            gridLines: {
                color: "rgba(0, 0, 0, 0)",
            }   
        }]
    }
}

or use

var options = {
    scales: {
        xAxes: [{
            gridLines: {
                display:false
            }
        }],
        yAxes: [{
            gridLines: {
                display:false
            }   
        }]
    }
}

How to force link from iframe to be opened in the parent window

Use target-attribute:

<a target="_parent" href="http://url.org">link</a>