Programs & Examples On #Post build

Post Build exited with code 1

My reason for the Code 1 was that the target folder was read only. Hope this helps someone! I had a post build event to do a copy from one directory to another and the destination was read only. So I just went and unchecked the read-only attribute on the directory and all its subdirectories! Just make sure that its a directory that's safe to do so!

shared global variables in C

If you're sharing code between C and C++, remember to add the following to the shared.hfile:

#ifdef __cplusplus
extern "C" {

extern int my_global;
/* other extern declarations ... */

#ifdef __cplusplus

jquery: change the URL address without redirecting?

No, because that would open up the floodgates for phishing. The only part of the URI you can change is the fragment (everything after the #). You can do so by setting window.location.hash.

Find a string by searching all tables in SQL Server Management Studio 2008

I have written a SP for the this which returns the search results in form of Table name, the Column names in which the search keyword string was found as well as the searches the corresponding rows as shown in below screen shot.

Sample Search Result

This might not be the most efficient solution but you can always modify and use it according to your need.

IF OBJECT_ID('sp_KeywordSearch', 'P') IS NOT NULL
    DROP PROC sp_KeywordSearch

CREATE PROCEDURE sp_KeywordSearch @KeyWord NVARCHAR(100)
        (TableName NVARCHAR(300),
         ColumnName NVARCHAR(MAX))

        @TableName NVARCHAR(300),
        @ColumnName NVARCHAR(300),
        @Count INT

    DECLARE @tableCursor CURSOR

            '] AS NVARCHAR(MAX)) LIKE ''%' + @KeyWord + N'%''',
            C.TABLE_SCHEMA = 'dbo' AND
            C.DATA_TYPE NOT IN ('image', 'timestamp')

    OPEN @tableCursor
    FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName

        SET @Count = 0

        EXEC sys.sp_executesql
            N'@Count INT OUTPUT',
            @Count OUTPUT

        IF @Count > 0
            INSERT  INTO @Result
                    (TableName, ColumnName)
            VALUES  (@TableName, @ColumnName)

        FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName

    CLOSE @tableCursor
    DEALLOCATE @tableCursor

    SELECT  SUBSTRING(TB.Sql, 1, LEN(TB.Sql) - 3) AS Sql, TB.TableName, SUBSTRING(TB.Columns, 1, LEN(TB.Columns) - 1) AS Columns
    FROM    (SELECT R.TableName, (SELECT R2.ColumnName + ', ' FROM @Result AS R2 WHERE R.TableName = R2.TableName FOR XML PATH('')) AS Columns,
                    'SELECT * FROM ' + R.TableName + ' WITH (NOLOCK) WHERE ' +
                    (SELECT 'CAST(' + R2.ColumnName + ' AS NVARCHAR(MAX)) LIKE ''%' + @KeyWord + '%'' OR '
                     FROM   @Result AS R2
                     WHERE  R.TableName = R2.TableName
                     XML PATH('')) AS Sql
             FROM   @Result AS R
             GROUP BY R.TableName) TB

    OPEN @tableCursor
    FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName

        PRINT @Sql
        SELECT  @TableName AS [Table],
                @ColumnName AS Columns

        FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName

    CLOSE @tableCursor
    DEALLOCATE @tableCursor


Initialising mock objects - MockIto

MockitoAnnotations & the runner have been well discussed above, so I'm going to throw in my tuppence for the unloved:

XXX mockedXxx = mock(XXX.class);

I use this because I find it a little bit more descriptive and I prefer (not out right ban) unit tests not to use member variables as I like my tests to be (as much as they can be) self contained.

Perform an action in every sub-directory using Bash

for D in `find . -type d`
    //Do whatever you need with D

Multiple radio button groups in MVC 4 Razor

Ok here's how I fixed this

My model is a list of categories. Each category contains a list of its subcategories.
with this in mind, every time in the foreach loop, each RadioButton will have its category's ID (which is unique) as its name attribue.
And I also used Html.RadioButton instead of Html.RadioButtonFor.

Here's the final 'working' pseudo-code:

@foreach (var cat in Model.Categories)
  //A piece of code & html here
  @foreach (var item in cat.SubCategories)
     @Html.RadioButton(item.CategoryID.ToString(), item.ID)

The result is:

<input name="127" type="radio" value="110">

Please note that I HAVE NOT put all these radio button groups inside a form. And I don't know if this solution will still work properly in a form.

Thanks to all of the people who helped me solve this ;)

How to start Activity in adapter?

When implementing the onClickListener, you can use v.getContext.startActivity.

btn.setOnClickListener(new OnClickListener() {                  
    public void onClick(View v) {

How to get dictionary values as a generic list

Use this:

List<MyType> items = new List<MyType>()
foreach(var value in myDico.Values)

The problem is that every key in your dictionary has a list of instances as value. Your code would work, if each key would have exactly one instance as value, as in the following example:

Dictionary<string, MyType> myDico = GetDictionary();
List<MyType> items = new List<MyType>(myDico.Values);

Parser Error when deploy ASP.NET application

This happens when the files inside the Debug and Release folder are not created properly(Either they are having wrong reference or having overwritten many times). I have faced the same problem in which, i everything works fine when we build the solution, but when i publish the website it gives me same error. I have solved this in following manner:

  1. Go to your Solution Explorer in Visual Studio and click on show hidden files (if they are not showing ! )
  2. you will find a folder named obj, open it .
  3. Here there are again 2 folder named respectively as Debug and Release. Now, delete the content from these two folder, Make sure that you do not delete the folders Debug and Release. Only delete the files and folders inside Debug and Release folder.
  4. Now build and publish your solution and everything will work like charm.

How to uncheck checkbox using jQuery Uniform library

A simpler solution is to do this rather than using uniform:

$('#check1').prop('checked', true); // will check the checkbox with id check1
$('#check1').prop('checked', false); // will uncheck the checkbox with id check1

This will not trigger any click action defined.

You can also use:

$('#check1').click(); // 

This will toggle the check/uncheck for the checkbox but this will also trigger any click action you have defined. So be careful.

EDIT: jQuery 1.6+ uses prop() not attr() for checkboxes checked value

How to zero pad a sequence of integers in bash so that all have the same width?

1.) Create a sequence of numbers 'seq' from 1 to 1000, and fix the width '-w' (width is determined by length of ending number, in this case 4 digits for 1000).

2.) Also, select which numbers you want using 'sed -n' (in this case, we select numbers 1-100).

3.) 'echo' out each number. Numbers are stored in the variable 'i', accessed using the '$'.

Pros: This code is pretty clean.

Cons: 'seq' isn't native to all Linux systems (as I understand)

for i in `seq -w 1 1000 | sed -n '1,100p'`; 
    echo $i; 

disable editing default value of text input

How about disabled=disabled:

<input id="price_from" value="price from " disabled="disabled">????????????

Problem is if you don't want user to edit them, why display them in input? You can hide them even if you want to submit a form. And to display information, just use other tag instead.

Python strftime - date without leading 0?

using, for example, "%-d" is not portable even between different versions of the same OS. A better solution would be to extract the date components individually, and choose between date specific formatting operators and date attribute access for each component.

e =, 1, 6)
"{date:%A} {} {date:%B}{date.year}".format(date=e)

How do I copy a range of formula values and paste them to a specific range in another sheet?

You can change

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)


Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

BTW, if you have xls file (excel 2003), you would get an error if your lastrow would be greater 3.

Try to use this code instead:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Application.CutCopyMode = False
End Sub

Note, above code determines last non empty row on DB sheet in column A (variable lastrowDB). If you need to find lastrow for each destination column in DB sheet, use next modification:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With



You could also use next approach instead Copy/PasteSpecial. Replace

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues


Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

What is the difference between % and %% in a cmd file?

In DOS you couldn't use environment variables on the command line, only in batch files, where they used the % sign as a delimiter. If you wanted a literal % sign in a batch file, e.g. in an echo statement, you needed to double it.

This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your % signs in a .cmd file.

SQL query for a carriage return in a string and ultimately removing carriage return

In SQL Server I would use:

WHERE CHARINDEX(CHAR(13), name) <> 0 OR CHARINDEX(CHAR(10), name) <> 0

This will search for both carriage returns and line feeds.

If you want to search for tabs too just add:

OR CHARINDEX(CHAR(9), name) <> 0

SQL Server 2012 Install or add Full-text search

You can add full text to an existing instance by changing the SQL Server program in Programs and Features. Follow the steps below. You might need the original disk or ISO for the installation to complete. (Per HotN's comment: If you have SQL Server Express, make sure it is SQL Server Express With Advanced Services.)


  1. Open the Programs and Features control panel.
  2. Select Microsoft SQL Server 2012 and click Change.
  3. When prompted to Add/Repair/Remove, select Add.
  4. Advance through the wizard until the Feature Selection screen. Then select Full-Text Search.

Step 1 Step 2

enter image description here

  1. On the Installation Type screen, select the appropriate SQL Server instance.

  2. Advance through the rest of the wizard.

Source (with screenshots):

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Try like this...

select CONVERT (varchar(10), getdate(), 103) AS [DD/MM/YYYY]

For more info :

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

How to check the extension of a filename in a bash script?

I wrote a bash script that looks at the type of a file then copies it to a location, I use it to look through the videos I've watched online from my firefox cache:

# flvcache script


for f in `find $CACHE -size +$MINFILESIZE`
    a=$(file $f | cut -f2 -d ' ')
    o=$(basename $f)
    if [ "$a" = "Macromedia" ]
            cp "$f" "$OUTPUTDIR/$o"

nautilus  "$OUTPUTDIR"&

It uses similar ideas to those presented here, hope this is helpful to someone.

How can I send large messages with Kafka (over 15MB)?

The idea is to have equal size of message being sent from Kafka Producer to Kafka Broker and then received by Kafka Consumer i.e.

Kafka producer --> Kafka Broker --> Kafka Consumer

Suppose if the requirement is to send 15MB of message, then the Producer, the Broker and the Consumer, all three, needs to be in sync.

Kafka Producer sends 15 MB --> Kafka Broker Allows/Stores 15 MB --> Kafka Consumer receives 15 MB

The setting therefore should be:

a) on Broker:


b) on Consumer:


How do I print out the contents of an object in Rails for easy debugging?

You need to use debug(@var). It's exactly like "print_r".

Reading file from Workspace in Jenkins with Groovy script

I realize this question was about creating a plugin, but since the new Jenkins 2 Pipeline builds use Groovy, I found myself here while trying to figure out how to read a file from a workspace in a Pipeline build. So maybe I can help someone like me out in the future.

Turns out it's very easy, there is a readfile step, and I should have rtfm:

env.WORKSPACE = pwd()
def version = readFile "${env.WORKSPACE}/version.txt"

Visual Studio Post Build Event - Copy to Relative Directory Location

If none of the TargetDir or other macros point to the right place, use the ".." directory to go backwards up the folder hierarchy.

ie. Use $(SolutionDir)\..\.. to get your base directory.

For list of all macros, see here:

How to delete a line from a text file in C#?

I'd very simply:

  • Open the file for read/write
  • Read/seek through it until the start of the line you want to delete
  • Set the write pointer to the current read pointer
  • Read through to the end of the line we're deleting and skip the newline delimiters (counting the number of characters as we go, we'll call it nline)
  • Read byte-by-byte and write each byte to the file
  • When finished truncate the file to (orig_length - nline).

What's the @ in front of a string in C#?

It marks the string as a verbatim string literal - anything in the string that would normally be interpreted as an escape sequence is ignored.

So "C:\\Users\\Rich" is the same as @"C:\Users\Rich"

There is one exception: an escape sequence is needed for the double quote. To escape a double quote, you need to put two double quotes in a row. For instance, @"""" evaluates to ".

Send data from javascript to a mysql database

The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.

So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net

If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.

How do I get current scope dom-element in AngularJS controller?

In controller:

function innerItem($scope, $element){
    var jQueryInnerItem = $($element); 

symfony2 : failed to write cache directory

You probably aborted a clearcache halfway and now you already have an app/cache/dev_old.

Try this (in the root of your project, assuming you're on a Unixy environment like OS X or Linux):

rm -rf app/cache/dev*

How to use vagrant in a proxy environment?

On a Windows host

open a CMD prompt;


Substitute the address and port in the above snippets to whatever is appropriate for your situation. The above will remain set until you close the CMD prompt. If it works for you, consider adding them permanently to your environment variables so that you won't have to set them every time you open a new CMD prompt.

How to convert a GUID to a string in C#?

Here are examples of output from each of the format specifiers:

N: cd26ccf675d64521884f1693c62ed303
D: cd26ccf6-75d6-4521-884f-1693c62ed303
B: {cd26ccf6-75d6-4521-884f-1693c62ed303}
P: (cd26ccf6-75d6-4521-884f-1693c62ed303)
X: {0xcd26ccf6,0x75d6,0x4521,{0x88,0x4f,0x16,0x93,0xc6,0x2e,0xd3,0x03}}

The default is D.

Run this yourself.

Detect WebBrowser complete page loading

Using the DocumentCompleted event with a page with multiple nested frames didn't work for me.

I used the Interop.SHDocVW library to cast the WebBrowser control like this:

public class webControlWrapper
    private bool _complete;
    private WebBrowser _webBrowserControl;

    public webControlWrapper(WebBrowser webBrowserControl)
        _webBrowserControl = webBrowserControl;

    public void NavigateAndWaitForComplete(string url)
        _complete = false;


        var webBrowser = (SHDocVw.WebBrowser) _webBrowserControl.ActiveXInstance;

        if (webBrowser != null)
            webBrowser.DocumentComplete += WebControl_DocumentComplete;

        //Wait until page is complete
        while (!_complete)

    private void WebControl_DocumentComplete(object pDisp, ref object URL)
        // Test if it's the main frame who called the event.
        if (pDisp == _webBrowserControl.ActiveXInstance)
            _complete = true;

This code works for me when navigating to a defined URL using the webBrowserControl.Navigate(url) method, but I don't know how to control page complete when a html button is clicked using the htmlElement.InvokeMember("click").

Regex pattern inside SQL Replace function?

For those looking for a performant and easy solution and are willing to enable CLR:

create database TestSQLFunctions
use TestSQLFunctions
alter database TestSQLFunctions set trustworthy on

EXEC sp_configure 'clr enabled', 1

FROM 0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C0103004BE8B85F0000000000000000E00022200B013000000800000006000000000000C2270000002000000040000000000010002000000002000004000000000000000600000000000000008000000002000000000000030060850000100000100000000010000010000000000000100000000000000000000000702700004F000000004000009803000000000000000000000000000000000000006000000C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E74657874000000C8070000002000000008000000020000000000000000000000000000200000602E72737263000000980300000040000000040000000A0000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000000E00000000000000000000000000004000004200000000000000000000000000000000A4270000000000004800000002000500682000000807000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003A022D02022A020304281000000A2A1E02281100000A2A0042534A4201000100000000000C00000076342E302E33303331390000000005006C00000018020000237E000084020000CC02000023537472696E6773000000005005000004000000235553005405000010000000234755494400000064050000A401000023426C6F620000000000000002000001471500000900000000FA0133001600000100000013000000020000000200000003000000110000000F00000001000000030000000000CA01010000000000060025014F02060092014F02060044001D020F006F02000006006C00E20106000801E2010600D400E20106007901E20106004501E20106005E01E20106008300E2010600580030020600360030020600B700E20106009E00B0010600AA02DB010A00F300FC010A001F00FC010E00C3027E02000000000100000000000100010001001000C3029D0241000100010050200000000096002E001A0001005F2000000000861817020600040000000100BD0200000200F40100000300B102090017020100110017020600190017020A0029001702100031001702100039001702100041001702100049001702100051001702100059001702100061001702150069001702100071001702100079001702100089001702060099002E001A0081001702060020007B0010012E000B002A002E00130033002E001B0052002E0023005B002E002B006D002E0033006D002E003B006D002E0043005B002E004B0073002E0053006D002E005B006D002E0063008B002E006B00B5002E007300C2000480000001000000000000000000000000009D020000040000000000000000000000210016000000000004000000000000000000000021000A00000000000400000000000000000000002100DB010000000000000000003C4D6F64756C653E0053797374656D2E44617461006D73636F726C696200446174614163636573734B696E64005265706C61636500477569644174747269627574650044656275676761626C6541747472696275746500436F6D56697369626C6541747472696275746500417373656D626C795469746C6541747472696275746500417373656D626C7954726164656D61726B417474726962757465005461726765744672616D65776F726B41747472696275746500417373656D626C7946696C6556657273696F6E41747472696275746500417373656D626C79436F6E66696775726174696F6E4174747269627574650053716C46756E6374696F6E41747472696275746500417373656D626C794465736372697074696F6E41747472696275746500436F6D70696C6174696F6E52656C61786174696F6E7341747472696275746500417373656D626C7950726F6475637441747472696275746500417373656D626C79436F7079726967687441747472696275746500417373656D626C79436F6D70616E794174747269627574650052756E74696D65436F6D7061746962696C6974794174747269627574650053797374656D2E52756E74696D652E56657273696F6E696E670053514C46756E6374696F6E732E646C6C0053797374656D0053797374656D2E5265666C656374696F6E007061747465726E004D6963726F736F66742E53716C5365727665722E536572766572002E63746F720053797374656D2E446961676E6F73746963730053797374656D2E52756E74696D652E496E7465726F7053657276696365730053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300446562756767696E674D6F6465730053797374656D2E546578742E526567756C617245787072657373696F6E730053514C46756E6374696F6E73004F626A656374007265706C6163656D656E7400696E70757400526567657800000000000000003A1617E607071B47B964858BCD87458B00042001010803200001052001011111042001010E04200101020600030E0E0E0E08B77A5C561934E0890801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F7773010801000200000000001101000C53514C46756E6374696F6E73000005010000000017010012436F7079726967687420C2A920203230323000002901002434346436386231632D393735312D343938612D396665352D32316666333934303738303900000C010007312E302E302E3000004D01001C2E4E45544672616D65776F726B2C56657273696F6E3D76342E352E320100540E144672616D65776F726B446973706C61794E616D65142E4E4554204672616D65776F726B20342E352E32808F010001005455794D6963726F736F66742E53716C5365727665722E5365727665722E446174614163636573734B696E642C2053797374656D2E446174612C2056657273696F6E3D342E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038390A4461746141636365737301000000000000982700000000000000000000B2270000002000000000000000000000000000000000000000000000A4270000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C0000000000FF25002000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001001000000018000080000000000000000000000000000001000100000030000080000000000000000000000000000001000000000048000000584000003C03000000000000000000003C0334000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE00000100000001000000000000000100000000003F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B0049C020000010053007400720069006E006700460069006C00650049006E0066006F0000007802000001003000300030003000300034006200300000001A000100010043006F006D006D0065006E007400730000000000000022000100010043006F006D00700061006E0079004E0061006D006500000000000000000042000D000100460069006C0065004400650073006300720069007000740069006F006E0000000000530051004C00460075006E006300740069006F006E00730000000000300008000100460069006C006500560065007200730069006F006E000000000031002E0030002E0030002E003000000042001100010049006E007400650072006E0061006C004E0061006D0065000000530051004C00460075006E006300740069006F006E0073002E0064006C006C00000000004800120001004C006500670061006C0043006F007000790072006900670068007400000043006F0070007900720069006700680074002000A90020002000320030003200300000002A00010001004C006500670061006C00540072006100640065006D00610072006B00730000000000000000004A00110001004F0072006900670069006E0061006C00460069006C0065006E0061006D0065000000530051004C00460075006E006300740069006F006E0073002E0064006C006C00000000003A000D000100500072006F0064007500630074004E0061006D00650000000000530051004C00460075006E006300740069006F006E00730000000000340008000100500072006F006400750063007400560065007200730069006F006E00000031002E0030002E0030002E003000000038000800010041007300730065006D0062006C0079002000560065007200730069006F006E00000031002E0030002E0030002E0030000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000C000000C43700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000


    @input nvarchar(max),
    @pattern nvarchar(max),
    @replacement nvarchar(max)
) RETURNS nvarchar  (max)
AS EXTERNAL NAME SQLFunctions.[SQLFunctions.Regex].Replace; 


-- outputs This is a test 
select dbo.RegexReplace('This is a test 12345','[0-9]','')

Content of the DLL: enter image description here

@RequestBody and @ResponseBody annotations in Spring

Below is an example of a method in a Java controller.

@RequestMapping(method = RequestMethod.POST)
public HttpStatus something(@RequestBody MyModel myModel) 
    return HttpStatus.OK;

By using @RequestBody annotation you will get your values mapped with the model you created in your system for handling any specific call. While by using @ResponseBody you can send anything back to the place from where the request was generated. Both things will be mapped easily without writing any custom parser etc.

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

You are using the FTP in an active mode.

Setting up the FTP in the active mode can be cumbersome nowadays due to firewalls and NATs.

It's likely because of your local firewall or NAT that the server was not able to connect back to your client to establish data transfer connection.

Or your client is not aware of its external IP address and provides an internal address instead to the server (in PORT command), which the server is obviously not able to use. But it should not be the case, as vsftpd by default rejects data transfer address not identical to source address of FTP control connection (the port_promiscuous directive).

See my article Network Configuration for Active Mode.

If possible, you should use a passive mode as it typically requires no additional setup on a client-side. That's also what the server suggested you by "Consider using PASV". The PASV is an FTP command used to enter the passive mode.

Unfortunately Windows FTP command-line client (the ftp.exe) does not support passive mode at all. It makes it pretty useless nowadays.

Use any other 3rd party Windows FTP command-line client instead. Most other support the passive mode.

For example WinSCP FTP client defaults to the passive mode and there's a guide available for converting Windows FTP script to WinSCP script.

(I'm the author of WinSCP)

Versioning SQL Server database

The typical solution is to dump the database as necessary and backup those files.

Depending on your development platform, there may be opensource plugins available. Rolling your own code to do it is usually fairly trivial.

Note: You may want to backup the database dump instead of putting it into version control. The files can get huge fast in version control, and cause your entire source control system to become slow (I'm recalling a CVS horror story at the moment).

Display Python datetime without time

>>> print, type(
2013-05-07 <type ''>

How to listen state changes in react.js?

It's been a while but for future reference: the method shouldComponentUpdate() can be used.

An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:

static getDerivedStateFromProps() 


How to set default font family for entire Android app

Not talk about performance, for custom font you can have a recursive method loop through all the views and set typeface if it's a TextView:

public class Font {
    public static void setAllTextView(ViewGroup parent) {
        for (int i = parent.getChildCount() - 1; i >= 0; i--) {
            final View child = parent.getChildAt(i);
            if (child instanceof ViewGroup) {
                setAllTextView((ViewGroup) child);
            } else if (child instanceof TextView) {
                ((TextView) child).setTypeface(getFont());

    public static Typeface getFont() {
        return Typeface.createFromAsset(YourApplicationContext.getInstance().getAssets(), "fonts/whateverfont.ttf");

In all your activity, pass current ViewGroup to it after setContentView and it's done:

ViewGroup group = (ViewGroup) getWindow().getDecorView().findViewById(;

For fragment you can do something similar.

What are .a and .so files?

.a are static libraries. If you use code stored inside them, it's taken from them and embedded into your own binary. In Visual Studio, these would be .lib files.

.so are dynamic libraries. If you use code stored inside them, it's not taken and embedded into your own binary. Instead it's just referenced, so the binary will depend on them and the code from the so file is added/loaded at runtime. In Visual Studio/Windows these would be .dll files (with small .lib files containing linking information).

When does Java's Thread.sleep throw InterruptedException?

Methods like sleep() and wait() of class Thread might throw an InterruptedException. This will happen if some other thread wanted to interrupt the thread that is waiting or sleeping.

How can I change the default Mysql connection timeout when connecting through python?

You change default value in MySQL configuration file (option connect_timeout in mysqld section) -


If this file is not accessible for you, then you can set this value using this statement -

SET GLOBAL connect_timeout=100;

Naming convention - underscore in C++ and C# variables

It's just a convention some programmers use to make it clear when you're manipulating a member of the class or some other kind of variable (parameters, local to the function, etc). Another convention that's also in wide use for member variables is prefixing the name with 'm_'.

Anyway, these are only conventions and you will not find a single source for all of them. They're a matter of style and each programming team, project or company has their own (or even don't have any).

(Mac) -bash: __git_ps1: command not found

__git_ps1 for bash is now found in in /usr/local/etc/bash_completion.d on my brew installed git version

PHP checkbox set to check based on database value

This simplest ways is to add the "checked attribute.

<label for="tag_1">Tag 1</label>
<input type="checkbox" name="tag_1" id="tag_1" value="yes" 
    <?php if($tag_1_saved_value === 'yes') echo 'checked="checked"';?> />

What is {this.props.children} and when you should use it?

props.children represents the content between the opening and the closing tags when invoking/rendering a component:

const Foo = props => (
    <p>I'm {}</p>
    <p>abc is: {}</p>

    <p>I have {props.children.length} children.</p>
    <p>They are: {props.children}.</p>
    <p>{Array.isArray(props.children) ? 'My kids are an array.' : ''}</p>

const Baz = () => <span>{} and</span>;
const Bar = () => <span> {}</span>;

invoke/call/render Foo:

<Foo abc={123}>
  <Baz />
  <Bar />

props and props.children

Setting the JVM via the command line on Windows

Yes - just explicitly provide the path to java.exe. For instance:

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_03\bin\java.exe" -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_12\bin\java.exe" -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

The easiest way to do this for a running command shell is something like:

set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

For example, here's a complete session showing my default JVM, then the change to the path, then the new one:

c:\Users\Jon\Test>java -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

c:\Users\Jon\Test>set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

c:\Users\Jon\Test>java -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

This won't change programs which explicitly use JAVA_HOME though.

Note that if you get the wrong directory in the path - including one that doesn't exist - you won't get any errors, it will effectively just be ignored.

Printing one character at a time from a string, using the while loop

Python allows you to use a string as an iterator:

for character in 'string':

I'm guessing it's your job to figure out how to turn that into a while loop.

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

I have just faced the same problem. First, you need to install the appropriate Oracle client for your OS. In my case, to install it on Ubuntu x64 I have followed this instructions

Then, you need to install cx_Oracle, a Python module to connect to the Oracle client. Again, assuming you are running Ubuntu in a 64bit machine, you should type in a shell:

wget -c
sudo alien -i cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm

This will work for Oracle 11g if you have installed Python 2.7.x, but you can download a different cx_Oracle version in To check which Python version do you have, type in a terminal:

python -V

I hope it helps

Git error: "Host Key Verification Failed" when connecting to remote repository

You can use your "git url" in 'https" URL format in the Jenkinsfile or wherever you want.

git url: ''

oracle varchar to number

select to_number(exception_value) from exception where to_number(exception_value) = 105

SQLite: How do I save the result of a query as a CSV file?

To include column names to your csv file you can do the following:

sqlite> .headers on
sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout

To verify the changes that you have made you can run this command:

sqlite> .show


echo: off   
explain: off   
headers: on   
mode: csv   
nullvalue: ""  
output: stdout  
separator: "|"   
stats: off   
width: 22 18 

Writing String to Stream and reading it back does not work

I think it would be a lot more productive to use a TextWriter, in this case a StreamWriter to write to the MemoryStream. After that, as other have said, you need to "rewind" the MemoryStream using something like stringAsStream.Position = 0L;.

stringAsStream = new MemoryStream();

// create stream writer with UTF-16 (Unicode) encoding to write to the memory stream
using(StreamWriter sWriter = new StreamWriter(stringAsStream, UnicodeEncoding.Unicode))
  sWriter.Write("Lorem ipsum.");
stringAsStream.Position = 0L; // rewind

Note that:

StreamWriter defaults to using an instance of UTF8Encoding unless specified otherwise. This instance of UTF8Encoding is constructed without a byte order mark (BOM)

Also, you don't have to create a new UnicodeEncoding() usually, since there's already one as a static member of the class for you to use in convenient utf-8, utf-16, and utf-32 flavors.

And then, finally (as others have said) you're trying to convert the bytes directly to chars, which they are not. If I had a memory stream and knew it was a string, I'd use a TextReader to get the string back from the bytes. It seems "dangerous" to me to mess around with the raw bytes.

data.frame Group By column

Using dplyr:

df <- data.frame(A = c(1, 1, 2, 3, 3), B = c(2, 3, 3, 5, 6))
df %>% group_by(A) %>% summarise(B = sum(B))

## Source: local data frame [3 x 2]
##   A  B
## 1 1  5
## 2 2  3
## 3 3 11

With sqldf:


Filtering array of objects with lodash based on property value

let myArr = [_x000D_
    { name: "john", age: 23 },_x000D_
    { name: "john", age: 43 },_x000D_
    { name: "jim", age: 101 },_x000D_
    { name: "bob", age: 67 },_x000D_
// this will return old object (myArr) with items named 'john'_x000D_
let list = _.filter(myArr, item => === 'jhon');_x000D_
//  this will return new object referenc (new Object) with items named 'john' _x000D_
let list =, item => === 'jhon').filter(item =>;

C++ Convert string (or char*) to wstring (or wchar_t*)

using Boost.Locale:

ws = boost::locale::conv::utf_to_utf<wchar_t>(s);

How to set user environment variables in Windows Server 2008 R2 as a normal user?

There are three ways

1) This runs the GUI editor for the user environment variables. It does exactly what the OP wanted to do and does not prompt for administrative credentials.

rundll32.exe sysdm.cpl,EditEnvironmentVariables

(bonus: This works on Windows Vista to Windows 10 for desktops and Windows Server 2008 through Server 2016. It does not work on Windows NT, 2000, XP, and 2003. However, on the older systems you can use sysdm.cpl without the ",EditEnvironmentVariables" parameter and then navigate to the Advanced tab and then Environment Variables button.)

2) Use the SETX command from the command prompt. This is like the set command but updates the environment that's stored in the registry. Unfortunately, SETX is not as easy to use as the built in SET command. There's no way to list the variables for example. Thus it's impossible to do something such as appending a folder to the user's PATH variable. While SET will display the variables you don't know which ones are user vs. system variables and the PATH that's shown is a combination of both.

3) Use regedit and navigate to HKEY_CURRENT_USER\Environment

Keep in mind that changes to the user's environment does not immediately propagate to all processes currently running for that user. You can see this in a command prompt where your changes will not be visible if you use SET. For example

rem Add a user environment variable named stackoverflow that's set to "test"
setx stackoverflow test
set st

This should show all variables whose names start with the letters "st". If there are none then it displays "Environment variable st not defined". Exit the command prompt and start another. Try set st again and you'll see


To delete the stackoverflow variable use

setx stackoverflow ""

It will respond with "SUCCESS: Specified value was saved." which looks strange given you want to delete the variable. However, if you start a new command prompt then set st will show that there are no variables starting with the letters "st"

(correction - I discovered that setx stackoverflow "" did not delete the variable. It's in the registry as an empty string. The SET command though interprets it as though there is no variable. if not defined stackoverflow echo Not defined says it's not defined.)

Check if Python Package is installed

I would like to comment to @ice.nicer reply but I cannot, so ... My observations is that packages with dashes are saved with underscores, not only with dots as pointed out by @dwich comment

For example, you do pip3 install sphinx-rtd-theme, but:

  • importlib.util.find_spec(sphinx_rtd_theme) returns an Object
  • importlib.util.find_spec(sphinx-rtd-theme) returns None
  • importlib.util.find_spec(sphinx.rtd.theme) raises ModuleNotFoundError

Moreover, some names are totally changed. For example, you do pip3 install pyyaml but it is saved simply as yaml

I am using python3.8

How to test if a file is a directory in a batch script?

One issue with using %%~si\NUL method is that there is the chance that it guesses wrong. Its possible to have a filename shorten to the wrong file. I don't think %%~si resolves the 8.3 filename, but guesses it, but using string manipulation to shorten the filepath. I believe if you have similar file paths it may not work.

An alternative method:

dir /AD %F% 2>&1 | findstr /C:"Not Found">NUL:&&(goto IsFile)||(goto IsDir)

  echo %F% is a file
  goto done

  echo %F% is a directory
  goto done


You can replace (goto IsFile)||(goto IsDir) with other batch commands:
(echo Is a File)||(echo is a Directory)

javascript - match string against the array of regular expressions

let expressions = [ '/something/', '/something_else/', '/and_something_else/'];

let str = 'else';

here will be the check for following expressions:

if( expressions.find(expression => expression.includes(str) ) ) {


using Array .find() method to traverse array and .include to check substring

How to scroll to top of the page in AngularJS?

You can use $anchorScroll.

Just inject $anchorScroll as a dependency, and call $anchorScroll() whenever you want to scroll to top.

Is there an opposite of include? for Ruby Arrays?

Here you go:

unless @players.include?(

You might have a look at the Ruby Style Guide for more info on similar techniques.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Replace the dependency in the POM.xml file


By the dependency


How to mock a final class with mockito

Mocking final/static classes/methods is possible with Mockito v2 only.

add this in your gradle file:

testImplementation 'org.mockito:mockito-inline:2.13.0'

This is not possible with Mockito v1, from the Mockito FAQ:

What are the limitations of Mockito

  • Needs java 1.5+

  • Cannot mock final classes


What are all the uses of an underscore in Scala?

There is one usage I can see everyone here seems to have forgotten to list...

Rather than doing this:

List("foo", "bar", "baz").map(n => n.toUpperCase())

You could can simply do this:

List("foo", "bar", "baz").map(_.toUpperCase())

How to add results of two select commands in same query

Something simple like this can be done using subqueries in the select clause:

select ((select sum(hours) from resource) +
        (select sum(hours) from projects-time)
       ) as totalHours

For such a simple query as this, such a subselect is reasonable.

In some databases, you might have to add from dual for the query to compile.

If you want to output each individually:

select (select sum(hours) from resource) as ResourceHours,
       (select sum(hours) from projects-time) as ProjectHours

If you want both and the sum, a subquery is handy:

select ResourceHours, ProjectHours, (ResourceHours+ProjecctHours) as TotalHours
from (select (select sum(hours) from resource) as ResourceHours,
             (select sum(hours) from projects-time) as ProjectHours
     ) t

Insert current date/time using now() in a field using MySQL/PHP

You forgot to close the mysql_query command:

mysql_query("INSERT INTO users (first, last, whenadded) VALUES ('$first', '$last', now())");

Note that last parentheses.

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

Due to security restrictions at my current place of work I was unable to set enviroment variables on my Windows based PC.

My workaround was to copy the mvn.bat file from %M2% into C:\WINNT and add the following to the top of the batch file:

@REM Needed as unable to set env variables on my desktop PC.

set MAVEN_OPTS=-Xms256m -Xmx1024m
set M2_HOME=C:\apache-maven-3.0.4
set M2=%M2_HOME%\bin
set JAVA_HOME=C:\Program Files\Java\jdk1.5.0_15
set PATH=%JAVA_HOME%\bin;%M2%;%PATH%

Not the nicest solution but it works. If anybody has any other way or work-around where the standard env vars are not able to be set into the system I'd welcome their response.

SQL Server Service not available in service list after installation of SQL Server Management Studio

downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?

You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.

Passing HTML input value as a JavaScript Function Parameter

Use this it will work,

<h1>Adding 'a' and 'b'</h1>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="a"><br>
  <button onclick="add()">Add</button>
  function add() {
    var m = document.getElementById("a").value;
    var n = document.getElementById("b").value;
    var sum = m + n;

Can I embed a .png image into an html page?

The 64base method works for large images as well, I use that method to embed all the images into my website, and it works every time. I've done with files up to 2Mb size, jpg and png.

Stylesheet not updating

In my case, since I could not append a cache busting timestamp to the css url it turned out that I had to manually refresh the application pool in IIS 7.5.7600.

Every other avenue was pursued, right down to disabling the caching entirely for the site and also for the local browser (like ENTIRELY disabled for both), still didn't do the trick. Also "restarting" the website did nothing.

Same position as me? [Site Name] > "Application Pool" > "Recycle" is your last resort...

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

I hope you have resolved your issue. If you still got issue then double check again if you install this Oracle under a domain account. I found a thread that says Oracle XE giving same error when installing under domain account. Please use a local account instead.


non static method cannot be referenced from a static context

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

You should do:

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


As I told you here

cannot find module "lodash"

I got the error above and after fixing it I got an error for lodash/merge, then I got an error for 'license-check-and-add' then I realized that according to if I ran the below command, it installs all the missing pacakages at once! Then running the yarn build command worked smoothly with a --force parameter with yarn build.

yarn install

yarn build --force

enter image description here

Yarn build --force execution: enter image description here

React onClick and preventDefault() link refresh/redirect?

A full version of the solution will be wrapping the method upvotes inside onClick, passing e and use native e.preventDefault();

upvotes = (e, arg1, arg2, arg3 ) => {
    //do something...

    return (<a type="simpleQuery" onClick={ e => this.upvotes(e, arg1, arg2, arg3) }>

Error: Argument is not a function, got undefined

If you are in a submodule, don't forget to declare the module in main app. ie :

angular.module('mainApp', ['subModule1', 'subModule2']);

   .controller('MyController', ['$scope', function($scope) {
      $scope.moduleName = 'subModule1';
<div ng-app="mainApp">
   <div ng-controller="MyController">
   <span ng-bind="moduleName"></span>

If you don't declare subModule1 in mainApp, you will got a "[ng:areq] Argument "MyController" is not a function, got undefined.

SOAP request in PHP with CURL

Tested and working!

  • with https, user & password

     //Data, connection, auth
     $dataFromTheForm = $_POST['fieldName']; // request data from the form
     $soapUrl = ""; // asmx URL of WSDL
     $soapUser = "username";  //  username
     $soapPassword = "password"; // password
     // xml post structure
     $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                         <soap:Envelope xmlns:xsi="" xmlns:xsd="" xmlns:soap="">
                             <GetItemPrice xmlns=""> // xmlns value to be set to your WSDL URL
                             </GetItemPrice >
                         </soap:Envelope>';   // data from the form, e.g. some ID number
        $headers = array(
                     "Content-type: text/xml;charset=\"utf-8\"",
                     "Accept: text/xml",
                     "Cache-Control: no-cache",
                     "Pragma: no-cache",
                     "Content-length: ".strlen($xml_post_string),
                 ); //SOAPAction: your op URL
         $url = $soapUrl;
         // PHP cURL  for https connection with auth
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
         // converting
         $response = curl_exec($ch); 
         // converting
         $response1 = str_replace("<soap:Body>","",$response);
         $response2 = str_replace("</soap:Body>","",$response1);
         // convertingc to XML
         $parser = simplexml_load_string($response2);
         // user $parser to get your data out of XML response and to display it. 

How to display the current time and date in C#

For time:

label1.Text = DateTime.Now.ToString("HH:mm:ss"); //result 22:11:45


label1.Text = DateTime.Now.ToString("hh:mm:ss tt"); //result 11:11:45 PM

For date:

label1.Text = DateTime.Now.ToShortDateString(); //30.5.2012

Get the latest record with filter in Django

last() latest()

Usign last():


using latest():


Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

What I did when faced this issue, was connect to DB and update the checksum field correspondent to the mistaken version, putting there the value resolved locally by FlyWay.

For the following error:

nested exception is org.flywaydb.core.api.FlywayException: Validate failed.
Migration Checksum mismatch for migration 1.12
    -> Applied to database : 1029320280
    -> Resolved locally    : -236187247

I simply did this:

UPDATE schema_version SET checksum = -236187247 WHERE version_rank = 12 AND checksum = 1029320280;

And problem solved..

NOTE: You have to be sure your schema is actually correct, check your tables and their structure, if everything is OK, then you can apply this solution; otherwise, you should repair your schema manually first using plain and native SQL.

Set UIButton title UILabel font size programmatically

this may help :

[objBtn.titleLabel setFont:[UIFont fontWithName:@“fontname” size:fontsize]];

How to escape strings in SQL Server using PHP?

Warning: This function was REMOVED in PHP 7.0.0.

For anyone still using these mssql_* functions, keep in mind that they have been removed from PHP as of v7.0.0. So, that means you eventually have to rewrite your model code to either use the PDO library, sqlsrv_* etc. If you're looking for something with a "quoting/escaping" method, I would recommend PDO.

Alternatives to this function include: PDO::query(), sqlsrv_query() and odbc_exec()

How can I find the location of origin/master in git, and how do I change it?

I am a git newbie as well. I had the same problem with 'your branch is ahead of origin/master by N commits' messages. Doing the suggested 'git diff origin/master' did show some diffs that I did not care to keep. So ...

Since my git clone was for hosting, and I wanted an exact copy of the master repo, and did not care to keep any local changes, I decided to save off my entire repo, and create a new one:

(on the hosting machine)

mv myrepo myrepo
git clone USER@MASTER_HOST:/REPO_DIR myrepo

For expediency, I used to make changes to the clone on my hosting machine. No more. I will make those changes to the master, git commit there, and do a git pull. Hopefully, this should keep my git clone on the hosting machine in complete sync.


Can I run javascript before the whole page is loaded?

Not only can you, but you have to make a special effort not to if you don't want to. :-)

When the browser encounters a classic script tag when parsing the HTML, it stops parsing and hands over to the JavaScript interpreter, which runs the script. The parser doesn't continue until the script execution is complete (because the script might do document.write calls to output markup that the parser should handle).

That's the default behavior, but you have a few options for delaying script execution:

  1. Use JavaScript modules. A type="module" script is deferred until the HTML has been fully parsed and the initial DOM created. This isn't the primary reason to use modules, but it's one of the reasons:

    <script type="module" src="./my-code.js"></script>
    <!-- Or -->
    <script type="module">
    // Your code here

    The code will be fetched (if it's separate) and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. (If your module code is inline rather than in its own file, it is also deferred until HTML parsing is complete.)

    This wasn't available when I first wrote this answer in 2010, but here in 2020, all major modern browsers support modules natively, and if you need to support older browsers, you can use bundlers like Webpack and Rollup.js.

  2. Use the defer attribute on a classic script tag:

    <script defer src="./my-code.js"></script>

    As with the module, the code in my-code.js will be fetched and parsed in parallel with the HTML parsing, but won't be run until the HTML parsing is done. But, defer doesn't work with inline script content, only with external files referenced via src.

  3. I don't think it's what you want, but you can use the async attribute to tell the browser to fetch the JavaScript code in parallel with the HTML parsing, but then run it as soon as possible, even if the HTML parsing isn't complete. You can put it on a type="module" tag, or use it instead of defer on a classic script tag.

  4. Put the script tag at the end of the document, just prior to the closing </body> tag:

    <!doctype html>
    <!-- ... -->
    <!-- The document's HTML goes here -->
    <script type="module" src="./my-code.js"></script><!-- Or inline script -->

    That way, even though the code is run as soon as its encountered, all of the elements defined by the HTML above it exist and are ready to be used.

    It used to be that this caused an additional delay on some browsers because they wouldn't start fetching the code until the script tag was encountered, but modern browsers scan ahead and start prefetching. Still, this is very much the third choice at this point, both modules and defer are better options.

The spec has a useful diagram showing a raw script tag, defer, async, type="module", and type="module" async and the timing of when the JavaScript code is fetched and run:

enter image description here

Here's an example of the default behavior, a raw script tag:

.found {_x000D_
    color: green;_x000D_
<p>Paragraph 1</p>_x000D_
    if (typeof NodeList !== "undefined" && !NodeList.prototype.forEach) {_x000D_
        NodeList.prototype.forEach = Array.prototype.forEach;_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
<p>Paragraph 2</p>

(See my answer here for details around that NodeList code.)

When you run that, you see "Paragraph 1" in green but "Paragraph 2" is black, because the script ran synchronously with the HTML parsing, and so it only found the first paragraph, not the second.

In contrast, here's a type="module" script:

.found {_x000D_
    color: green;_x000D_
<p>Paragraph 1</p>_x000D_
<script type="module">_x000D_
    document.querySelectorAll("p").forEach(p => {_x000D_
<p>Paragraph 2</p>

Notice how they're both green now; the code didn't run until HTML parsing was complete. That would also be true with a defer script with external content (but not inline content).

(There was no need for the NodeList check there because any modern browser supporting modules already has forEach on NodeList.)

In this modern world, there's no real value to the DOMContentLoaded event of the "ready" feature that PrototypeJS, jQuery, ExtJS, Dojo, and most others provided back in the day (and still provide); just use modules or defer. Even back in the day, there wasn't much reason for using them (and they were often used incorrectly, holding up page presentation while the entire jQuery library was loaded because the script was in the head instead of after the document), something some developers at Google flagged up early on. This was also part of the reason for the YUI recommendation to put scripts at the end of the body, again back in the day.

Difference between int and double

int is a binary representation of a whole number, double is a double-precision floating point number.

Graphical DIFF programs for linux

I know of two graphical diff programs: Meld and KDiff3. I haven't used KDiff3, but Meld works well for me.

It seems that both are in the standard package repositories for openSUSE 11.0

How do I create ColorStateList programmatically?

Here's an example of how to create a ColorList programmatically in Kotlin:

val colorList = ColorStateList(
                intArrayOf(-android.R.attr.state_enabled),  // Disabled
                intArrayOf(android.R.attr.state_enabled)    // Enabled
                Color.BLACK,     // The color for the Disabled state
                Color.RED        // The color for the Enabled state

Import txt file and having each line as a list

with open('file') as file:

How to convert JSON string into List of Java object?

use below simple code, no need to use any library

String list = "your_json_string";
Gson gson = new Gson();                         
Type listType = new TypeToken<ArrayList<YourClassObject>>() {}.getType();
ArrayList<YourClassObject> users = new Gson().fromJson(list , listType);

Table 'mysql.user' doesn't exist:ERROR

My solution was to run

mysql_upgrade -u root

Scenario: I updated the MySQL version on my Mac with 'homebrew upgrade'. Afterwards, some stuff worked, but other commands raised the error described in the question.

Word count from a txt file program

The funny symbols you're encountering are a UTF-8 BOM (Byte Order Mark). To get rid of them, open the file using the correct encoding (I'm assuming you're on Python 3):

file = open(r"D:\zzzz\names2.txt", "r", encoding="utf-8-sig")

Furthermore, for counting, you can use collections.Counter:

from collections import Counter
wordcount = Counter(

Display them with:

>>> for item in wordcount.items(): print("{}\t{}".format(*item))
snake   1
lion    2
goat    2
horse   3

How to convert a string to ASCII

I think this code may be help you:

string str = char.ConvertFromUtf32(65)

What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

$testArray = [
  "name"   => "Dinesh Madusanka",
  "gender" => "male"
  "name"   => "Tharaka Devinda",
  "gender" => "male"
  "name"   => "Dumidu Ranasinghearachchi",
  "gender" => "male"



  echo "<pre>";

How to use onResume()?

Most of the previous answers do a good job explaining how, why, and when to use onResume() but I would like to add something about re-creating your Activity.

I want to know if I want to restart the activity at the end of exectuion of an other what method is executed onCreate() or onResume()

The answer is onCreate() However, when deciding to actually re-create it, you should ask yourself how much of the Activity needs to be re-created. If it is data in an adapter, say for a list, then you can call notifyDataChanged() on the adapter to repopulate the adapter and not have to redraw everything.

Also, if you just need to update certain views but not all then it may be more efficient to call invalidate() on the view(s) that need updated. This will only redraw those views and possibly allow your application to run more smoothly. I hope this can help you.

"Multiple definition", "first defined here" errors

Maybe you included the .c file in makefile multiple times.

Excel SUMIF between dates

To SUMIFS between dates, use the following:


Convert a CERT/PEM certificate to a PFX certificate

openssl pkcs12 -inkey bob_key.pem -in bob_cert.cert -export -out bob_pfx.pfx

Eclipse java debugging: source not found

If you want to attach source code to any JAR by auto-downloading, try using this Eclipse plugin Java Source Attacher

enter image description here

How do I get the Back Button to work with an AngularJS ui-router state machine?

history.back() and switch to previous state often give effect not that you want. For example, if you have form with tabs and each tab has own state, this just switched previous tab selected, not return from form. In case nested states, you usually need so think about witch of parent states you want to rollback.

This directive solves problem

angular.module('app', ['ui-router-back'])

<span ui-back='defaultState'> Go back </span>

It returns to state, that was active before button has displayed. Optional defaultState is state name that used when no previous state in memory. Also it restores scroll position


class UiBackData {
    fromStateName: string;
    fromParams: any;
    fromStateScroll: number;

interface IRootScope1 extends ng.IScope {
    uiBackData: UiBackData;

class UiBackDirective implements ng.IDirective {
    uiBackDataSave: UiBackData;

    constructor(private $state: angular.ui.IStateService,
        private $rootScope: IRootScope1,
        private $timeout: ng.ITimeoutService) {

    link: ng.IDirectiveLinkFn = (scope, element, attrs) => {
        this.uiBackDataSave = angular.copy(this.$rootScope.uiBackData);

        function parseStateRef(ref, current) {
            var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
            if (preparsed) ref = current + '(' + preparsed[1] + ')';
            parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
            if (!parsed || parsed.length !== 4)
                throw new Error("Invalid state ref '" + ref + "'");
            let paramExpr = parsed[3] || null;
            let copy = angular.copy(scope.$eval(paramExpr));
            return { state: parsed[1], paramExpr: copy };

        element.on('click', (e) => {

            if (this.uiBackDataSave.fromStateName)
                this.$state.go(this.uiBackDataSave.fromStateName, this.uiBackDataSave.fromParams)
                    .then(state => {
                        // Override ui-router autoscroll 
                        this.$timeout(() => {
                        }, 500, false);
            else {
                var r = parseStateRef((<any>attrs).uiBack, this.$state.current);
                this.$state.go(r.state, r.paramExpr);

    public static factory(): ng.IDirectiveFactory {
        const directive = ($state, $rootScope, $timeout) =>
            new UiBackDirective($state, $rootScope, $timeout);
        directive.$inject = ['$state', '$rootScope', '$timeout'];
        return directive;

    .directive('uiBack', UiBackDirective.factory())
        ($rootScope: IRootScope1) => {

                (event, toState, toParams, fromState, fromParams) => {
                    if ($rootScope.uiBackData == null)
                        $rootScope.uiBackData = new UiBackData();
                    $rootScope.uiBackData.fromStateName =;
                    $rootScope.uiBackData.fromStateScroll = $(window).scrollTop();
                    $rootScope.uiBackData.fromParams = fromParams;

How to remove an element from the flow?

For the sake of completeness: The float property removes a element from the flow of the HTML too, e.g.

float: right

Moving items around in an ArrayList

Moving element with respect to each other is something I needed a lot in a project of mine. So I wrote a small util class that moves an element in an list to a position relative to another element. Feel free to use (and improve upon ;))

import java.util.List;

public class ListMoveUtil
    enum Position

     * Moves element `elementToMove` to be just before or just after `targetElement`.
     * @param list
     * @param elementToMove
     * @param targetElement
     * @param pos
    public static <T> void moveElementTo( List<T> list, T elementToMove, T targetElement, Position pos )
        if ( elementToMove.equals( targetElement ) )
        int srcIndex = list.indexOf( elementToMove );
        int targetIndex = list.indexOf( targetElement );
        if ( srcIndex < 0 )
            throw new IllegalArgumentException( "Element: " + elementToMove + " not in the list!" );
        if ( targetIndex < 0 )
            throw new IllegalArgumentException( "Element: " + targetElement + " not in the list!" );
        list.remove( elementToMove );

        // if the element to move is after the targetelement in the list, just remove it
        // else the element to move is before the targetelement. When we removed it, the targetindex should be decreased by one
        if ( srcIndex < targetIndex )
            targetIndex -= 1;
        switch ( pos )
            case AFTER:
                list.add( targetIndex + 1, elementToMove );
            case BEFORE:
                list.add( targetIndex, elementToMove );

ToggleButton in C# WinForms

Changing a CheckBox appearance to Button will give you difficulty in adjustments. You cannot change its dimensions because its size depends on the size of your text or image.

You can try this: (initialize the count variable first to 1 | int count = 1)

private void settingsBtn_Click(object sender, EventArgs e)

        if (count % 2 == 0)

It's very simple but it works.

Warning: This will work well with buttons that are occasionally used (i.e. settings), the value of count in int/long may be overloaded when used more than it's capacity without closing the app's process. (Check data type ranges:

The Good News: If you're running an app that is not intended for use 24/7 all-year round, I think this is helpful. Important thing is that when the app's process ended and you run it again, the count will reset to 1.

Python append() vs. + operator on lists, why do these give different results?

The method you're looking for is extend(). From the Python documentation:

    Add an item to the end of the list; equivalent to a[len(a):] = [x].

    Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

list.insert(i, x)
    Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

How to resolve Nodejs: Error: ENOENT: no such file or directory

If there is no layout folder.Just use like this to your routing:

app.get('/', (req, res) => {
    res.render('something', { layout: false });

Here change something with your folder name and Hope it will fix your error.

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

I had a similar issue because I did not define routing correctly for web api. Here is my solution:

public class Global : System.Web.HttpApplication { void Application_Start(object sender, EventArgs e) { GlobalConfiguration.Configuration.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = System.Web.Http.RouteParameter.Optional } );


These pages helped me:

How to find event listeners on a DOM node when debugging or from the JavaScript code?

Opera 12 (not the latest Chrome Webkit engine based) Dragonfly has had this for a while and is obviously displayed in the DOM structure. In my opinion it is a superior debugger and is the only reason remaining why I still use the Opera 12 based version (there is no v13, v14 version and the v15 Webkit based lacks Dragonfly still)

enter image description here

Single Line Nested For Loops

The best source of information is the official Python tutorial on list comprehensions. List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop.

Look at this longer list comprehension from the tutorial (the if part filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here (x,y)):

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same).

>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

The major difference between a list comprehension and a for loop is that the final part of the for loop (where you do something) comes at the beginning rather than at the end.

On to your questions:

What type must object be in order to use this for loop structure?

An iterable. Any object that can generate a (finite) set of elements. These include any container, lists, sets, generators, etc.

What is the order in which i and j are assigned to elements in object?

They are assigned in exactly the same order as they are generated from each list, as if they were in a nested for loop (for your first comprehension you'd get 1 element for i, then every value from j, 2nd element into i, then every value from j, etc.)

Can it be simulated by a different for loop structure?

Yes, already shown above.

Can this for loop be nested with a similar or different structure for loop? And how would it look?

Sure, but it's not a great idea. Here, for example, gives you a list of lists of characters:

[[ch for ch in word] for word in ("apple", "banana", "pear", "the", "hello")]

How to find lines containing a string in linux

The usual way to do this is with grep, which uses a pattern to match lines:

grep 'pattern' file

Each line which matches the pattern will be output. If you want to search for fixed strings only, use grep -F 'pattern' file.

How do I disable TextBox using JavaScript?

With the help of jquery it can be done as follows.

$("#color").prop('disabled', true);

Java: Retrieving an element from a HashSet

First of all convert your set to Array. Then, get item by index of array .

Set uniqueItem = new HashSet() ;

Object[] arrayItem = uniqueItem.toArray(); 
for(int i = 0; i < uniqueItem.size();i++){
    System.out.println("Item "+i+" "+arrayItem[i].toString());

Extracting specific selected columns to new DataFrame as a copy

The easiest way is

new = old[['A','C','D']]


Sorting using Comparator- Descending order (User defined classes)

I would create a comparator for the person class that can be parametrized with a certain sorting behaviour. Here I can set the sorting order but it can be modified to allow sorting for other person attributes as well.

public class PersonComparator implements Comparator<Person> {

  public enum SortOrder {ASCENDING, DESCENDING}

  private SortOrder sortOrder;

  public PersonComparator(SortOrder sortOrder) {
    this.sortOrder = sortOrder;

  public int compare(Person person1, Person person2) {
    Integer age1 = person1.getAge();
    Integer age2 = person2.getAge();
    int compare = Math.signum(age1.compareTo(age2));

    if (sortOrder == ASCENDING) {
      return compare;
    } else {
      return compare * (-1);

(hope it compiles now, I have no IDE or JDK at hand, coded 'blind')


Thanks to Thomas, edited the code. I wouldn't say that the usage of Math.signum is good, performant, effective, but I'd like to keep it as a reminder, that the compareTo method can return any integer and multiplying by (-1) will fail if the implementation returns Integer.MIN_INTEGER... And I removed the setter because it's cheap enough to construct a new PersonComparator just when it's needed.

But I keep the boxing because it shows that I rely on an existing Comparable implementation. Could have done something like Comparable<Integer> age1 = new Integer(person1.getAge()); but that looked too ugly. The idea was to show a pattern which could easily be adapted to other Person attributes, like name, birthday as Date and so on.

How to connect android emulator to the internet

In order to use internet via proxy on emulator try these steps it Worked for me:

Go to settings->Wireless & networks->mobile networks->Access Point Names. Press menu button. an option menu will appear.

from the option menu select New APN.

Click on Name. provide name to apn say My APN.

Click on APN. Enter www.

Click on Proxy. enter your proxy server IP. you can get it from internet explorers internet options menu.

click on Port. enter port number in my case it was 8080. you can get it from internet explorers internet options menu.

Click on User-name. provide user-name in format domain\user-name. generally it is your systems login.

Click on password. provide your systems password.

press menu button again. an option menu will appear.

press save this and try to open your browser. I think it has helped u?

How to convert a DataFrame back to normal RDD in pyspark?

@dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.

Try this:

rdd =


rdd =

Excel compare two columns and highlight duplicates

NOTE: You may want to remove duplicate items (eg duplicate entries in the same column) before doing these steps to prevent false positives.

  1. Select both columns
  2. click Conditional Formatting
  3. click Highlight Cells Rules
  4. click Duplicate Values (the defaults should be OK)
  5. Duplicates are now highlighted in red:

enter image description here

enter image description here

Class has no initializers Swift

You have to use implicitly unwrapped optionals so that Swift can cope with circular dependencies (parent <-> child of the UI components in this case) during the initialization phase.

@IBOutlet var imgBook: UIImageView!
@IBOutlet var titleBook: UILabel!
@IBOutlet var pageBook: UILabel!

Read this doc, they explain it all nicely.

Access-Control-Allow-Origin and Angular.js $http

Writing this middleware might help !

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,     Content-Type, Accept");

for details visit

dlib installation on Windows 10

After spending a lot of time, this comment gave me the right result.

  1. Download Python 3.6.8 and install, make sure you add it to PATH.

  2. Install NumPy, scipy, matplotlib and pandas in your pc/laptop with this command in command prompt:-

    pip install numpy

    pip install scipy

    pip install matplotlib

    pip install pandas

  3. Go to and right click on filename wheel-0.33.6-py2.py3-none-any.whl (21.6 kB) and copy link address. Then go to your pc/laptop, open command prompt and write this command "python -m pip install" after this command space first then paste the link copied. After install successful go to next step.

  4. Then go this link, and right click on filename "dlib-19.8.1-cp36-cp36m-win_amd64.whl" then copy link address. Then open command prompt and do the same as step 2 which is, write this command "python -m pip install" after this command space first then paste the link copied. then the dlib will be installed successfully.

  5. After that, type python and enter, then type import dlib to check dlib is installed perfectly. the you can proceed to install face which suite for python 3.6.

What's the scope of a variable initialized in an if statement?

you're executing this code from command line therefore if conditions is true and x is set. Compare:

>>> if False:
    y = 42

>>> y
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
NameError: name 'y' is not defined

iOS - Build fails with CocoaPods cannot find header files

What worked for me was selecting the Pods project, finding and selecting the target framework with the missing header in the Pod project's target directory and setting "Build Active Architecture Only" to "No" under "Architectures" in the target's build settings.

How to get name of the computer in VBA?

A shell method to read the environmental variable for this courtesy of devhut

Debug.Print CreateObject("WScript.Shell").ExpandEnvironmentStrings("%COMPUTERNAME%")

Same source gives an API method:

Option Explicit

#If VBA7 And Win64 Then
    'x64 Declarations
    Declare PtrSafe Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
    'x32 Declaration
    Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#End If

Public Sub test()

    Debug.Print ComputerName
End Sub

Public Function ComputerName() As String
    Dim sBuff                 As String * 255
    Dim lBuffLen              As Long
    Dim lResult               As Long
    lBuffLen = 255
    lResult = GetComputerName(sBuff, lBuffLen)
    If lBuffLen > 0 Then
        ComputerName = Left(sBuff, lBuffLen)
    End If
End Function

Python: Writing to and Reading from serial port should be; uses keyword arguments, not positional.

Also, you're reading from the port twice; what you probably want to do is this:

for modem in PortList:
    for port in modem:
            ser = serial.Serial(port, 9600, timeout=1)
            read_val =
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:

Best way to call a JSON WebService from a .NET Console

Although the existing answers are valid approaches , they are antiquated . HttpClient is a modern interface for working with RESTful web services . Check the examples section of the page in the link , it has a very straightforward use case for an asynchronous HTTP GET .

using (var client = new System.Net.Http.HttpClient())
    return await client.GetStringAsync(""); //uri

How do you perform a left outer join using linq extension methods

Whilst the accepted answer works and is good for Linq to Objects it bugged me that the SQL query isn't just a straight Left Outer Join.

The following code relies on the LinkKit Project that allows you to pass expressions and invoke them to your query.

static IQueryable<TResult> LeftOuterJoin<TSource,TInner, TKey, TResult>(
     this IQueryable<TSource> source, 
     IQueryable<TInner> inner, 
     Expression<Func<TSource,TKey>> sourceKey, 
     Expression<Func<TInner,TKey>> innerKey, 
     Expression<Func<TSource, TInner, TResult>> result
    ) {
    return from a in source.AsExpandable()
            join b in inner on sourceKey.Invoke(a) equals innerKey.Invoke(b) into c
            from d in c.DefaultIfEmpty()
            select result.Invoke(a,d);

It can be used as follows

Table1.LeftOuterJoin(Table2, x => x.Key1, x => x.Key2, (x,y) => new { x,y});

EPPlus - Read Excel Table

Below code will read excel data into a datatable, which is converted to list of datarows.

if (FileUpload1.HasFile)
    if (Path.GetExtension(FileUpload1.FileName) == ".xlsx")
        Stream fs = FileUpload1.FileContent;
        ExcelPackage package = new ExcelPackage(fs);
        DataTable dt = new DataTable();
        dt= package.ToDataTable();
        List<DataRow> listOfRows = new List<DataRow>();
        listOfRows = dt.AsEnumerable().ToList();

using OfficeOpenXml;
using System.Data;
using System.Linq;

 public static class ExcelPackageExtensions
        public static DataTable ToDataTable(this ExcelPackage package)
            ExcelWorksheet workSheet = package.Workbook.Worksheets.First();
            DataTable table = new DataTable();
            foreach (var firstRowCell in workSheet.Cells[1, 1, 1, workSheet.Dimension.End.Column])

            for (var rowNumber = 2; rowNumber <= workSheet.Dimension.End.Row; rowNumber++)
                var row = workSheet.Cells[rowNumber, 1, rowNumber, workSheet.Dimension.End.Column];
                var newRow = table.NewRow();
                foreach (var cell in row)
                    newRow[cell.Start.Column - 1] = cell.Text;
            return table;


How do I escape a reserved word in Oracle?

From a quick search, Oracle appears to use double quotes (", eg "table") and apparently requires the correct case—whereas, for anyone interested, MySQL defaults to using backticks (`) except when set to use double quotes for compatibility.

How to assign the output of a Bash command to a variable?

In this specific case, note that bash has a variable called PWD that contains the current directory: $PWD is equivalent to `pwd`. (So do other shells, this is a standard feature.) So you can write your script like this:

until [ "$PWD" = "/" ]; do
  echo "$PWD"
  ls && cd .. && ls 

Note the use of double quotes around the variable references. They are necessary if the variable (here, the current directory) contains whitespace or wildcards (\[?*), because the shell splits the result of variable expansions into words and performs globbing on these words. Always double-quote variable expansions "$foo" and command substitutions "$(foo)" (unless you specifically know you have not to).

In the general case, as other answers have mentioned already:

  • You can't use whitespace around the equal sign in an assignment: var=value, not var = value
  • The $ means “take the value of this variable”, so you don't use it when assigning: var=value, not $var=value.

make an html svg object also a clickable link

The easiest way is to not use <object>. Instead use an <img> tag and the anchor should work just fine.

How can I run Android emulator for Intel x86 Atom without hardware acceleration on Windows 8 for API 21 and 19?

yes is possible to run your android emulator without have a hardware accelerator. In fact to do that, you need to open your android virtual device. When you reached to system image configure, it suggest you which version of android image you want to use. Whatever version of android system image that you select,you need to make sure that,ABI is armeabi-v7a and, you target is System image ameabi-v7a with google APIs. And then complete the rest of task and check out your emulator.

Find stored procedure by name

For SQL Server version 9.0 (2005), you can use the code below:

select * 
syscomments c
inner join sys.procedures p on p.object_id =
where like '%usp_ConnectionsCount%';

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

Here is an option that's easier to extend than yours, but no, there is none built into the library itself.

private static List<string> suffixes = new List<string> { " B", " KB", " MB", " GB", " TB", " PB" };
public static string Foo(int number)
    for (int i = 0; i < suffixes.Count; i++)
        int temp = number / (int)Math.Pow(1024, i + 1);
        if (temp == 0)
            return (number / (int)Math.Pow(1024, i)) + suffixes[i];
    return number.ToString();

Stored procedure - return identity as output parameter or scalar

SELECT IDENT_CURRENT('databasename.dbo.tablename') AS your identity column;

Char Comparison in C

In C the char type has a numeric value so the > operator will work just fine for example

#include <stdio.h>
main() {

    char a='z';

    char b='h';

    if ( a > b ) {
        printf("%c greater than %c\n",a,b);

PyCharm import external library

Answer for PyCharm 2016.1 on OSX: (This is an update to the answer by @GeorgeWilliams993's answer above, but I don't have the rep yet to make comments.)

Go to Pycharm menu --> Preferences --> Project: (projectname) --> Project Interpreter

At the top is a popup for "Project Interpreter," and to the right of it is a button with ellipses (...) - click on this button for a different popup and choose "More" (or, as it turns out, click on the main popup and choose "Show All").

This shows a list of interpreters, with one selected. At the bottom of the screen are a set of tools... pick the rightmost one:

Show path for the selected interpreter button

Now you should see all the paths pycharm is searching to find imports, and you can use the "+" button at the bottom to add a new path.

I think the most significant difference from @GeorgeWilliams993's answer is that the gear button has been replaced by a set of ellipses. That threw me off.

Executing a command stored in a variable from PowerShell

Here is yet another way without Invoke-Expression but with two variables (command:string and parameters:array). It works fine for me. Assume 7z.exe is in the system path.

$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\', 'C:\TEMP\with space\changelog'

& $cmd $prm

If the command is known (7z.exe) and only parameters are variable then this will do

$prm = 'a', '-tzip', 'c:\temp\with space\', 'C:\TEMP\with space\changelog'

& 7z.exe $prm

BTW, Invoke-Expression with one parameter works for me, too, e.g. this works

$cmd = '& 7z.exe a -tzip "c:\temp\with space\" "C:\TEMP\with space\changelog"'

Invoke-Expression $cmd

P.S. I usually prefer the way with a parameter array because it is easier to compose programmatically than to build an expression for Invoke-Expression.

In bootstrap how to add borders to rows without adding up?

You can simply use the border class from bootstrap:

<div class="row border border-dark">

For more details visit the following link: Borders

Oracle insert if not exists statement

Another approach would be to leverage the INSERT ALL syntax from oracle,

    INTO table1(email, campaign_id) VALUES (email, campaign_id)
WITH source_data AS
 (SELECT '[email protected]' email,100 campaign_id
  FROM   dual
  SELECT '[email protected]' email,200 campaign_id
  FROM   dual)      
SELECT email
FROM   source_data src
        FROM   table1 dest
        WHERE =
        AND    src.campaign_id = dest.campaign_id);

INSERT ALL also allow us to perform a conditional insert into multiple tables based on a sub query as source.

There are some really clean and nice examples are there to refer.


Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"


For example:


matplotlib: how to change data points color based on some variable

This is what matplotlib.pyplot.scatter is for.

As a quick example:

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
t = np.linspace(0, 2 * np.pi, 20)
x = np.sin(t)
y = np.cos(t)


enter image description here

Push an associative item into an array in JavaScript

Another method for creating a JavaScript associative array

First create an array of objects,

 var arr = {'name': []};

Next, push the value to the object.

  var val = 2;

To read from it:

var val =[0];

Always show vertical scrollbar in <select>

It will work in IE7. But here you need to fixed the size less than the number of option and not use overflow-y:scroll. In your example you have 2 option but you set size=10, which will not work.

Suppose your select has 10 option, then fixed size=9.

Here, in your code reference you used height:100px with size:2. I remove the height css, because its not necessary and change the size:5 and it works fine.

Here is your modified code from jsfiddle:

<select size="5" style="width:100px;">

this will generate a larger select box than size:2 create.In case of small size the select box will not display the scrollbar,you have to check with appropriate size quantity.Without scrollbar it will work if click on the upper and lower icons of scrollbar.I show both example in your fiddle with size:2 and size greater than 2(e.g: 3,5).

Here is your desired result. I think this will help you:


    border: 1px dashed red;
    height: 150px;
    overflow-x: hidden;
    overflow-y: scroll;
    width: 150px;
 .wrapper .selection{
   border:1px solid #ccc


<div class="wrapper">
<select size="15" class="selection">
    <option>Item 1</option>
    <option>Item 2</option>
    <option>Item 3</option>

Is there a way to specify which pytest tests to run from a file?

Here's a possible partial answer, because it only allows selecting the test scripts, not individual tests within those scripts.

And it also limited by my using legacy compatibility mode vs unittest scripts, so not guaranteeing it would work with native pytest.

Here goes:

  1. create a new dictory, say subset_tests_directory.
  2. ln -s tests_directory/
  3. ln -s tests_directory/

  4. be careful about imports which implicitly assume files are in test_directory. I had to fix several of those by running python, from within subset_tests_directory and correcting as needed.

  5. Once the test scripts execute correctly, just cd subset_tests_directory and pytest there. Pytest will only pick up the scripts it sees.

Another possibility is symlinking within your current test directory, say as ln -s then pytest subset*.py. That would avoid needing to adjust your imports, but it would clutter things up until you removed the symlinks. Worked for me as well.

How to Reload ReCaptcha using JavaScript?

Important: Version 1.0 of the reCAPTCHA API is no longer supported, please upgrade to Version 2.0.

You can use grecaptcha.reset(); to reset the captcha.

Source :

How to Delete a directory from Hadoop cluster which is having comma(,) in its name?

Run the command in the terminal

$hadoop fs -rm -r /path/to/directory

How do I check if a string is unicode or ascii?


import six
if isinstance(obj, six.text_type)

inside the six library it is represented as:

if PY3:
    string_types = str,
    string_types = basestring,

String format currency

I strongly suspect the problem is simply that the current culture of the thread handling the request isn't set appropriately.

You can either set it for the whole request, or specify the culture while formatting. Either way, I would suggest not use string.Format with a composite format unless you really have more than one thing to format (or a wider message). Instead, I'd use:

@price.ToString("C", culture)

It just makes it somewhat simpler.

EDIT: Given your comment, it sounds like you may well want to use a UK culture regardless of the culture of the user. So again, either set the UK culture as the thread culture for the whole request, or possibly introduce your own helper class with a "constant":

public static class Cultures
    public static readonly CultureInfo UnitedKingdom = 


@price.ToString("C", Cultures.UnitedKingdom)

In my experience, having a "named" set of cultures like this makes the code using it considerably simpler to read, and you don't need to get the string right in multiple places.

How do I set up a private Git repository on GitHub? Is it even possible?

If you are a student you can get a free private repository at


As noted in another answer, now there is an option for private repos also for simple users

Difference between and e.currentTarget

It's worth noting that can be useful, for example, for using a single listener to trigger different actions. Let's say you have the typical "menu" sprite with 10 buttons inside, so instead of doing:

menu.button1.addEventListener(MouseEvent.CLICK, doAction1);
menu.button2.addEventListener(MouseEvent.CLICK, doAction2);

You can simply do:

menu.addEventListener(MouseEvent.CLICK, doAction);

And trigger a different action within doAction(event) depending on the (using it's name property, etc...)

Python copy files to a new directory and rename if file name already exists

I would say you have an indentation problem, at least as you wrote it here:

while not os.path.exists(file + "_" + str(i) + extension):
   print "Already 2x exists..."
   print "Renaming"
   shutil.copy(path, file + "_" + str(i) + extension)

should be:

while os.path.exists(file + "_" + str(i) + extension):
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)

Check this out, please!

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

Something like the following example. Note I'm in Eastern Australia (UTC + 10 hours at the moment).

>>> import datetime
>>> dtnow =;dtutcnow = datetime.datetime.utcnow()
>>> dtnow
datetime.datetime(2010, 8, 4, 9, 33, 9, 890000)
>>> dtutcnow
datetime.datetime(2010, 8, 3, 23, 33, 9, 890000)
>>> delta = dtnow - dtutcnow
>>> delta
datetime.timedelta(0, 36000)
>>> hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60)
>>> hh,mm
(10, 0)
>>> "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)

Drop primary key using script in SQL Server database

simply click

'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'

and run the below query is :

Query:alter Table 'TableName' drop constraint PK__TableName__30242045

Read file content from S3 bucket with boto3

Using the client instead of resource:

s3 = boto3.client('s3')
result = s3.list_objects(Bucket = bucket, Prefix='/something/')
for o in result.get('Contents'):
    data = s3.get_object(Bucket=bucket, Key=o.get('Key'))
    contents = data['Body'].read()

Underline text in UIlabel

As kovpas has shown you can use the bounding box in most cases, although it is not always guaranteed that the bounding box will fit neatly around the text. A box with a height of 50 and font size of 12 may not give the results you want depending on the UILabel configuration.

Query the UIString within the UILabel to determine its exact metrics and use these to better place your underline regardless of the enclosing bounding box or frame using the drawing code already provided by kovpas.

You should also look at UIFont's "leading" property that gives the distance between baselines based on a particular font. The baseline is where you would want your underline to be drawn.

Look up the UIKit additions to NSString:

(CGSize)sizeWithFont:(UIFont *)font 
//Returns the size of the string if it were to be rendered with the specified font on a single line.

(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size 
// Returns the size of the string if it were rendered and constrained to the specified size.

(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
//Returns the size of the string if it were rendered with the specified constraints.

jQuery: Get height of hidden element in jQuery

You could do something like this, a bit hacky though, forget position if it's already absolute:

var previousCss  = $("#myDiv").attr("style");

    position:   'absolute', // Optional if #myDiv is already absolute
    visibility: 'hidden',
    display:    'block'

optionHeight = $("#myDiv").height();

$("#myDiv").attr("style", previousCss ? previousCss : "");

Python send POST with header

If we want to add custom HTTP headers to a POST request, we must pass them through a dictionary to the headers parameter.

Here is an example with a non-empty body and headers:

import requests
import json

url = ''
body = {'name': 'Maryja'}
headers = {'content-type': 'application/json'}

r =, data=json.dumps(body), headers=headers)


Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:


Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:


Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:


Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

Compute mean and standard deviation by group for multiple variables in a data.frame

Here's another take on the data.table answers, using @Carson's data, that's a bit more readable (and also a little faster, because of using lapply instead of sapply):

dt = data.table(ID=c(1:3), Obs_1=rnorm(9), Obs_2=rnorm(9), Obs_3=rnorm(9))

dt[, c(mean = lapply(.SD, mean), sd = lapply(.SD, sd)), by = ID]
#   ID mean.Obs_1 mean.Obs_2 mean.Obs_3  sd.Obs_1  sd.Obs_2  sd.Obs_3
#1:  1  0.4854187 -0.3238542  0.7410611 1.1108687 0.2885969 0.1067961
#2:  2  0.4171586 -0.2397030  0.2041125 0.2875411 1.8732682 0.3438338
#3:  3 -0.3601052  0.8195368 -0.4087233 0.8105370 0.3829833 1.4705692

Create an ArrayList with multiple object types?


   ArrayList<Object> list = new ArrayList <>();`     


 ArrayList arraylist = new ArrayList();

How long will my session last?

In general you can say session.gc_maxlifetime specifies the maximum lifetime since the last change of your session data (not the last time session_start was called!). But PHP’s session handling is a little bit more complicated.

Because the session data is removed by a garbage collector that is only called by session_start with a probability of session.gc_probability devided by session.gc_divisor. The default values are 1 and 100, so the garbage collector is only started in only 1% of all session_start calls. That means even if the the session is already timed out in theory (the session data had been changed more than session.gc_maxlifetime seconds ago), the session data can be used longer than that.

Because of that fact I recommend you to implement your own session timeout mechanism. See my answer to How do I expire a PHP session after 30 minutes? for more details.

How to find a hash key containing a matching value

The best way to find the key for a particular value is to use key method that is available for a hash....

gender = {"MALE" => 1, "FEMALE" => 2}
gender.key(1) #=> MALE

I hope it solves your problem...

How to Convert JSON object to Custom C# object?

JSON.Net is your best bet but, depending on the shape of the objects and whether there are circular dependencies, you could use JavaScriptSerializer or DataContractSerializer.

How to install Ruby 2.1.4 on Ubuntu 14.04

Use RVM (Ruby Version Manager) to install and manage any versions of Ruby. You can have multiple versions of Ruby installed on the machine and you can easily select the one you want.

To install RVM type into terminal:

\curl -sSL | bash -s stable

And let it work. After that you will have RVM along with Ruby installed.

Source: RVM Site

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

import re

htmlString = '</dd><dt> Fine, thank you.&#160;</dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'

SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))'

Result ='utf-8'), htmlString.decode('utf-8'), re.I | re.U)

print Result.groups()

Works that way. The expression contains non-latin characters, so it usually fails. You've got to decode into Unicode and use re.U (Unicode) flag.

I'm a beginner too and I faced that issue a couple of times myself.

onSaveInstanceState () and onRestoreInstanceState ()

The state you save at onSaveInstanceState() is later available at onCreate() method invocation. So use onCreate (and its Bundle parameter) to restore state of your activity.

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

My guess is that $_.Name does not exist.

If I were you, I'd bring the script into the ISE and run it line for line till you get there then take a look at the value of $_

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

As we recently posted on the React blog, in the vast majority of cases you don't need getDerivedStateFromProps at all.

If you just want to compute some derived data, either:

  1. Do it right inside render
  2. Or, if re-calculating it is expensive, use a memoization helper like memoize-one.

Here's the simplest "after" example:

import memoize from "memoize-one";

class ExampleComponent extends React.Component {
  getDerivedData = memoize(computeDerivedState);

  render() {
    const derivedData = this.getDerivedData(this.props.someValue);
    // ...

Check out this section of the blog post to learn more.

Exit single-user mode

I tried this is working


Setting up a git remote origin

For anyone who comes here, as I did, looking for the syntax to change origin to a different location you can find that documentation here: Using git remote add to do this will result in "fatal: remote origin already exists."

Nutshell: git remote set-url origin

(The marked answer is correct, I'm just hoping to help anyone as lost as I was... haha)

Angular: Cannot find a differ supporting object '[object Object]'

This ridiculous error message merely means there's a binding to an array that doesn't exist.

  *ngFor="let option of setting.options"
  >{{ option }}

In the example above the value of setting.options is undefined. To fix, press F12 and open developer window. When the the get request returns the data look for the values to contain data.

If data exists, then make sure the binding name is correct

//was the property name correct? 

If the data exists, is it an Array?

If the data doesn't exist then fix it on the backend.

python uninstall

For me, the following mostly works:

have pip installed, e.g.:

$ easy_install pip

Check, how is your installed package named from pip point of view:

$ pip freeze

This shall list names of all packages, you have installed (and which were detected by pip). The name can be sometime long, then use just the name of the package being shown at the and after #egg=. You can also in most cases ignore the version part (whatever follows == or -).

Then uninstall the package:

$ pip uninstall

If it asks for confirmation about removing the package, then you are lucky guy and it will be removed.

pip shall detect all packages, which were installed by pip. It shall also detect most of the packages installed via easy_install or, but this may in some rare cases fail.

Here is real sample from my local test with package named ttr.rdstmc on MS Windows.

$ pip freeze |grep ttr

$ python develop
Finished processing dependencies for ttr.rdstmc==0.0.1dev

$ pip freeze |grep ttr
-e hg+https://[email protected]/vlcinsky/ttr.rdstmc@d61a9922920c508862602f7f39e496f7b99315f0#egg=ttr.rdstmc-dev

$ pip uninstall ttr.rdstmc
Uninstalling ttr.rdstmc:
Proceed (y/n)? y
  Successfully uninstalled ttr.rdstmc

$ pip freeze |grep ttr

Edit 2015-05-20

All what is written above still applies, anyway, there are small modifications available now.

Install pip in python 2.7.9 and python 3.4

Recent python versions come with a package ensurepip allowing to install pip even when being offline:

$ python -m ensurepip --upgrade

On some systems (like Debian Jessie) this is not available (to prevent breaking system python installation).

Using grep or find

Examples above assume, you have grep installed. I had (at the time I had MS Windows on my machine) installed set of linux utilities (incl. grep). Alternatively, use native MS Windows find or simply ignore that filtering and find the name in a bit longer list of detected python packages.

How to define Singleton in TypeScript

You can also make use of the function Object.Freeze(). Its simple and easy:

class Singleton {

  instance: any = null;
  data: any = {} // store data in here

  constructor() {
    if (!this.instance) {
      this.instance = this;
    return this.instance

const singleton: Singleton = new Singleton();

export default singleton;

Open directory dialog

You can use the built-in FolderBrowserDialog class for this. Don't mind that it's in the System.Windows.Forms namespace.

using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
    System.Windows.Forms.DialogResult result = dialog.ShowDialog();

If you want the window to be modal over some WPF window, see the question How to use a FolderBrowserDialog from a WPF application.

EDIT: If you want something a bit more fancy than the plain, ugly Windows Forms FolderBrowserDialog, there are some alternatives that allow you to use the Vista dialog instead:

  • Third-party libraries, such as Ookii dialogs (.NET 4.5+)

  • The Windows API Code Pack-Shell:

      using Microsoft.WindowsAPICodePack.Dialogs;
      var dialog = new CommonOpenFileDialog();
      dialog.IsFolderPicker = true;
      CommonFileDialogResult result = dialog.ShowDialog();

    Note that this dialog is not available on operating systems older than Windows Vista, so be sure to check CommonFileDialog.IsPlatformSupported first.

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().

In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

Responsive image map

You can also use svg instead of an image map. ;)

There is a tutorial on how to do this.

.hover_group:hover {_x000D_
  opacity: 1;_x000D_
#projectsvg {_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  padding-bottom: 77%;_x000D_
  vertical-align: middle;_x000D_
  margin: 0;_x000D_
  overflow: hidden;_x000D_
#projectsvg svg {_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
<figure id="projectsvg">_x000D_
  <svg version="1.1" xmlns="" xmlns:xlink="" viewBox="0 0 1920 1080" preserveAspectRatio="xMinYMin meet" >_x000D_
<!-- set your background image -->_x000D_
<image width="1920" height="1080" xlink:href="" />_x000D_
<g class="hover_group" opacity="0">_x000D_
  <a xlink:href="">_x000D_
    <text x="652" y="706.9" font-size="20">First zone</text>_x000D_
    <rect x="572" y="324.1" opacity="0.2" fill="#FFFFFF" width="264.6" height="387.8"></rect>_x000D_
<g class="hover_group" opacity="0">_x000D_
  <a xlink:href="">_x000D_
    <text x="1230.7" y="952" font-size="20">Second zone</text>_x000D_
    <rect x="1081.7" y="507" opacity="0.2" fill="#FFFFFF" width="390.2" height="450"></rect>_x000D_

Android: making a fullscreen application

Simply declare in styles.xml

  <style name="AppTheme.Fullscreen" parent="AppTheme">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>

Then use in menifest.xml

            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />

Chill Pill :)

Java - How to access an ArrayList of another class?

Put them in an arrayList in your first class like:

import java.util.ArrayList;
    public class numbers {

    private int number1 = 50;
    private int number2 = 100;

    public ArrayList<int> getNumberList() {
        ArrayList<int> numbersList= new ArrayList<int>();
        return numberList;

Then, in your test class you can call numbers.getNumberList() to get your arrayList. In addition, you might want to create methods like addToList / removeFromList in your numbers class so you can handle it the way you need it.

You can also access a variable declared in one class from another simply like


if you have it declared there as public.

But it isn't such a good practice in my opinion, since you probably need to modify this list in your code later. Note that you have to add your class to the import list.

If you can tell me what your app requirements are, i'll be able tell you more precise what i think it's best to do.

Logical operators ("and", "or") in DOS batch

If you have interested to write an if+AND/OR in one statement, then there is no any of it. But, you can still group if with &&/|| and (/) statements to achieve that you want in one line w/o any additional variables and w/o if-else block duplication (single echo command for TRUE and FALSE code sections):

@echo off


set "A=1" & set "B=2" & call :IF_AND
set "A=1" & set "B=3" & call :IF_AND
set "A=2" & set "B=2" & call :IF_AND
set "A=2" & set "B=3" & call :IF_AND


set "A=1" & set "B=2" & call :IF_OR
set "A=1" & set "B=3" & call :IF_OR
set "A=2" & set "B=2" & call :IF_OR
set "A=2" & set "B=3" & call :IF_OR

exit /b 0

( ( if %A% EQU 1 ( type nul>nul ) else type 2>nul ) || ( if %B% EQU 2 ( type nul>nul ) else type 2>nul ) || ( echo.FALSE-& type 2>nul ) ) && echo TRUE+

exit /b 0

( ( if %A% EQU 1 ( type nul>nul ) else type 2>nul ) && ( if %B% EQU 2 ( type nul>nul ) else type 2>nul ) && echo.TRUE+ ) || echo.FALSE-

exit /b 0




The trick is in the type command which drops/sets the errorlevel and so handles the way to the next command.

Fill DataTable from SQL Server database

If the variable table contains invalid characters (like a space) you should add square brackets around the variable.

public DataTable fillDataTable(string table)
    string query = "SELECT * FROM dstut.dbo.[" + table + "]";

    using(SqlConnection sqlConn = new SqlConnection(conSTR))
    using(SqlCommand cmd = new SqlCommand(query, sqlConn))
        DataTable dt = new DataTable();
        return dt;

By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input

Routing with Multiple Parameters using ASP.NET MVC

Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:

public ActionResult GetImages(string artistName, string apiKey)

MVC will auto-populate the parameters when given a URL like:


One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:

public ActionResult GetImages(string id, string apiKey)

would be populated correctly with a URL like the following:


In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:

            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults

If you wanted to support a url like


you could add a route like:

            "ArtistImages",                                              // Route name
            "{controller}/{action}/{artistName}/{apikey}",                           // URL with parameters
            new { controller = "Home", action = "Index", artistName = "", apikey = "" }  // Parameter defaults

and a method like the first example above.

Phone validation regex

enter image description hereThis solution actually validates the numbers and the format. For example: 123-456-7890 is a valid format but is NOT a valid US number and this answer bears that out where others here do not.

If you do not want the extension capability remove the following including the parenthesis: (?:\s*(?:#|x.?|ext.?|extension)\s*(\d+)\s*)? :)

edit (addendum) I needed this in a client side only application so I converted it. Here it is for the javascript folks:

var myPhoneRegex = /(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]??)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]??|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})\s*(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+)\s*)?$/i;
if (myPhoneRegex.test(phoneVar)) {
    // Successful match
} else {
    // Match attempt failed

hth. end edit

This allows extensions or not and works with .NET


To validate with or without trailing spaces. Perhaps when using .NET validators and trimming server side use this slightly different regex:


All valid:

1 800 5551212

800 555 1212



+1800 555 1212 extension65432

800 5551212 ext3333

Invalid #s




EDIT: Based on Felipe's comment I have updated this for international.

Based on what I could find out from here and here regarding valid global numbers

This is tested as a first line of defense of course. An overarching element of the international number is that it is no longer than 15 characters. I did not write a replace for all the non digits and sum the result. It should be done for completeness. Also, you may notice that I have not combined the North America regex with this one. The reason is that this international regex will match North American numbers, however, it will also accept known invalid # such as +1 234-911-5678. For more accurate results you should separate them as well.

Pauses and other dialing instruments are not mentioned and therefore invalid per E.164

\(?\+[0-9]{1,3}\)? ?-?[0-9]{1,3} ?-?[0-9]{3,5} ?-?[0-9]{4}( ?-?[0-9]{3})?

With 1-10 letter word for extension and 1-6 digit extension:

\(?\+[0-9]{1,3}\)? ?-?[0-9]{1,3} ?-?[0-9]{3,5} ?-?[0-9]{4}( ?-?[0-9]{3})? ?(\w{1,10}\s?\d{1,6})?

Valid International: Country name for ref its not a match.

+55 11 99999-5555 Brazil

+593 7 282-3889 Ecuador

(+44) 0848 9123 456 UK

+1 284 852 5500 BVI

+1 345 9490088 Grand Cayman

+32 2 702-9200 Belgium

+65 6511 9266 Asia Pacific

+86 21 2230 1000 Shanghai

+9124 4723300 India

+821012345678 South Korea

And for your extension pleasure

+55 11 99999-5555 ramal 123 Brazil

+55 11 99999-5555 foo786544 Brazil


How to play .wav files with java

The snippet here works fine, tested with windows sound:

public static void main(String[] args) {
        AePlayWave aw = new AePlayWave( "C:\\WINDOWS\\Media\\tada.wav" );

Removing leading zeroes from a field in a SQL statement

To remove leading 0, You can multiply number column with 1 Eg: Select (ColumnName * 1)

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: Connection refused

& I resolved it following way.

   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();


How do I exclude Weekend days in a SQL Server query?

The answer depends on your server's week-start set up, so it's either

SELECT [date_created] FROM table WHERE DATEPART(w,[date_created]) NOT IN (7,1)

if Sunday is the first day of the week for your server


SELECT [date_created] FROM table WHERE DATEPART(w,[date_created]) NOT IN (6,7)

if Monday is the first day of the week for your server

Comment if you've got any questions :-)

How to skip a iteration/loop in while-loop

You're looking for the continue; statement.

ERROR: Cannot open source file " "

  1. Copy the contents of the file,
  2. Create an .h file, give it the name of the original .h file
  3. Copy the contents of the original file to the newly created one
  4. Build it
  5. VOILA!!

How to call code behind server method from a client side JavaScript function?

I had to register my buttonid as a postbacktrigger...


System.Net.WebException HTTP status code

(I do realise the question is old, but it's among the top hits on Google.)

A common situation where you want to know the response code is in exception handling. As of C# 7, you can use pattern matching to actually only enter the catch clause if the exception matches your predicate:

catch (WebException ex) when (ex.Response is HttpWebResponse response)

This can easily be extended to further levels, such as in this case where the WebException was actually the inner exception of another (and we're only interested in 404):

catch (StorageException ex) when (ex.InnerException is WebException wex && wex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.NotFound)

Finally: note how there's no need to re-throw the exception in the catch clause when it doesn't match your criteria, since we don't enter the clause in the first place with the above solution.

1030 Got error 28 from storage engine

To expand on this (even though it is an older question); It is not not about the MySQL space itself probably, but about space in general, assuming for tmp files or something like that. My mysql data dir was not full, the / (root) partition was

How can I convert string date to NSDate?

 func convertDateFormatter(date: String) -> String

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let date = dateFormatter.dateFromString(date)

    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let timeStamp = dateFormatter.stringFromDate(date!)

    return timeStamp

Updated for Swift 3.

func convertDateFormatter(date: String) -> String

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let date = date)

    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let timeStamp = dateFormatter.string(from: date!)

    return timeStamp

Ignoring NaNs with str.contains

You can also patern :

DF[DF.col.str.contains(pat = '(foo)', regex = True) ]

list.clear() vs list = new ArrayList<Integer>();

I think that the answer is that it depends on a whole range of factors such as:

  • whether the list size can be predicted beforehand (i.e. can you set the capacity accurately),
  • whether the list size is variable (i.e. each time it is filled),
  • how long the lifetime of the list will be in both versions, and
  • your heap / GC parameters and CPU.

These make it hard to predict which will be better. But my intuition is that the difference will not be that great.

Two bits of advice on optimization:

  • Don't waste time trying to optimize this ... unless the application is objectively too slow AND measurement using a profiler tells you that this is a performance hotspot. (The chances are that one of those preconditions won't be true.)

  • If you do decide to optimize this, do it scientifically. Try both (all) of the alternatives and decide which is best by measuring the performance in your actual application on a realistic problem / workload / input set. (An artificial benchmark is liable to give you answers that do not predict real-world behavior, because of factors like those I listed previously.)

How to stop (and restart) the Rails Server?

On OSX, you can take advantage of the UNIX-like command line - here's what I keep handy in my .bashrc to enable me to more easily restart a server that's running in background (-d) mode (note that you have to be in the Rails root directory when running this):

alias restart_rails='kill -9 `cat tmp/pids/`; rails server -d'

My initial response to the comment by @zane about how the PID file isn't removed was that it might be behavior dependent on the Rails version or OS type. However, it's also possible that the shell runs the second command (rails server -d) sooner than the kill can actually cause the previous running instance to stop.

So alternatively, kill -9 cat tmp/pids/ && rails server -d might be more robust; or you can specifically run the kill, wait for the tmp/pids folder to empty out, then restart your new server.

How to use bitmask?

Let's say I have 32-bit ARGB value with 8-bits per channel. I want to replace the alpha component with another alpha value, such as 0x45

unsigned long alpha = 0x45
unsigned long pixel = 0x12345678;
pixel = ((pixel & 0x00FFFFFF) | (alpha << 24));

The mask turns the top 8 bits to 0, where the old alpha value was. The alpha value is shifted up to the final bit positions it will take, then it is OR-ed into the masked pixel value. The final result is 0x45345678 which is stored into pixel.

Javascript String to int conversion

JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:

var numberAsInt = parseInt(number, 10);  
// Second arg is radix, 10 is decimal.

If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.