Programs & Examples On #Space tree

How to add column if not exists on PostgreSQL?

the below function will check the column if exist return appropriate message else it will add the column to the table.

create or replace function addcol(schemaname varchar, tablename varchar, colname varchar, coltype varchar)
returns varchar 
language 'plpgsql'
as 
$$
declare 
    col_name varchar ;
begin 
      execute 'select column_name from information_schema.columns  where  table_schema = ' ||
      quote_literal(schemaname)||' and table_name='|| quote_literal(tablename) || '   and    column_name= '|| quote_literal(colname)    
      into   col_name ;   

      raise info  ' the val : % ', col_name;
      if(col_name is null ) then 
          col_name := colname;
          execute 'alter table ' ||schemaname|| '.'|| tablename || ' add column '|| colname || '  ' || coltype; 
      else
           col_name := colname ||' Already exist';
      end if;
return col_name;
end;
$$

Angular 2 two way binding using ngModel is not working

Angular 2 Beta

This answer is for those who use Javascript for angularJS v.2.0 Beta.

To use ngModel in your view you should tell the angular's compiler that you are using a directive called ngModel.

How?

To use ngModel there are two libraries in angular2 Beta, and they are ng.common.FORM_DIRECTIVES and ng.common.NgModel.

Actually ng.common.FORM_DIRECTIVES is nothing but group of directives which are useful when you are creating a form. It includes NgModel directive also.

app.myApp = ng.core.Component({
    selector: 'my-app',
    templateUrl: 'App/Pages/myApp.html',
    directives: [ng.common.NgModel] // specify all your directives here
}).Class({
    constructor: function () {
        this.myVar = {};
        this.myVar.text = "Testing";
    },

});

How do I pass a variable by reference?

Here is the simple (I hope) explanation of the concept pass by object used in Python.
Whenever you pass an object to the function, the object itself is passed (object in Python is actually what you'd call a value in other programming languages) not the reference to this object. In other words, when you call:

def change_me(list):
   list = [1, 2, 3]

my_list = [0, 1]
change_me(my_list)

The actual object - [0, 1] (which would be called a value in other programming languages) is being passed. So in fact the function change_me will try to do something like:

[0, 1] = [1, 2, 3]

which obviously will not change the object passed to the function. If the function looked like this:

def change_me(list):
   list.append(2)

Then the call would result in:

[0, 1].append(2)

which obviously will change the object. This answer explains it well.

PHP Fatal error: Cannot access empty property

I realise this answer is not a direct response to the problem described by the OP, but I found this question as a result of searching for the same error message. I thought it worth posting my experience here just in case anybody is muddling over the same thing...

You can encounter the error in question as a result of a poorly formatted for loop over an associative array. In a fit of bone-headedness, I was using -> instead of => in my for statement:

        foreach ($object->someArray as $key->$val) {
            // do something
        }

Of course, I should have had:

        foreach ($object->someArray as $key=>$val) {
            // do something
        }

I confused myself at first, thinking the reported error was referring to the someArray property!

How to add a button to UINavigationBar?

swift 3

    let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(cancelPressed(_:)))
    cancelBarButton.setTitleTextAttributes( [NSFontAttributeName : UIFont.cancelBarButtonFont(),
                                                          NSForegroundColorAttributeName : UIColor.white], for: .normal)
    self.navigationItem.leftBarButtonItem = cancelBarButton


    func cancelPressed(_ sender: UIBarButtonItem ) {
        self.dismiss(animated: true, completion: nil)
    }

How to copy only a single worksheet to another workbook using vba

The much longer example below combines some of the useful snippets above:

  • You can specify any number of sheets you want to copy across
  • You can copy entire sheets, i.e. like dragging the tab across, or you can copy over the contents of cells as values-only but preserving formatting.

It could still do with a lot of work to make it better (better error-handling, general cleaning up), but it hopefully provides a good start.

Note that not all formatting is carried across because the new sheet uses its own theme's fonts and colours. I can't work out how to copy those across when pasting as values only.

 Option Explicit

Sub copyDataToNewFile()
    Application.ScreenUpdating = False

    ' Allow different ways of copying data:
    ' sheet = copy the entire sheet
    ' valuesWithFormatting = create a new sheet with the same name as the
    '                        original, copy values from the cells only, then
    '                        apply original formatting. Formatting is only as
    '                        good as the Paste Special > Formats command - theme
    '                        colours and fonts are not preserved.
    Dim copyMethod As String
    copyMethod = "valuesWithFormatting"

    Dim newFilename As String           ' Name (+optionally path) of new file
    Dim themeTempFilePath As String     ' To temporarily save the source file's theme

    Dim sourceWorkbook As Workbook      ' This file
    Set sourceWorkbook = ThisWorkbook

    Dim newWorkbook As Workbook         ' New file

    Dim sht As Worksheet                ' To iterate through sheets later on.
    Dim sheetFriendlyName As String     ' To store friendly sheet name
    Dim sheetCount As Long              ' To avoid having to count multiple times

    ' Sheets to copy over, using internal code names as more reliable.
    Dim colSheetObjectsToCopy As New Collection
    colSheetObjectsToCopy.Add Sheet1
    colSheetObjectsToCopy.Add Sheet2

    ' Get filename of new file from user.
    Do
        newFilename = InputBox("Please Specify the name of your new workbook." & vbCr & vbCr & "Either enter a full path or just a filename, in which case the file will be saved in the same location (" & sourceWorkbook.Path & "). Don't use the name of a workbook that is already open, otherwise this script will break.", "New Copy")
        If newFilename = "" Then MsgBox "You must enter something.", vbExclamation, "Filename needed"
    Loop Until newFilename > ""

    ' If they didn't supply a path, assume same location as the source workbook.
    ' Not perfect - simply assumes a path has been supplied if a path separator
    ' exists somewhere. Could still be a badly-formed path. And, no check is done
    ' to see if the path actually exists.
    If InStr(1, newFilename, Application.PathSeparator, vbTextCompare) = 0 Then
        newFilename = sourceWorkbook.Path & Application.PathSeparator & newFilename
    End If

    ' Create a new workbook and save as the user requested.
    ' NB This fails if the filename is the same as a workbook that's
    ' already open - it should check for this.
    Set newWorkbook = Application.Workbooks.Add(xlWBATWorksheet)
    newWorkbook.SaveAs Filename:=newFilename, _
        FileFormat:=xlWorkbookDefault

    ' Theme fonts and colours don't get copied over with most paste-special operations.
    ' This saves the theme of the source workbook and then loads it into the new workbook.
    ' BUG: Doesn't work!
    'themeTempFilePath = Environ("temp") & Application.PathSeparator & sourceWorkbook.Name & " - Theme.xml"
    'sourceWorkbook.Theme.ThemeFontScheme.Save themeTempFilePath
    'sourceWorkbook.Theme.ThemeColorScheme.Save themeTempFilePath
    'newWorkbook.Theme.ThemeFontScheme.Load themeTempFilePath
    'newWorkbook.Theme.ThemeColorScheme.Load themeTempFilePath
    'On Error Resume Next
    'Kill themeTempFilePath  ' kill = delete in VBA-speak
    'On Error GoTo 0


    ' getWorksheetNameFromObject returns null if the worksheet object doens't
    ' exist
    For Each sht In colSheetObjectsToCopy
        sheetFriendlyName = getWorksheetNameFromObject(sourceWorkbook, sht)
        Application.StatusBar = "VBL Copying " & sheetFriendlyName
        If Not IsNull(sheetFriendlyName) Then
            Select Case copyMethod
                Case "sheet"
                    sourceWorkbook.Sheets(sheetFriendlyName).Copy _
                        After:=newWorkbook.Sheets(newWorkbook.Sheets.count)
                Case "valuesWithFormatting"
                    newWorkbook.Sheets.Add After:=newWorkbook.Sheets(newWorkbook.Sheets.count), _
                        Type:=sourceWorkbook.Sheets(sheetFriendlyName).Type
                    sheetCount = newWorkbook.Sheets.count
                    newWorkbook.Sheets(sheetCount).Name = sheetFriendlyName
                    ' Copy all cells in current source sheet to the clipboard. Could copy straight
                    ' to the new workbook by specifying the Destination parameter but in this case
                    ' we want to do a paste special as values only and the Copy method doens't allow that.
                    sourceWorkbook.Sheets(sheetFriendlyName).Cells.Copy ' Destination:=newWorkbook.Sheets(newWorkbook.Sheets.Count).[A1]
                    newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlValues
                    newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlFormats
                    newWorkbook.Sheets(sheetCount).Tab.Color = sourceWorkbook.Sheets(sheetFriendlyName).Tab.Color
                    Application.CutCopyMode = False
            End Select
        End If
    Next sht

    Application.StatusBar = False
    Application.ScreenUpdating = True
    ActiveWorkbook.Save

Remove category & tag base from WordPress url - without a plugin

Select Custom Structure in permalinks and add /%category%/%postname%/ after your domain. Adding "/" to the category base doesn't work, you have to add a period/dot. I wrote a tutorial for this here: remove category from URL tutorial

How to change the color of text in javafx TextField?

Setting the -fx-text-fill works for me.

See below:

if (passed) {
    resultInfo.setText("Passed!");
    resultInfo.setStyle("-fx-text-fill: green; -fx-font-size: 16px;");
} else {
    resultInfo.setText("Failed!");
    resultInfo.setStyle("-fx-text-fill: red; -fx-font-size: 16px;");
}

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare();

You can simply use BeginInvokeOnMainThread(). It invokes an Action on the device main (UI) thread.

Device.BeginInvokeOnMainThread(() => { displayToast("text to display"); });

It is simple and works perfectly for me!

EDIT : Works if you're using C# Xamarin

How to display list items on console window in C#

Actually you can do it pretty simple, since the list have a ForEach method and since you can pass in Console.WriteLine as a method group. The compiler will then use an implicit conversion to convert the method group to, in this case, an Action<int> and pick the most specific method from the group, in this case Console.WriteLine(int):

  var list = new List<int>(Enumerable.Range(0, 50));

  list.ForEach(Console.WriteLine);

Works with strings too =)

To be utterly pedantic (and I'm not suggesting a change to your answer - just commenting for the sake of interest) Console.WriteLine is a method group. The compiler then uses an implicit conversion from the method group to Action<int>, picking the most specific method (Console.WriteLine(int) in this case).

'python3' is not recognized as an internal or external command, operable program or batch file

Yes, I think for Windows users you need to change all the python3 calls to python to solve your original error. This change will run the Python version set in your current environment. If you need to keep this call as it is (aka python3) because you are working in cross-platform or for any other reason, then a work around is to create a soft link. To create it, go to the folder that contains the Python executable and create the link. For example, this worked in my case in Windows 10 using mklink:

cd C:\Python3
mklink python3.exe python.exe

Use a (soft) symbolic link in Linux:

cd /usr/bin/python3
ln -s python.exe python3.exe

What are the main differences between JWT and OAuth authentication?

find the main differences between JWT & OAuth

  1. OAuth 2.0 defines a protocol & JWT defines a token format.

  2. OAuth can use either JWT as a token format or access token which is a bearer token.

  3. OpenID connect mostly use JWT as a token format.

Refer to a cell in another worksheet by referencing the current worksheet's name?

Still using indirect. Say your A1 cell is your variable that will contain the name of the referenced sheet (Jan). If you go by:

=INDIRECT(CONCATENATE("'",A1," Item'", "!J3"))

Then you will have the 'Jan Item'!J3 value.

How to parse/read a YAML file into a Python object?

Here is one way to test which YAML implementation the user has selected on the virtualenv (or the system) and then define load_yaml_file appropriately:

load_yaml_file = None

if not load_yaml_file:
    try:
        import yaml
        load_yaml_file = lambda fn: yaml.load(open(fn))
    except:
        pass

if not load_yaml_file:
    import commands, json
    if commands.getstatusoutput('ruby --version')[0] == 0:
        def load_yaml_file(fn):
            ruby = "puts YAML.load_file('%s').to_json" % fn
            j = commands.getstatusoutput('ruby -ryaml -rjson -e "%s"' % ruby)
            return json.loads(j[1])

if not load_yaml_file:
    import os, sys
    print """
ERROR: %s requires ruby or python-yaml  to be installed.

apt-get install ruby

  OR

apt-get install python-yaml

  OR

Demonstrate your mastery of Python by using pip.
Please research the latest pip-based install steps for python-yaml.
Usually something like this works:
   apt-get install epel-release
   apt-get install python-pip
   apt-get install libyaml-cpp-dev
   python2.7 /usr/bin/pip install pyyaml
Notes:
Non-base library (yaml) should never be installed outside a virtualenv.
"pip install" is permanent:
  https://stackoverflow.com/questions/1550226/python-setup-py-uninstall
Beware when using pip within an aptitude or RPM script.
  Pip might not play by all the rules.
  Your installation may be permanent.
Ruby is 7X faster at loading large YAML files.
pip could ruin your life.
  https://stackoverflow.com/questions/46326059/
  https://stackoverflow.com/questions/36410756/
  https://stackoverflow.com/questions/8022240/
Never use PyYaml in numerical applications.
  https://stackoverflow.com/questions/30458977/
If you are working for a Fortune 500 company, your choices are
1. Ask for either the "ruby" package or the "python-yaml"
package. Asking for Ruby is more likely to get a fast answer.
2. Work in a VM. I highly recommend Vagrant for setting it up.

""" % sys.argv[0]
    os._exit(4)


# test
import sys
print load_yaml_file(sys.argv[1])

How to set the default value of an attribute on a Laravel model

The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:

/**
 * The "booting" method of the model.
 *
 * @return void
 */
protected static function boot()
{
    parent::boot();

    // auto-sets values on creation
    static::creating(function ($query) {
        $query->is_voicemail = $query->is_voicemail ?? true;
    });
}

Why is 2 * (i * i) faster than 2 * i * i in Java?

(Editor's note: this answer is contradicted by evidence from looking at the asm, as shown by another answer. This was a guess backed up by some experiments, but it turned out not to be correct.)


When the multiplication is 2 * (i * i), the JVM is able to factor out the multiplication by 2 from the loop, resulting in this equivalent but more efficient code:

int n = 0;
for (int i = 0; i < 1000000000; i++) {
    n += i * i;
}
n *= 2;

but when the multiplication is (2 * i) * i, the JVM doesn't optimize it since the multiplication by a constant is no longer right before the n += addition.

Here are a few reasons why I think this is the case:

  • Adding an if (n == 0) n = 1 statement at the start of the loop results in both versions being as efficient, since factoring out the multiplication no longer guarantees that the result will be the same
  • The optimized version (by factoring out the multiplication by 2) is exactly as fast as the 2 * (i * i) version

Here is the test code that I used to draw these conclusions:

public static void main(String[] args) {
    long fastVersion = 0;
    long slowVersion = 0;
    long optimizedVersion = 0;
    long modifiedFastVersion = 0;
    long modifiedSlowVersion = 0;

    for (int i = 0; i < 10; i++) {
        fastVersion += fastVersion();
        slowVersion += slowVersion();
        optimizedVersion += optimizedVersion();
        modifiedFastVersion += modifiedFastVersion();
        modifiedSlowVersion += modifiedSlowVersion();
    }

    System.out.println("Fast version: " + (double) fastVersion / 1000000000 + " s");
    System.out.println("Slow version: " + (double) slowVersion / 1000000000 + " s");
    System.out.println("Optimized version: " + (double) optimizedVersion / 1000000000 + " s");
    System.out.println("Modified fast version: " + (double) modifiedFastVersion / 1000000000 + " s");
    System.out.println("Modified slow version: " + (double) modifiedSlowVersion / 1000000000 + " s");
}

private static long fastVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        n += 2 * (i * i);
    }
    return System.nanoTime() - startTime;
}

private static long slowVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        n += 2 * i * i;
    }
    return System.nanoTime() - startTime;
}

private static long optimizedVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        n += i * i;
    }
    n *= 2;
    return System.nanoTime() - startTime;
}

private static long modifiedFastVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        if (n == 0) n = 1;
        n += 2 * (i * i);
    }
    return System.nanoTime() - startTime;
}

private static long modifiedSlowVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        if (n == 0) n = 1;
        n += 2 * i * i;
    }
    return System.nanoTime() - startTime;
}

And here are the results:

Fast version: 5.7274411 s
Slow version: 7.6190804 s
Optimized version: 5.1348007 s
Modified fast version: 7.1492705 s
Modified slow version: 7.2952668 s

How do I enable index downloads in Eclipse for Maven dependency search?

  1. In Eclipse, click on Windows > Preferences, and then choose Maven in the left side.
  2. Check the box "Download repository index updates on startup".
    • Optionally, check the boxes Download Artifact Sources and Download Artifact JavaDoc.
  3. Click OK. The warning won't appear anymore.
  4. Restart Eclipse.

http://i.imgur.com/IJ2T3vc.png

Max size of URL parameters in _GET

Ok, it seems that some versions of PHP have a limitation of length of GET params:

Please note that PHP setups with the suhosin patch installed will have a default limit of 512 characters for get parameters. Although bad practice, most browsers (including IE) supports URLs up to around 2000 characters, while Apache has a default of 8000.

To add support for long parameters with suhosin, add suhosin.get.max_value_length = <limit> in php.ini

Source: http://www.php.net/manual/en/reserved.variables.get.php#101469

How to part DATE and TIME from DATETIME in MySQL

Simply,
SELECT TIME(column_name), DATE(column_name)

How to add element in Python to the end of list using list.insert?

list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append

Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]

Time complexity, append O(1), insert O(n)

getElementById returns null?

It can be caused by:

  1. Invalid HTML syntax (some tag is not closed or similar error)
  2. Duplicate IDs - there are two HTML DOM elements with the same ID
  3. Maybe element you are trying to get by ID is created dynamically (loaded by ajax or created by script)?

Please, post your code.

Position absolute but relative to parent

If you don't give any position to parent then by default it takes static. If you want to understand that difference refer to this example

Example 1::

http://jsfiddle.net/Cr9KB/1/

   #mainall
{

    background-color:red;
    height:150px;
    overflow:scroll
}

Here parent class has no position so element is placed according to body.

Example 2::

http://jsfiddle.net/Cr9KB/2/

#mainall
{
    position:relative;
    background-color:red;
    height:150px;
    overflow:scroll
}

In this example parent has relative position hence element are positioned absolute inside relative parent.

Why does a base64 encoded string have an = sign at the end

http://www.hcidata.info/base64.htm

Encoding "Mary had" to Base 64

In this example we are using a simple text string ("Mary had") but the principle holds no matter what the data is (e.g. graphics file). To convert each 24 bits of input data to 32 bits of output, Base 64 encoding splits the 24 bits into 4 chunks of 6 bits. The first problem we notice is that "Mary had" is not a multiple of 3 bytes - it is 8 bytes long. Because of this, the last group of bits is only 4 bits long. To remedy this we add two extra bits of '0' and remember this fact by putting a '=' at the end. If the text string to be converted to Base 64 was 7 bytes long, the last group would have had 2 bits. In this case we would have added four extra bits of '0' and remember this fact by putting '==' at the end.

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

It is possible to set environment variables on Mac OS X 10.10 Yosemite with 3 files + 2 commands.

Main file with environment variables definition:

$ ls -la /etc/environment 
-r-xr-xr-x  1 root  wheel  369 Oct 21 04:42 /etc/environment
$ cat /etc/environment
#!/bin/sh

set -e

syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - start"

launchctl setenv JAVA_HOME      /usr/local/jdk1.7
launchctl setenv MAVEN_HOME     /opt/local/share/java/maven3

if [ -x /usr/libexec/path_helper ]; then
    export PATH=""
    eval `/usr/libexec/path_helper -s`
    launchctl setenv PATH $PATH
fi

osascript -e 'tell app "Dock" to quit'

syslog -s -l warn "Set environment variables with /etc/environment $(whoami) - complete"

Service definition to load environment variables for user applications (terminal, IDE, ...):

$ ls -la /Library/LaunchAgents/environment.user.plist
-rw-------  1 root  wheel  504 Oct 21 04:37 /Library/LaunchAgents/environment.user.plist
$ sudo cat /Library/LaunchAgents/environment.user.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>environment.user</string>
    <key>ProgramArguments</key>
    <array>
            <string>/etc/environment</string>
    </array>
    <key>KeepAlive</key>
    <false/>
    <key>RunAtLoad</key>
    <true/>
    <key>WatchPaths</key>
    <array>
        <string>/etc/environment</string>
    </array>
</dict>
</plist>

The same service definition for root user applications:

$ ls -la /Library/LaunchDaemons/environment.plist
-rw-------  1 root  wheel  499 Oct 21 04:38 /Library/LaunchDaemons/environment.plist
$ sudo cat /Library/LaunchDaemons/environment.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>environment</string>
    <key>ProgramArguments</key>
    <array>
            <string>/etc/environment</string>
    </array>
    <key>KeepAlive</key>
    <false/>
    <key>RunAtLoad</key>
    <true/>
    <key>WatchPaths</key>
    <array>
        <string>/etc/environment</string>
    </array>
</dict>
</plist>

And finally we should register these services:

$ launchctl load -w /Library/LaunchAgents/environment.user.plist
$ sudo launchctl load -w /Library/LaunchDaemons/environment.plist

What we get:

  1. The only place to declare system environment variables: /etc/environment
  2. Instant auto-update of environment variables after modification of /etc/environment file - just relaunch your application

Issues / problems:

In order your env variables were correctly taken by applications after system reboot you will need:

  • either login twice: login => logout => login
  • or close & re-open applications manually, where env variables should be taken
  • or do NOT use feature "Reopen windows when logging back".

This happens due to Apple denies explicit ordering of loaded services, so env variables are registered in parallel with processing of the "reopen queue".

But actually, I reboot my system only several times per year (on big updates), so it is not a big deal.

Maven Out of Memory Build Failure

_JAVA_OPTIONS="-Xmx3G" mvn clean install

What do the crossed style properties in Google Chrome devtools mean?

In addition to the above answer I also want to highlight a case of striked out property which really surprised me.

If you are adding a background image to a div :

<div class = "myBackground">

</div>

You want to scale the image to fit in the dimensions of the div so this would be your normal class definition.

.myBackground {

 height:100px;
 width:100px;
 background: url("/img/bck/myImage.jpg") no-repeat; 
 background-size: contain;

}

but if you interchange the order as :-

.myBackground {
 height:100px;
 width:100px;
 background-size: contain;  //before the background
 background: url("/img/bck/myImage.jpg") no-repeat; 
}

then in chrome you ll see background-size as striked out. I am not sure why this is , but yeah you dont want to mess with it.

jQuery UI Dialog with ASP.NET button postback

$('#divname').parent().appendTo($("form:first"));

Using this code solved my problem and it worked in every browser, Internet Explorer 7, Firefox 3, and Google Chrome. I start to love jQuery... It's a cool framework.

I have tested with partial render too, exactly what I was looking for. Great!

<script type="text/javascript">
    function openModalDiv(divname) {
        $('#' + divname).dialog({ autoOpen: false, bgiframe: true, modal: true });
        $('#' + divname).dialog('open');
        $('#' + divname).parent().appendTo($("form:first"));
    }

    function closeModalDiv(divname) {
        $('#' + divname).dialog('close');
    }
</script>
...
...
<input id="Button1" type="button" value="Open 1" onclick="javascript:openModalDiv('Div1');" />
...
...
<div id="Div1" title="Basic dialog" >
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
       <ContentTemplate>
          postback test<br />
          <asp:Button ID="but_OK" runat="server" Text="Send request" /><br />
          <asp:TextBox ID="tb_send" runat="server"></asp:TextBox><br />
          <asp:Label ID="lbl_result" runat="server" Text="prova" BackColor="#ff0000></asp:Label>
        </ContentTemplate>
    <asp:UpdatePanel>
    <input id="Button2" type="button" value="cancel" onclick="javascript:closeModalDiv('Div1');" />
</div>

How to use Utilities.sleep() function

Some Google services do not like to be used to much. Quite recently my account was locked because of script, which was sending two e-mails per second to the same user. Google considered it as a spam. So using sleep here is also justified to prevent such situations.

How to dismiss the dialog with click on outside of the dialog?

This method should completely avoid activities below the grey area retrieving click events.

Remove this line if you have it:

window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);

Put this on your activity created

getWindow().setFlags(LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);

then override the touch event with this

@Override
public boolean onTouchEvent(MotionEvent ev)
{
    if(MotionEvent.ACTION_DOWN == ev.getAction())
    {
        Rect dialogBounds = new Rect();
        getWindow().getDecorView().getHitRect(dialogBounds);
        if (!dialogBounds.contains((int) ev.getX(), (int) ev.getY())) {
            // You have clicked the grey area
            displayYourDialog();
            return false; // stop activity closing
        }
    }

    // Touch events inside are fine.
    return super.onTouchEvent(ev);
}

Vertically centering Bootstrap modal window

you can use:

.modal {
    position: fixed;
    top: 50% !important;
    left: 50%;
    transform: translate(-50%, -50%);
}

to center it both vertically and horizontally.

Multiple radio button groups in MVC 4 Razor

I fixed a similar issue building a RadioButtonFor with pairs of text/value from a SelectList. I used a ViewBag to send the SelectList to the View, but you can use data from model too. My web application is a Blog and I have to build a RadioButton with some types of articles when he is writing a new post.

The code below was simplyfied.

List<SelectListItem> items = new List<SelectListItem>();

Dictionary<string, string> dictionary = new Dictionary<string, string>();

dictionary.Add("Texto", "1");
dictionary.Add("Foto", "2");
dictionary.Add("Vídeo", "3");

foreach (KeyValuePair<string, string> pair in objBLL.GetTiposPost())
{
    items.Add(new SelectListItem() { Text = pair.Key, Value = pair.Value, Selected = false });
}

ViewBag.TiposPost = new SelectList(items, "Value", "Text");

In the View, I used a foreach to build a radiobutton.

<div class="form-group">
    <div class="col-sm-10">
        @foreach (var item in (SelectList)ViewBag.TiposPost)
        {
            @Html.RadioButtonFor(model => model.IDTipoPost, item.Value, false)
            <label class="control-label">@item.Text</label>
        }

    </div>
</div>

Notice that I used RadioButtonFor in order to catch the option value selected by user, in the Controler, after submit the form. I also had to put the item.Text outside the RadioButtonFor in order to show the text options.

Hope it's useful!

Android studio- "SDK tools directory is missing"

This is INTERNET error So, Create a SQUID Proxy Server
1. install android studio
2. setup proxy settings in android studio

proxy setting in android studio

3. uninstall android studio and keep user settings

enter image description here

4. install android studio again
5. after finish first setup, then android must detect proxy settings automatically and setup SDK

enter image description here

6. after finish sdk configs, then create your first project
7. confirm proxy settings dialog for first time

enter image description here

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

7-Zip command to create and extract a password-protected ZIP file on Windows?

From http://www.dotnetperls.com:

7z a secure.7z * -pSECRET

Where:

7z        : name and path of 7-Zip executable
a         : add to archive
secure.7z : name of destination archive
*         : add all files from current directory to destination archive
-pSECRET  : specify the password "SECRET"

To open :

7z x secure.7z

Then provide the SECRET password

Note: If the password contains spaces or special characters, then enclose it with single quotes

7z a secure.7z * -p"pa$$word @|"

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

Delete package.json and package-lock.json file

Then type npm init

after that type npm install socket.io --save

finally type npm install

It works for me

SQL left join vs multiple tables on FROM line?

When you need an outer join the second syntax is not always required:

Oracle:

SELECT a.foo, b.foo
  FROM a, b
 WHERE a.x = b.x(+)

MSSQLServer (although it's been deprecated in 2000 version)/Sybase:

SELECT a.foo, b.foo
  FROM a, b
 WHERE a.x *= b.x

But returning to your question. I don't know the answer, but it is probably related to the fact that a join is more natural (syntactically, at least) than adding an expression to a where clause when you are doing exactly that: joining.

What is the difference between <p> and <div>?

They have semantic difference - a <div> element is designed to describe a container of data whereas a <p> element is designed to describe a paragraph of content.

The semantics make all the difference. HTML is a markup language which means that it is designed to "mark up" content in a way that is meaningful to the consumer of the markup. Most developers believe that the semantics of the document are the default styles and rendering that browsers apply to these elements but that is not the case.

The elements that you choose to mark up your content should describe the content. Don't mark up your document based on how it should look - mark it up based on what it is.

If you need a generic container purely for layout purposes then use a <div>. If you need an element to describe a paragraph of content then use a <p>.

Note: It is important to understand that both <div> and <p> are block-level elements which means that most browsers will treat them in a similar fashion.

Lombok is not generating getter and setter

If you are using maven and Eclipse, must be installed manually.

  1. Verify pom

_x000D_
_x000D_
 <dependency>_x000D_
            <groupId>org.projectlombok</groupId>_x000D_
            <artifactId>lombok</artifactId>_x000D_
            <version>1.18.10</version>_x000D_
            <type>jar</type>_x000D_
        </dependency>
_x000D_
_x000D_
_x000D_

  1. go to Maven Dependencies

enter image description here

  1. Right click in the library and Run as Java aplication

enter image description here

  1. Especify location IDE, install and close IDE (Eclipse). enter image description here

How to extract HTTP response body from a Python requests call?


import requests

site_request = requests.get("https://abhiunix.in")

site_response = str(site_request.content)

print(site_response)

You can do it either way.

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

My issue was due to what physical USB female port I plugged the Arduino cable into on my D-Link DUB-H7 (USB hub) on Windows 10. I had my Arduino plugged into one of the two ports way on the right (in the image below). The USB cable fit, and it powers the Arduino fine, but the Arduino wasn't seeing the port for some reason.

enter image description here

Windows does not recognize these two ports. Any of the other ports are fair game. In my case, the Tools > Port menu was grayed out. In this scenario, the "Ports" section in the object explorer was hidden. So to show the hidden devices, I chose View > show hidden. COM1 was what showed up originally. When I changed it to COM3, it didn't work.

There are many places where the COM port can be configured.

Windows > Control Panel > Device Manager > Ports > right click Arduino > Properties > Port Settings > Advanced > COM Port Number: [choose port]

Windows > Start Menu > Arduino > Tools > Ports > [choose port]

Windows > Start Menu > Arduino > File > Preferences > @ very bottom, there is a label named "More preferences can be edited directly in the file".

C:\Users{user name}\AppData\Local\Arduino15\preferences.txt

target_package = arduino
target_platform = avr
board = uno
software=ARDUINO
# Warn when data segment uses greater than this percentage
build.warn_data_percentage = 75

programmer = arduino:avrispmkii

upload.using = bootloader
upload.verify = true

serial.port=COM3
serial.databits=8
serial.stopbits=1
serial.parity=N
serial.debug_rate=9600

# I18 Preferences

# default chosen language (none for none)
editor.languages.current = 

The user preferences.txt overrides this one:

C:\Users{user name}\Desktop\avrdude.conf

... search for "com" ... "com1" is the default

Convert String to Calendar Object in Java

SimpleDateFormat is great, just note that HH is different from hh when working with hours. HH will return 24 hour based hours and hh will return 12 hour based hours.

For example, the following will return 12 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

While this will return 24 hour time:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

Eclipse hangs on loading workbench

I didn't try all these. I restarted by laptop/machine . And everything was back to normal after that.

Merge unequal dataframes and replace missing rows with 0

Or, as an alternative to @Chase's code, being a recent plyr fan with a background in databases:

require(plyr)
zz<-join(df1, df2, type="left")
zz[is.na(zz)] <- 0

Access Enum value using EL with JSTL

In Java Class:

    public class EnumTest{
    //Other property link
    private String name;
    ....

        public enum Status {
                ACTIVE,NEWLINK, BROADCASTED, PENDING, CLICKED, VERIFIED, AWARDED, INACTIVE, EXPIRED, DELETED_BY_ADMIN;
            }

        private Status statusobj ;

    //Getter and Setters
}

So now POJO and enum obj is created. Now EnumTest you will set in session object using in the servlet or controller class session.setAttribute("enumTest", EnumTest );

In JSP Page

<c:if test="${enumTest.statusobj == 'ACTIVE'}">

//TRUE??? THEN PROCESS SOME LOGIC

C non-blocking keyboard input

The curses library can be used for this purpose. Of course, select() and signal handlers can be used too to a certain extent.

Undefined function mysql_connect()

My guess is your PHP installation wasn't compiled with MySQL support.

Check your configure command (php -i | grep mysql). You should see something like '--with-mysql=shared,/usr'.

You can check for complete instructions at http://php.net/manual/en/mysql.installation.php. Although, I would rather go with the solution proposed by @wanovak.

Still, I think you need MySQL support in order to use PDO.

What is the meaning of "this" in Java?

To be complete, this can also be used to refer to the outer object

class Outer {
    class Inner {
        void foo() {
            Outer o = Outer.this;
    }
  }
}

How to select between brackets (or quotes or ...) in Vim?

I would add a detail to the most voted answer:

If you're using gvim and want to copy to the clipboard, use

"+<command>

To copy all the content between brackets (or parens or curly brackets)

For example: "+yi} will copy to the clipboard all the content between the curly brackets your cursor is.

Display the current time and date in an Android application

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
Date date = Calendar.getInstance().getTime();
String sDate = format.format(date);//31-12-9999
int mYear = c.get(Calendar.YEAR);//9999
int mMonth = c.get(Calendar.MONTH);
mMonth = mMonth + 1;//12
int hrs = c.get(Calendar.HOUR_OF_DAY);//24
int min = c.get(Calendar.MINUTE);//59
String AMPM;
if (c.get(Calendar.AM_PM) == 0) {
    AMPM = "AM";
} else {
    AMPM = "PM";
}

Failed to connect to camera service

when you use camera.open; and you finish using the camera write this commend camera.release(); this will stop the camera so you can use it again

Calculate relative time in C#

Here's the algorithm stackoverflow uses but rewritten more concisely in perlish pseudocode with a bug fix (no "one hours ago"). The function takes a (positive) number of seconds ago and returns a human-friendly string like "3 hours ago" or "yesterday".

agoify($delta)
  local($y, $mo, $d, $h, $m, $s);
  $s = floor($delta);
  if($s<=1)            return "a second ago";
  if($s<60)            return "$s seconds ago";
  $m = floor($s/60);
  if($m==1)            return "a minute ago";
  if($m<45)            return "$m minutes ago";
  $h = floor($m/60);
  if($h==1)            return "an hour ago";
  if($h<24)            return "$h hours ago";
  $d = floor($h/24);
  if($d<2)             return "yesterday";
  if($d<30)            return "$d days ago";
  $mo = floor($d/30);
  if($mo<=1)           return "a month ago";
  $y = floor($mo/12);
  if($y<1)             return "$mo months ago";
  if($y==1)            return "a year ago";
  return "$y years ago";

Can you have multiple $(document).ready(function(){ ... }); sections?

You can even nest document ready functions inside included html files. Here's an example using jquery:

File: test_main.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="jquery-1.10.2.min.js"></script>
</head>

<body>
    <div id="main-container">
        <h1>test_main.html</h1>
    </div>

<script>
    $(document).ready( function()
    {
        console.log( 'test_main.html READY' );
        $("#main-container").load("test_embed.html");
    } );
</script>

</body>
</html>

File: test_embed.html

<h1>test_embed.html</h1>
<script>
    $(document).ready( function()
    {
        console.log( 'test_embed.html READY' );
    } );
</script>

Console output:

test_main.html READY                       test_main.html:15
test_embed.html READY                      (program):4

Browser shows:

test_embed.html

how to specify local modules as npm package dependencies

After struggling much with the npm link command (suggested solution for developing local modules without publishing them to a registry or maintaining a separate copy in the node_modules folder), I built a small npm module to help with this issue.

The fix requires two easy steps.

First:

npm install lib-manager --save-dev

Second, add this to your package.json:

{  
  "name": "yourModuleName",  
  // ...
  "scripts": {
    "postinstall": "./node_modules/.bin/local-link"
  }
}

More details at https://www.npmjs.com/package/lib-manager. Hope it helps someone.

Changing Placeholder Text Color with Swift

It is more about personalize your textField but anyways I'll share this code got from another page and made it a little better:

import UIKit
extension UITextField {
func setBottomLine(borderColor: UIColor, fontColor: UIColor, placeHolderColor:UIColor, placeHolder: String) {
    self.borderStyle = UITextBorderStyle.none
    self.backgroundColor = UIColor.clear
    let borderLine = UIView()
    let height = 1.0
    borderLine.frame = CGRect(x: 0, y: Double(self.frame.height) - height, width: Double(self.frame.width), height: height)
    self.textColor = fontColor
    borderLine.backgroundColor = borderColor
    self.addSubview(borderLine)
    self.attributedPlaceholder = NSAttributedString(
        string: placeHolder,
        attributes: [NSAttributedStringKey.foregroundColor: placeHolderColor]
    )
  }
}

And you can use it like this:

self.textField.setBottomLine(borderColor: lineColor, fontColor: fontColor, placeHolderColor: placeHolderColor, placeHolder: placeHolder)

Knowing that you have an UITextField connected to a ViewController.

Source: http://codepany.com/blog/swift-3-custom-uitextfield-with-single-line-input/

How to print time in format: 2009-08-10 18:17:54.811

You could use strftime, but struct tm doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.

struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%S", &tm);

How to enable production mode?

You don't need any environment.ts or such file to be provided by your seed project. Just have a configuration.ts and add all such entries which require runtime decision (example:- logging configuration and urls). This will fit in any design structure and also help in future

configuration.ts

export class Configuration {

   isInProductionMode : bool = true;

   // other configuration
   serviceUrl : string = "http://myserver/myservice.svc";
   logFileName : string = "...";
}

// Now use in your startup code (main.ts or equivalent as per the seed project design

import { Configuration } from './configuration';
import { enableProdMode } from '@angular/core';
....
if (Configuration.isInProductionMode)
    enableProdMode();

Remove specific characters from a string in Python

>>> s = 'a1b2c3'
>>> ''.join(c for c in s if c not in '123')
'abc'

Get all validation errors from Angular 2 FormGroup

// IF not populated correctly - you could get aggregated FormGroup errors object
let getErrors = (formGroup: FormGroup, errors: any = {}) {
  Object.keys(formGroup.controls).forEach(field => {
    const control = formGroup.get(field);
    if (control instanceof FormControl) {
      errors[field] = control.errors;
    } else if (control instanceof FormGroup) {
      errors[field] = this.getErrors(control);
    }
  });
  return errors;
}

// Calling it:
let formErrors = getErrors(this.form);

Cannot uninstall angular-cli

I have also faced the same issue in recent past for me I have do the following commands one by one in terminal.

sudo npm uninstall -g angular-cli
sudo npm cache clean

After this run

ng -v

If still get angular-cli version 1.0.0-beta.2x.x then run the following command

which ng

It will show the ng path. Go to the path and if it is linked with any file remove the same the link and actual ng file. In my case the link is in /usr/bin/ng and actual path of ng file is /lib/node_modules/@angular/cli/bin/ng.

sudo rm -rf /lib/node_modules/@angular/cli/bin/ng
sudo rm -rf /usr/bin/ng

Next you need to install @angular/cli using

sudo npm install -g @angular/cli

Close all the terminal and run ng -v and you are on. May be it will help someone. Thanks :)

Resizable table columns with jQuery

Here's a short complete html example. See demo http://jsfiddle.net/CU585/

<!DOCTYPE html><html><head><title>resizable columns</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
<style>
th {border: 1px solid black;}
table{border-collapse: collapse;}
.ui-icon, .ui-widget-content .ui-icon {background-image: none;}
</style>
<body>
<table>
<tr><th>head 1</th><th>head 2</th></tr><tr><td>a1</td><td>b1</td></tr></table><script>
$( "th" ).resizable();
</script></body></html>

Hide axis and gridlines Highcharts

For the yAxis you'll also need:

gridLineColor: 'transparent',

Python regex for integer?

You need to anchor the regex at the start and end of the string:

^[0-9]+$

Explanation:

^      # Start of string
[0-9]+ # one or more digits 0-9
$      # End of string

What is the difference between Html.Hidden and Html.HiddenFor

Every method in HtmlHelper class has a twin with For suffix. Html.Hidden takes a string as an argument that you must provide but Html.HiddenFor takes an Expression that if you view is a strongly typed view you can benefit from this and feed that method a lambda expression like this

o=>o.SomeProperty 

instead of "SomeProperty" in the case of using Html.Hidden method.

Docker - Ubuntu - bash: ping: command not found

Alternatively you can use a Docker image which already has ping installed, e.g. busybox:

docker run --rm busybox ping SERVER_NAME -c 2

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

accepting HTTPS connections with self-signed certificates

This is problem resulting from lack of SNI(Server Name Identification) support inA,ndroid 2.x. I was struggling with this problem for a week until I came across the following question, which not only gives a good background of the problem but also provides a working and effective solution devoid of any security holes.

'No peer certificate' error in Android 2.3 but NOT in 4

How to add 10 minutes to my (String) time?

You have a plenty of easy approaches within above answers. This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.

String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());

Output :

14:10
14:20

How can I change the width and height of slides on Slick Carousel?

Basically you need to edit the JS and add (in this case, inside $('#featured-articles').slick({ ), this:

variableWidth: true,

This will allow you to edit the width in your CSS where you can, generically use:

.slick-slide {
    width: 100%;
}

or in this case:

.featured {
    width: 100%;
}

Searching for UUIDs in text with regex

$UUID_RE = join '-', map { "[0-9a-f]{$_}" } 8, 4, 4, 4, 12;

BTW, allowing only 4 on one of the positions is only valid for UUIDv4. But v4 is not the only UUID version that exists. I have met v1 in my practice as well.

SQL grammar for SELECT MIN(DATE)

You need to use GROUP BY instead of DISTINCT if you want to use aggregation functions.

SELECT title, MIN(date)
FROM table
GROUP BY title

Passing in class names to react components

You can achieve this by "interpolating" the className passed from the parent component to the child component using this.props.className. Example below:

export default class ParentComponent extends React.Component {
  render(){
    return <ChildComponent className="your-modifier-class" />
  }
}

export default class ChildComponent extends React.Component {
  render(){
    return <div className={"original-class " + this.props.className}></div>
  }
}

Use virtualenv with Python with Visual Studio Code in Ubuntu

Another way is to open Visual Studio Code from a terminal with the virtualenv set and need to perform F1 Python: Select Interpreter and select the required virtualenv.

virtualenv

UIImage resize (Scale proportion)

Try to make the bounds's size integer.

#include <math.h>
....

    if (ratio > 1) {
        bounds.size.width = resolution;
        bounds.size.height = round(bounds.size.width / ratio);
    } else {
        bounds.size.height = resolution;
        bounds.size.width = round(bounds.size.height * ratio);
    }

Using import fs from 'fs'

It's not supported just yet... If you want to use it you will have to install Babel.

How can I get the domain name of my site within a Django template?

Similar to user panchicore's reply, this is what I did on a very simple website. It provides a few variables and makes them available on the template.

SITE_URL would hold a value like example.com
SITE_PROTOCOL would hold a value like http or https
SITE_PROTOCOL_URL would hold a value like http://example.com or https://example.com
SITE_PROTOCOL_RELATIVE_URL would hold a value like //example.com.

module/context_processors.py

from django.conf import settings

def site(request):

    SITE_PROTOCOL_RELATIVE_URL = '//' + settings.SITE_URL

    SITE_PROTOCOL = 'http'
    if request.is_secure():
        SITE_PROTOCOL = 'https'

    SITE_PROTOCOL_URL = SITE_PROTOCOL + '://' + settings.SITE_URL

    return {
        'SITE_URL': settings.SITE_URL,
        'SITE_PROTOCOL': SITE_PROTOCOL,
        'SITE_PROTOCOL_URL': SITE_PROTOCOL_URL,
        'SITE_PROTOCOL_RELATIVE_URL': SITE_PROTOCOL_RELATIVE_URL
    }

settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    "module.context_processors.site",
    ....
 )

SITE_URL = 'example.com'

Then, on your templates, use them as {{ SITE_URL }}, {{ SITE_PROTOCOL }}, {{ SITE_PROTOCOL_URL }} and {{ SITE_PROTOCOL_RELATIVE_URL }}

How to specify the JDK version in android studio?

For new Android Studio versions, go to C:\Program Files\Android\Android Studio\jre\bin(or to location of Android Studio installed files) and open command window at this location and type in following command in command prompt:-

java -version

Styles.Render in MVC4

I did all things necessary to add bundling to an MVC 3 web (I'm new to the existing solution). Styles.Render didn't work for me. I finally discovered I was simply missing a colon. In a master page: <%: Styles.Render("~/Content/Css") %> I'm still confused about why (on the same page) <% Html.RenderPartial("LogOnUserControl"); %> works without the colon.

How to implement common bash idioms in Python?

Your best bet is a tool that is specifically geared towards your problem. If it's processing text files, then Sed, Awk and Perl are the top contenders. Python is a general-purpose dynamic language. As with any general purpose language, there's support for file-manipulation, but that isn't what it's core purpose is. I would consider Python or Ruby if I had a requirement for a dynamic language in particular.

In short, learn Sed and Awk really well, plus all the other goodies that come with your flavour of *nix (All the Bash built-ins, grep, tr and so forth). If it's text file processing you're interested in, you're already using the right stuff.

Using filesystem in node.js with async / await

Node v14.0.0 and above

you can just do:

import { readdir } from "fs/promises";

just like you would import from "fs"

see this PR for more details: https://github.com/nodejs/node/pull/31553

Message 'src refspec master does not match any' when pushing commits in Git

Only commit solved this error:

git commit -m "first commit"

How to pass a single object[] to a params object[]

The params parameter modifier gives callers a shortcut syntax for passing multiple arguments to a method. There are two ways to call a method with a params parameter:

1) Calling with an array of the parameter type, in which case the params keyword has no effect and the array is passed directly to the method:

object[] array = new[] { "1", "2" };

// Foo receives the 'array' argument directly.
Foo( array );

2) Or, calling with an extended list of arguments, in which case the compiler will automatically wrap the list of arguments in a temporary array and pass that to the method:

// Foo receives a temporary array containing the list of arguments.
Foo( "1", "2" );

// This is equivalent to:
object[] temp = new[] { "1", "2" );
Foo( temp );


In order to pass in an object array to a method with a "params object[]" parameter, you can either:

1) Create a wrapper array manually and pass that directly to the method, as mentioned by lassevk:

Foo( new object[] { array } );  // Equivalent to calling convention 1.

2) Or, cast the argument to object, as mentioned by Adam, in which case the compiler will create the wrapper array for you:

Foo( (object)array );  // Equivalent to calling convention 2.


However, if the goal of the method is to process multiple object arrays, it may be easier to declare it with an explicit "params object[][]" parameter. This would allow you to pass multiple arrays as arguments:

void Foo( params object[][] arrays ) {
  foreach( object[] array in arrays ) {
    // process array
  }
}

...
Foo( new[] { "1", "2" }, new[] { "3", "4" } );

// Equivalent to:
object[][] arrays = new[] {
  new[] { "1", "2" },
  new[] { "3", "4" }
};
Foo( arrays );

Edit: Raymond Chen describes this behavior and how it relates to the C# specification in a new post.

Resetting MySQL Root Password with XAMPP on Localhost

You want to edit this file: "\xampp\phpMyAdmin\config.inc.php"

change this line:

$cfg['Servers'][$i]['password'] = 'WhateverPassword';

to whatever your password is. If you don't remember your password, then run this command within the Shell:

mysqladmin.exe -u root password WhateverPassword

where WhateverPassword is your new password.

How to get current time in milliseconds in PHP?

This works even if you are on 32-bit PHP:

list($msec, $sec) = explode(' ', microtime());

$time_milli = $sec.substr($msec, 2, 3); // '1491536422147'
$time_micro = $sec.substr($msec, 2, 6); // '1491536422147300'

Note this doesn't give you integers, but strings. However this works fine in many cases, for example when building URLs for REST requests.


If you need integers, 64-bit PHP is mandatory.

Then you can reuse the above code and cast to (int):

list($msec, $sec) = explode(' ', microtime());

// these parentheses are mandatory otherwise the precedence is wrong!
//                  ?                        ?
$time_milli = (int) ($sec.substr($msec, 2, 3)); // 1491536422147
$time_micro = (int) ($sec.substr($msec, 2, 6)); // 1491536422147300

Or you can use the good ol' one-liners:

$time_milli = (int) round(microtime(true) * 1000);    // 1491536422147
$time_micro = (int) round(microtime(true) * 1000000); // 1491536422147300

Removing elements from array Ruby

Not very simple but:

a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,3].count(k)}.values.flatten
=> [1, 1, 2, 2]

Also handles the case for multiples in the 'subtrahend':

a = [1,1,1,2,2,3]
b = a.group_by {|n| n}.each {|k,v| v.pop [1,1,3].count(k)}.values.flatten
=> [1, 2, 2]

EDIT: this is more an enhancement combining Norm212 and my answer to make a "functional" solution.

b = [1,1,3].each.with_object( a ) { |del| a.delete_at( a.index( del ) ) }

Put it in a lambda if needed:

subtract = lambda do |minuend, subtrahend|
  subtrahend.each.with_object( minuend ) { |del| minuend.delete_at( minuend.index( del ) ) }
end

then:

subtract.call a, [1,1,3]

How do I collapse sections of code in Visual Studio Code for Windows?

Code folding by regions has arrived with v1.17. Folding by regions documentation. And v1.19 and 1.23.

[Generally you can add a space, for example // region and // endregion to //region and //endregion and it will also work.]

TypeScript/JavaScript: //#region and //#endregion or // #region and // #endregion
C#:                    #region and #endregion
C/C++:                 #pragma region and #pragma endregion
F#:                    //#region and //#endregion
PowerShell:            #region and #endregion
Python:                #region and #endregion
VB:                    #Region and #End Region
PHP:                   #region and #endregion
Bat:                   ::#region and ::#endregion or REM #region and REM #endregion
Markdown:              <!-- #region --> and <!-- #endregion -->
Golang                 //region and //endregion or //#region and //#endregion
Java                   //#region and //#endregion
CSS/SCSS/Less:         /* #region */ and /* #endregion */ or /*#region*/ and /*#endregion*/
SCSS/Less:             // #region and // #endregion
Go:                    // region, // endregion and // #region, // #endregion
shellscript:           # region and # endregion
Perl5                  #region and #endregion or =pod and =cut`

Important: If you don't see your language in the list::

Each language also has snippets available for the markers. Type '#' and invoke code completion to see them. To have region markers configured for your language, contact the language extension provider.

So type # and then Ctrl+Space to see the region markers for any language.


Difference between DOMContentLoaded and load events

See the difference yourself:

DEMO

From Microsoft IE

The DOMContentLoaded event fires when parsing of the current page is complete; the load event fires when all files have finished loading from all resources, including ads and images. DOMContentLoaded is a great event to use to hookup UI functionality to complex web pages.

From Mozilla Developer Network

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

Using global variables between files?

See Python's document on sharing global variables across modules:

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).

config.py:

x = 0   # Default value of the 'x' configuration setting

Import the config module in all modules of your application; the module then becomes available as a global name.

main.py:

import config
print (config.x)

or

from config import x
print (x)

In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.

How to convert the ^M linebreak to 'normal' linebreak in a file opened in vim?

in order to get the ^M character to match I had to visually select it and then use the OS copy to clipboard command to retrieve it. You can test it by doing a search for the character before trying the replace command.

/^M

should select the first bad line

:%s/^M/\r/g

will replace all the errant ^M with carriage returns.

This is as functions in MacVim, which is based on gvim 7.

EDIT:

Having this problem again on my Windows 10 machine, which has Ubuntu for Windows, and I think this is causing fileformat issues for vim. In this case changing the ff to unix, mac, or dos did nothing other than to change the ^M to ^J and back again.

The solution in this case:

:%s/\r$/ /g
:%s/ $//g

The reason I went this route is because I wanted to ensure I was being non-destructive with my file. I could have :%s/\r$//g but that would have deleted the carriage returns right out, and could have had unexpected results. Instead we convert the singular CR character, here a ^M character, into a space, and then remove all spaces at the end of lines (which for me is a desirable result regardless)

Sorry for reviving an old question that has long since been answered, but there seemed to be some confusion afoot and I thought I'd help clear some of that up since this is coming up high in google searches.

What is the http-header "X-XSS-Protection"?

TL;DR: All well written web sites (/apps) must emit the header X-XSS-Protection: 0 and just forget about this feature. If you want to have extra security that better user agents can provide, use a strict Content-Security-Policy header.

Long answer:

HTTP header X-XSS-Protection is one of those things that Microsoft introduced in Internet Explorer 8.0 (MSIE 8) that was supposed to improve security of incorrectly written web sites.

The idea is to apply some kind of heuristics to try to detect reflection XSS attack and automatically neuter the attack.

The problematic part of this is "heuristics" and "neutering". The heuristics causes false positives and neutering cannot be safely done because it causes side-effects that can be used to implement XSS attacks and DoS attacks on perfectly safe web sites.

The bad part is that if a web site does not emit the header X-XSS-Protection then the browser will behave as if the header X-XSS-Protection: 1 had been emitted. The worst part is that this value is the least-safe value of all possible values for this header!

For a given secure web site (that is, the site does not have reflected XSS vulnerabilities) this "XSS protection" feature allows following attacks:

X-XSS-Protection: 1 allows attacker to selectively block parts of JavaScript and keep rest of the scripts running. This is possible because the heuristics of this feature are simply "if value of any GET parameter is found in the scripting part of the page source, the script will be automatically modified in user agent dependant way". In practice, the attacker can e.g. add parameter disablexss=<script src="framebuster.js" and the browser will automatically remove the string <script src="framebuster.js" from the actual page source. Note that the rest of the page continues run and the attacker just removed this part of page security. In practice, any JS in the page source can be modified. For some cases, a page without XSS vulnerability having reflected content can be used to run selected JavaScript on page due the neutering incorrectly turning plain text data into executable JavaScript code. (That is, turn textual data within a normal DOM text node into content of <script> tag and execute it!)

X-XSS-Protection: 1; mode=block allows attacker to leak data from the page source by using the behavior of the page as side-channel. For example, if the page contains JavaScript code along the lines of var csrf_secret="521231347843", the attacker simply adds an extra parameter e.g. leak=var%20csrf_secret="3 and if the page is NOT blocked, the 3 was incorrect first digit. The attacker tries again, this time leak=var%20csrf_secret="5 and the page loading will be aborted. This allows the attacker to know that the first digit of the secret is 5. The attacker then continues to guess the next digit. This allows easily brute-forcing of CSRF secrets or any other secret value in the <script> source.

In the end, if your site is full of XSS reflection attacks, using the default value of 1 will reduce the attack surface a little bit. However, if your site is secure and you don't emit X-XSS-Protection: 0, your site will be vulnerable with any browser that supports this feature. If you want defense in depth support from browsers against yet-unknown XSS vulnerabilities on your site, use a strict Content-Security-Policy header and keep sending 0 for this mis-feature. That doesn't open your site to any known vulnerabilities.

Currently this feature is enabled by default in MSIE, Safari and Google Chrome. This used to be enabled in Edge but Microsoft already removed this mis-feature from Edge. Mozilla Firefox never implemented this.

See also:

https://homakov.blogspot.com/2013/02/hacking-facebook-with-oauth2-and-chrome.html https://blog.innerht.ml/the-misunderstood-x-xss-protection/ http://p42.us/ie8xss/Abusing_IE8s_XSS_Filters.pdf https://www.slideshare.net/masatokinugawa/xxn-en https://bugs.chromium.org/p/chromium/issues/detail?id=396544 https://bugs.chromium.org/p/chromium/issues/detail?id=498982

Map a network drive to be used by a service

There is a good answer here: https://superuser.com/a/651015/299678

I.e. You can use a symbolic link, e.g.

mklink /D C:\myLink \\127.0.0.1\c$

How to find out what the date was 5 days ago?

If you want a method in which you know the algorithm, or the functions mentioned in the previous answer aren't available: convert the date to Julian Day number (which is a way of counting days from January 1st, 4713 B.C), then subtract five, then convert back to calendar date (year, month, day). Sources of the algorithms for the two conversions is section 9 of http://www.hermetic.ch/cal_stud/jdn.htm or http://en.wikipedia.org/wiki/Julian_day

How to use code to open a modal in Angular 2?

We can use jquery to open bootstrap modal.

ngAfterViewInit() { 
      $('#scanModal').modal('show'); 
}

How can prevent a PowerShell window from closing so I can see the error?

You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post.

  1. One-time Fix: Run your script from the PowerShell Console, or launch the PowerShell process using the -NoExit switch. e.g. PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
  2. Per-script Fix: Add a prompt for input to the end of your script file. e.g. Read-Host -Prompt "Press Enter to exit"
  3. Global Fix: Change your registry key to always leave the PowerShell Console window open after the script finishes running. Here's the 2 registry keys that would need to be changed:

    ? Open With ? Windows PowerShell
    When you right-click a .ps1 file and choose Open With

    Registry Key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command

    Default Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"
    

    Desired Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""
    

    ? Run with PowerShell
    When you right-click a .ps1 file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed).

    Registry Key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command

    Default Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
    

    Desired Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \"%1\""
    

You can download a .reg file from my blog to modify the registry keys for you if you don't want to do it manually.

It sounds like you likely want to use option #2. You could even wrap your whole script in a try block, and only prompt for input if an error occurred, like so:

try
{
    # Do your script's stuff
}
catch
{
    Write-Error $_.Exception.ToString()
    Read-Host -Prompt "The above error occurred. Press Enter to exit."
}

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

I had the same problem.

In my case the problem was with maven home directory and user settings file in Intellij Settings under Maven. I had installed Maven not in the default directory and I had also changed the location of the settings.xml file. This should also be changed in the IntelliJ Settings.

Hope this helps also.

Returning unique_ptr from functions

This is in no way specific to std::unique_ptr, but applies to any class that is movable. It's guaranteed by the language rules since you are returning by value. The compiler tries to elide copies, invokes a move constructor if it can't remove copies, calls a copy constructor if it can't move, and fails to compile if it can't copy.

If you had a function that accepts std::unique_ptr as an argument you wouldn't be able to pass p to it. You would have to explicitly invoke move constructor, but in this case you shouldn't use variable p after the call to bar().

void bar(std::unique_ptr<int> p)
{
    // ...
}

int main()
{
    unique_ptr<int> p = foo();
    bar(p); // error, can't implicitly invoke move constructor on lvalue
    bar(std::move(p)); // OK but don't use p afterwards
    return 0;
}

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

The pointer-events could be useful for this problem as you would be able to put a div over the arrow button, but still be able to click the arrow button.

The pointer-events css makes it possible to click through a div.

This approach will not work for IE versions older than IE11, however. You could something working in IE8 and IE9 if the element you put on top of the arrow button is an SVG element, but it will be more complicated to style the button the way you want proceeding like this.

Here a Js fiddle example: http://jsfiddle.net/e7qnqzx6/2/

Define a global variable in a JavaScript function

If you are making a startup function, you can define global functions and variables this way:

function(globalScope)
{
    // Define something
    globalScope.something()
    {
        alert("It works");
    };
}(window)

Because the function is invoked globally with this argument, this is global scope here. So, the something should be a global thing.

What is the difference between i++ & ++i in a for loop?

The way for loop is processed is as follows

1 First, initialization is performed (i=0)

2 the check is performed (i < n)

3 the code in the loop is executed.

4 the value is incremented

5 Repeat steps 2 - 4

This is the reason why, there is no difference between i++ and ++i in the for loop which has been used.

Differences between Emacs and Vim

vim is a handy editor, you simple type vim filename to open the file, edit, save and close.

emacs is an "operating system" pretend to be an editor, you can eval code to change its behavior, and extend it as you like. A mode to receive/send email on emacs is like an email software on operating system.

When doing simple editing, for example, modify a config file, I use vim.

Otherwise, I never leave emacs.

C# : assign data to properties via constructor vs. instantiating

Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:

public class Album 
{
    // Note that we make the setter 'private'
    public string Name { get; private set; }
    public string Artist { get; private set; }
    public int Year { get; private set; }

    public Album(string name, string artist, int year)
    {
        this.Name = name;
        this.Artist = artist;
        this.Year = year;
    }
}

If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:

new { 
    Name = "Some Name",
    Artist = "Some Artist",
    Year = 1994
};

the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const(C++) or final (Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.

That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:

public void Configure(ConfigurationSetup setup);

and I have a class that has a number of members such as:

class ConfigurationSetup {
    public String Name { get; set; }
    public String Location { get; set; }
    public Int32 Size { get; set; }
    public DateTime Time { get; set; }

    // ... and some other configuration stuff... 
}

Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name and Location, I can just do:

ConfigurationSetup setup = new ConfigurationSetup {
    Name = "Some Name",
    Location = "San Jose"
};

and this allows me to set up some combination without having to define a new constructor for every possibly permutation.

On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.

How to hide output of subprocess in Python 2.7

Redirect the output to DEVNULL:

import os
import subprocess

FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['echo', 'foo'], 
    stdout=FNULL, 
    stderr=subprocess.STDOUT)

It is effectively the same as running this shell command:

retcode = os.system("echo 'foo' &> /dev/null")

Update: This answer applies to the original question relating to python 2.7. As of python >= 3.3 an official subprocess.DEVNULL symbol was added.

retcode = subprocess.call(['echo', 'foo'], 
    stdout=subprocess.DEVNULL, 
    stderr=subprocess.STDOUT)

Count characters in textarea

substring() needs to become substr().

Example: jsfiddle.net/xqyWV

Installing NumPy via Anaconda in Windows

The above answers seem to resolve the issue. If it doesn't, then you may also try to update conda using the following command.

conda update conda

And then try to install numpy using

conda install numpy

Convert categorical data in pandas dataframe

This works for me:

pandas.factorize( ['B', 'C', 'D', 'B'] )[0]

Output:

[0, 1, 2, 0]

Running code after Spring Boot starts

Use a SmartInitializingSingleton bean in spring > 4.1

@Bean
public SmartInitializingSingleton importProcessor() {
    return () -> {
        doStuff();
    };

}

As alternative a CommandLineRunner bean can be implemented or annotating a bean method with @PostConstruct.

ERROR 1148: The used command is not allowed with this MySQL version

I got this error while loading data when using docker[1]. The solution worked after I followed these next steps. Initially, I created the database and table datavault and fdata. When I tried to import the data[2], I got the error[3]. Then I did:

  • SET GLOBAL local_infile = 1;
  • Confirm using SHOW VARIABLES LIKE 'local_infile';
  • Then I restarted my mysql session: mysql -P 3306 -u required --local-infile=1 -p, see [4] for user creation.
  • I recreated my table as this solved my problem:
    • use datavault;
    • drop table fdata;
    • CREATE TABLE fdata (fID INT, NAME VARCHAR(64), LASTNAME VARCHAR(64), EMAIL VARCHAR(128), GENDER VARCHAR(12), IPADDRESS VARCHAR(40));
  • Finally I imported the data using [2].

For completeness, I would add I was running the mysql version inside the container via docker exec -it testdb sh. The mysql version was mysql Ver 8.0.17 for Linux on x86_64 (MySQL Community Server - GPL). This was also tested with mysql.exe Ver 14.14 Distrib 5.7.14, for Win64 (x86_64) which was another version of mysql from WAMP64. The associated commands used are listed in [5].


[1] docker run --name testdb -v //c/Users/C/Downloads/data/csv-data/:/var/data -p 3306 -e MYSQL_ROOT_PASSWORD=password -d mysql:latest

[2] load data local infile '/var/data/mockdata.csv' into table fdata fields terminated by ',' enclosed by '' lines terminated by '\n' IGNORE 1 ROWS;

[3] ERROR 1148 (42000): The used command is not allowed with this MySQL version

[4] The required client was created using:

  • CREATE USER 'required'@'%' IDENTIFIED BY 'password';
  • GRANT ALL PRIVILEGES ON * . * TO 'required'@'%';
  • FLUSH PRIVILEGES;
  • You might need this line ALTER USER 'required'@'%' IDENTIFIED WITH mysql_native_password BY 'password'; if you run into this error: Authentication plugin ‘caching_sha2_password’ cannot be loaded

[5] Commands using mysql from WAMP64:

  • mysql -urequired -ppassword -P 32775 -h 192.168.99.100 --local-infile=1 where the port is thee mapped port into the host as described by docker ps -a and the host ip was optained using docker-machine ip (This depends on OS and possibly Docker version).
  • Create database datavault2 and table fdata as described above
  • load data local infile 'c:/Users/C/Downloads/data/csv-data/mockdata.csv' into table fdata fields terminated by ',' enclosed by '' lines terminated by '\n';
  • For my record, this other alternative to load the file worked after I have previously created datavault3 and fdata: mysql -urequired -ppassword -P 32775 -h 192.168.99.100 --local-infile datavault3 -e "LOAD DATA LOCAL INFILE 'c:/Users/C/Downloads/data/csv-data/mockdata.csv' REPLACE INTO TABLE fdata FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 ROWS" and it successfully loaded the data easily checked after running select * from fdata limit 10;.

Can I obtain method parameter name using Java reflection?

To add my 2 cents; parameter info is available in a class file "for debugging" when you use javac -g to compile the source. And it is available to APT but you'll need an annotation so no use to you. (Somebody discussed something similar 4-5 years ago here: http://forums.java.net/jive/thread.jspa?messageID=13467&tstart=0 )

Overall in-short you can't get it unless you work on Source files directly (similar to what APT does at compile time).

socket.error: [Errno 48] Address already in use

You can also serve on the next-highest available port doing something like this in Python:

import SimpleHTTPServer
import SocketServer

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

port = 8000
while True:
    try:
        httpd = SocketServer.TCPServer(('', port), Handler)
        print 'Serving on port', port
        httpd.serve_forever()
    except SocketServer.socket.error as exc:
        if exc.args[0] != 48:
            raise
        print 'Port', port, 'already in use'
        port += 1
    else:
        break

If you need to do the same thing for other utilities, it may be more convenient as a bash script:

#!/usr/bin/env bash

MIN_PORT=${1:-1025}
MAX_PORT=${2:-65535}

(netstat -atn | awk '{printf "%s\n%s\n", $4, $4}' | grep -oE '[0-9]*$'; seq "$MIN_PORT" "$MAX_PORT") | sort -R | head -n 1

Set that up as a executable with the name get-free-port and you can do something like this:

someprogram --port=$(get-free-port)

That's not as reliable as the native Python approach because the bash script doesn't capture the port -- another process could grab the port before your process does (race condition) -- but still may be useful enough when using a utility that doesn't have a try-try-again approach of its own.

col align right

How about this? Bootstrap 4

<div class="row justify-content-end">
    <div class="col-3">
        The content is positioned as if there was
        "col-9" classed div appending this one.
    </div>
</div>

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you really need to use sys.path.insert, consider leaving sys.path[0] as it is:

sys.path.insert(1, path_to_dev_pyworkbooks)

This could be important since 3rd party code may rely on sys.path documentation conformance:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.

What happens to C# Dictionary<int, int> lookup if the key does not exist?

You should check for Dictionary.ContainsKey(int key) before trying to pull out the value.

Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(2,4);
myDictionary.Add(3,5);

int keyToFind = 7;
if(myDictionary.ContainsKey(keyToFind))
{
    myValueLookup = myDictionay[keyToFind];
    // do work...
}
else
{
    // the key doesn't exist.
}

How to split an integer into an array of digits?

While list(map(int, str(x))) is the Pythonic approach, you can formulate logic to derive digits without any type conversion:

from math import log10

def digitize(x):
    n = int(log10(x))
    for i in range(n, -1, -1):
        factor = 10**i
        k = x // factor
        yield k
        x -= k * factor

res = list(digitize(5243))

[5, 2, 4, 3]

One benefit of a generator is you can feed seamlessly to set, tuple, next, etc, without any additional logic.

Save PHP variables to a text file

Use serialize() on the variable, then save the string to a file. later you will be able to read the serialed var from the file and rebuilt the original var (wether it was a string or an array or an object)

Password encryption at client side

You need a library that can encrypt your input on client side and transfer it to the server in encrypted form.

You can use following libs:

  • jCryption. Client-Server asymmetric encryption over Javascript

Update after 3 years (2013):

Update after 4 years (2014):

How to install Selenium WebDriver on Mac OS

To use the java -jar selenium-server-standalone-2.45.0.jar command-line tool you need to install a JDK. You need to download and install the JDK and the standalone selenium server.

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

The question is already answered, Updating answer to add the PyCharm bin directory to $PATH var, so that pycharm editor can be opened from anywhere(path) in terminal.

Edit the bashrc file,

nano .bashrc

Add following line at the end of bashrc file

export PATH="<path-to-unpacked-pycharm-installation-directory>/bin:$PATH"

Now you can open pycharm from anywhere in terminal

pycharm.sh

strdup() - what does it do in C?

Exactly what it sounds like, assuming you're used to the abbreviated way in which C and UNIX assigns words, it duplicates strings :-)

Keeping in mind it's actually not part of the ISO C standard itself(a) (it's a POSIX thing), it's effectively doing the same as the following code:

char *strdup(const char *src) {
    char *dst = malloc(strlen (src) + 1);  // Space for length plus nul
    if (dst == NULL) return NULL;          // No memory
    strcpy(dst, src);                      // Copy the characters
    return dst;                            // Return the new string
}

In other words:

  1. It tries to allocate enough memory to hold the old string (plus a '\0' character to mark the end of the string).

  2. If the allocation failed, it sets errno to ENOMEM and returns NULL immediately. Setting of errno to ENOMEM is something malloc does in POSIX so we don't need to explicitly do it in our strdup. If you're not POSIX compliant, ISO C doesn't actually mandate the existence of ENOMEM so I haven't included that here(b).

  3. Otherwise the allocation worked so we copy the old string to the new string(c) and return the new address (which the caller is responsible for freeing at some point).

Keep in mind that's the conceptual definition. Any library writer worth their salary may have provided heavily optimised code targeting the particular processor being used.


(a) However, functions starting with str and a lower case letter are reserved by the standard for future directions. From C11 7.1.3 Reserved identifiers:

Each header declares or defines all identifiers listed in its associated sub-clause, and *optionally declares or defines identifiers listed in its associated future library directions sub-clause.**

The future directions for string.h can be found in C11 7.31.13 String handling <string.h>:

Function names that begin with str, mem, or wcs and a lowercase letter may be added to the declarations in the <string.h> header.

So you should probably call it something else if you want to be safe.


(b) The change would basically be replacing if (d == NULL) return NULL; with:

if (d == NULL) {
    errno = ENOMEM;
    return NULL;
}

(c) Note that I use strcpy for that since that clearly shows the intent. In some implementations, it may be faster (since you already know the length) to use memcpy, as they may allow for transferring the data in larger chunks, or in parallel. Or it may not :-) Optimisation mantra #1: "measure, don't guess".

In any case, should you decide to go that route, you would do something like:

char *strdup(const char *src) {
    size_t len = strlen(src) + 1;       // String plus '\0'
    char *dst = malloc(len);            // Allocate space
    if (dst == NULL) return NULL;       // No memory
    memcpy (dst, src, len);             // Copy the block
    return dst;                         // Return the new string
}

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

    <style>
    .Button
    {
        margin:5px;
    }
    </style>

 <asp:Button ID="Button1" runat="server" Text="Button" CssClass="Button" />
 <asp:Button ID="Button2" runat="server" Text="Button" CssClass="Button"/>

Create an ArrayList of unique values

I use helper class. Not sure it's good or bad

public class ListHelper<T> {
    private final T[] t;

    public ListHelper(T[] t) {
        this.t = t;
    }

    public List<T> unique(List<T> list) {
       Set<T> set = new HashSet<>(list);
        return Arrays.asList(set.toArray(t));
    }
}

Usage and test:

import static org.assertj.core.api.Assertions.assertThat;


public class ListHelperTest {

    @Test
    public void unique() {
        List<String> s = Arrays.asList("abc", "cde", "dfg", "abc");
        List<String> unique = new ListHelper<>(new String[0]).unique(s);
        assertThat(unique).hasSize(3);
    }
}

Or Java8 version:

public class ListHelper<T> {
    public Function<List<T>, List<T>> unique() {
        return l -> l.stream().distinct().collect(Collectors.toList());
    }
}

public class ListHelperTest {
    @Test
    public void unique() {
        List<String> s = Arrays.asList("abc", "cde", "dfg", "abc");
        assertThat(new ListHelper<String>().unique().apply(s)).hasSize(3);
    }
}

When should I use git pull --rebase?

I think you should use git pull --rebase when collaborating with others on the same branch. You are in your work ? commit ? work ? commit cycle, and when you decide to push your work your push is rejected, because there's been parallel work on the same branch. At this point I always do a pull --rebase. I do not use squash (to flatten commits), but I rebase to avoid the extra merge commits.

As your Git knowledge increases you find yourself looking a lot more at history than with any other version control systems I've used. If you have a ton of small merge commits, it's easy to lose focus of the bigger picture that's happening in your history.

This is actually the only time I do rebasing(*), and the rest of my workflow is merge based. But as long as your most frequent committers do this, history looks a whole lot better in the end.

(*) While teaching a Git course, I had a student arrest me on this, since I also advocated rebasing feature branches in certain circumstances. And he had read this answer ;) Such rebasing is also possible, but it always has to be according to a pre-arranged/agreed system, and as such should not "always" be applied. And at that time I usually don't do pull --rebase either, which is what the question is about ;)

Installing PDO driver on MySQL Linux server

  1. PDO stands for PHP Data Object.
  2. PDO_MYSQL is the driver that will implement the interface between the dataobject(database) and the user input (a layer under the user interface called "code behind") accessing your data object, the MySQL database.

The purpose of using this is to implement an additional layer of security between the user interface and the database. By using this layer, data can be normalized before being inserted into your data structure. (Capitals are Capitals, no leading or trailing spaces, all dates at properly formed.)

But there are a few nuances to this which you might not be aware of.

First of all, up until now, you've probably written all your queries in something similar to the URL, and you pass the parameters using the URL itself. Using the PDO, all of this is done under the user interface level. User interface hands off the ball to the PDO which carries it down field and plants it into the database for a 7-point TOUCHDOWN.. he gets seven points, because he got it there and did so much more securely than passing information through the URL.

You can also harden your site to SQL injection by using a data-layer. By using this intermediary layer that is the ONLY 'player' who talks to the database itself, I'm sure you can see how this could be much more secure. Interface to datalayer to database, datalayer to database to datalayer to interface.

And:

By implementing best practices while writing your code you will be much happier with the outcome.

Additional sources:

Re: MySQL Functions in the url php dot net/manual/en/ref dot pdo-mysql dot php

Re: three-tier architecture - adding security to your applications https://blog.42.nl/articles/introducing-a-security-layer-in-your-application-architecture/

Re: Object Oriented Design using UML If you really want to learn more about this, this is the best book on the market, Grady Booch was the father of UML http://dl.acm.org/citation.cfm?id=291167&CFID=241218549&CFTOKEN=82813028

Or check with bitmonkey. There's a group there I'm sure you could learn a lot with.

>

If we knew what the terminology really meant we wouldn't need to learn anything.

>

Check whether a variable is a string in Ruby

You can do:

foo.instance_of?(String)

And the more general:

foo.kind_of?(String)

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

If you want to use SOCKS5 proxy, you may try rubygems-socksproxy https://github.com/gussan/rubygems-socksproxy.

It works for me on OSX 10.9.3.

How to align footer (div) to the bottom of the page?

Use <div style="position:fixed;bottom:0;height:auto;margin-top:40px;width:100%;text-align:center">I am footer</div>. Footer will not go upwards

Better way of getting time in milliseconds in javascript?

Try Date.now().

The skipping is most likely due to garbage collection. Typically garbage collection can be avoided by reusing variables as much as possible, but I can't say specifically what methods you can use to reduce garbage collection pauses.

How to enable explicit_defaults_for_timestamp?

For me it worked to add the phrase "explicit_defaults_for_timestamp = ON" without quotes into the config file my.ini.

Make sure you add this phrase right underneath the [mysqld] statement in the config file.

You will find my.ini under C:\ProgramData\MySQL\MySQL Server 5.7 if you had conducted the default installation of MySQL.

What is the difference between ( for... in ) and ( for... of ) statements?

I found the following explanation from https://javascript.info/array very helpful:

One of the oldest ways to cycle array items is the for loop over indexes:

let arr = ["Apple", "Orange", "Pear"];

for (let i = 0; i < arr.length; i++) { alert( arr[i] ); } But for arrays there is another form of loop, for..of:

let fruits = ["Apple", "Orange", "Plum"];

// iterates over array elements for (let fruit of fruits) { alert( fruit ); } The for..of doesn’t give access to the number of the current element, just its value, but in most cases that’s enough. And it’s shorter.

Technically, because arrays are objects, it is also possible to use for..in:

let arr = ["Apple", "Orange", "Pear"];

for (let key in arr) { alert( arr[key] ); // Apple, Orange, Pear } But that’s actually a bad idea. There are potential problems with it:

The loop for..in iterates over all properties, not only the numeric ones.

There are so-called “array-like” objects in the browser and in other environments, that look like arrays. That is, they have length and indexes properties, but they may also have other non-numeric properties and methods, which we usually don’t need. The for..in loop will list them though. So if we need to work with array-like objects, then these “extra” properties can become a problem.

The for..in loop is optimized for generic objects, not arrays, and thus is 10-100 times slower. Of course, it’s still very fast. The speedup may only matter in bottlenecks. But still we should be aware of the difference.

Generally, we shouldn’t use for..in for arrays.

Unable to run Java GUI programs with Ubuntu

I too had OpenJDK on my Ubuntu machine:

$ java -version
java version "1.7.0_51"
OpenJDK Runtime Environment (IcedTea 2.4.4) (7u51-2.4.4-0ubuntu0.13.04.2)
OpenJDK 64-Bit Server VM (build 24.45-b08, mixed mode)

Replacing OpenJDK with the HotSpot VM works fine:

sudo apt-get autoremove openjdk-7-jre-headless

How to install the JDK on Ubuntu (Linux)

Get exit code of a background process

Another solution is to monitor processes via the proc filesystem (safer than ps/grep combo); when you start a process it has a corresponding folder in /proc/$pid, so the solution could be

#!/bin/bash
....
doSomething &
local pid=$!
while [ -d /proc/$pid ]; do # While directory exists, the process is running
    doSomethingElse
    ....
else # when directory is removed from /proc, process has ended
    wait $pid
    local exit_status=$?
done
....

Now you can use the $exit_status variable however you like.

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I had a similar problem.

Problem in error code below:

int prevSize = messageListHistory.size();
// some insert
adapter.notifyItemRangeInserted(prevSize - 1, messageListHistory.size() -1);

Solution:

int prevSize = messageListHistory.size();
// some insert
adapter.notifyItemRangeInserted(prevSize, messageListHistory.size() -prevSize);

Get the selected value in a dropdown using jQuery.

$('#availability').find('option:selected').val() // For Value 
$('#availability').find('option:selected').text() // For Text
or 
$('#availability option:selected').val() // For Value 
$('#availability option:selected').text() // For Text

How to remove underline from a name on hover

try this:

legend.green-color a:hover{
    text-decoration: none;
}

AngularJS - value attribute for select

You could modify you model to look like this:

$scope.options = {
    "AL" : "Alabama",
    "AK" : "Alaska",
    "AS" : "American Samoa"
  };

Then use

<select ng-options="k as v for (k,v) in options"></select>

How to get UTC timestamp in Ruby?

if you need a human-readable timestamp (like rails migration has) ex. "20190527141340"

Time.now.utc.to_formatted_s(:number)  # using Rails

Time.now.utc.strftime("%Y%m%d%H%M%S") # using Ruby

Search for one value in any column of any table inside a database

I expanded the code, because it's not told me the 'record number', and I must to refind it.

CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT

-- Copyright @ 2012 Gyula Kulifai. All rights reserved.
-- Extended By: Gyula Kulifai
-- Purpose: To put key values, to exactly determine the position of search
-- Resources: Anatoly Lubarsky
-- Date extension: 19th October 2012 12:24 GMT
-- Tested on: SQL Server 10.0.5500 (SQL Server 2008 SP3)

CREATE TABLE #Results (TableName nvarchar(370), KeyValues nvarchar(3630), ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
    ,@TableShortName nvarchar(256)
    ,@TableKeys nvarchar(512)
    ,@SQL nvarchar(3830)

SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''

    -- Scan Tables
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )
    Set @TableShortName=PARSENAME(@TableName, 1)
    -- print @TableName + ';' + @TableShortName +'!' -- *** DEBUG LINE ***

        -- LOOK Key Fields, Set Key Columns
        SET @TableKeys=''
        SELECT @TableKeys = @TableKeys + '''' + QUOTENAME([name]) + ': '' + CONVERT(nvarchar(250),' + [name] + ') + ''' + ',' + ''' + '
         FROM syscolumns 
         WHERE [id] IN (
            SELECT [id] 
             FROM sysobjects 
             WHERE [name] = @TableShortName)
           AND colid IN (
            SELECT SIK.colid 
             FROM sysindexkeys SIK 
             JOIN sysobjects SO ON 
                SIK.[id] = SO.[id]  
             WHERE 
                SIK.indid = 1
                AND SO.[name] = @TableShortName)
        If @TableKeys<>''
            SET @TableKeys=SUBSTRING(@TableKeys,1,Len(@TableKeys)-8)
        -- Print @TableName + ';' + @TableKeys + '!' -- *** DEBUG LINE ***

    -- Search in Columns
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        ) -- Set ColumnName

        IF @ColumnName IS NOT NULL
        BEGIN
            SET @SQL='
                SELECT 
                    ''' + @TableName + '''
                    ,'+@TableKeys+'
                    ,''' + @ColumnName + '''
                ,LEFT(' + @ColumnName + ', 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            --Print @SQL -- *** DEBUG LINE ***
            INSERT INTO #Results
                Exec (@SQL)
        END -- IF ColumnName
    END -- While Table and Column
END --While Table

SELECT TableName, KeyValues, ColumnName, ColumnValue FROM #Results
END

Access a JavaScript variable from PHP

try adding this to your js function:

    var outputvar = document.getElementById("your_div_id_inside_html_form");
    outputvar.innerHTML='<input id=id_to_send_to_php value='+your_js_var+'>';

Later in html:

    <div id="id_you_choosed_for_outputvar"></div>

this div will contain the js var to be passed through a form to another js function or to php, remember to place it inside your html form!. This solution is working fine for me.

In your specific geolocation case you can try adding the following to function showPosition(position):

    var outputlon = document.getElementById("lon1");
    outputlon.innerHTML = '<input id=lon value='+lon+'>';
    var outputlat = document.getElementById("lat1");
    outputlat.innerHTML = '<input id=lat value='+lat+'>';  

later add these div to your html form:

<div id=lat1></div>
<div id=lon1></div>

In these div you'll get latitude and longitude as input values for your php form, you would better hide them using css (show only the marker on a map if used) in order to avoid users to change them before to submit, and set your database to accept float values with lenght 10,7.

Hope this will help.

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

_x000D_
_x000D_
const format1 = "YYYY-MM-DD HH:mm:ss"
const format2 = "YYYY-MM-DD"
var date1 = new Date("2020-06-24 22:57:36");
var date2 = new Date();

dateTime1 = moment(date1).format(format1);
dateTime2 = moment(date2).format(format2);

document.getElementById("demo1").innerHTML = dateTime1;
document.getElementById("demo2").innerHTML = dateTime2;
_x000D_
<!DOCTYPE html>
<html>
<body>

<p id="demo1"></p>
<p id="demo2"></p>

<script src="https://momentjs.com/downloads/moment.js"></script>

</body>
</html>
_x000D_
_x000D_
_x000D_

Setting button text via javascript

The value of a button element isn't the displayed text, contrary to what happens to input elements of type button.

You can do this :

 b.appendChild(document.createTextNode('test value'));

Demonstration

rename the columns name after cbind the data

Try:

colnames(merger)[1] <- "Date"

Example

Here is a simple example:

a <- 1:10
b <- cbind(a, a, a)
colnames(b)

# change the first one
colnames(b)[1] <- "abc"

# change all colnames
colnames(b) <- c("aa", "bb", "cc")

LocalDate to java.util.Date and vice versa simplest conversion?

I solved this question with solution below

  import org.joda.time.LocalDate;
  Date myDate = new Date();
  LocalDate localDate = LocalDate.fromDateFields(myDate);
  System.out.println("My date using Date" Nov 18 11:23:33 BRST 2016);
  System.out.println("My date using joda.time LocalTime" 2016-11-18);

In this case localDate print your date in this format "yyyy-MM-dd"

How to call a vue.js function on page load

you can also do this using mounted

https://vuejs.org/v2/guide/migration.html#ready-replaced

....
methods:{
    getUnits: function() {...}
},
mounted: function(){
    this.$nextTick(this.getUnits)
}
....

Formatting floats without trailing zeros

Here's a solution that worked for me. It's a blend of the solution by PolyMesh and use of the new .format() syntax.

for num in 3, 3., 3.0, 3.1, 3.14, 3.140:
    print('{0:.2f}'.format(num).rstrip('0').rstrip('.'))

Output:

3
3
3
3.1
3.14
3.14

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

How to detect simple geometric shapes using OpenCV

You can also use template matching to detect shapes inside an image.

Assign output of os.system to a variable and prevent it from being displayed on the screen

The commands module is a reasonably high-level way to do this:

import commands
status, output = commands.getstatusoutput("cat /etc/services")

status is 0, output is the contents of /etc/services.

using scp in terminal

You can download in the current directory with a . :

cd # by default, goes to $HOME
scp me@host:/path/to/file .

or in you HOME directly with :

scp me@host:/path/to/file ~

UNIX export command

When you execute a program the child program inherits its environment variables from the parent. For instance if $HOME is set to /root in the parent then the child's $HOME variable is also set to /root.

This only applies to environment variable that are marked for export. If you set a variable at the command-line like

$ FOO="bar"

That variable will not be visible in child processes. Not unless you export it:

$ export FOO

You can combine these two statements into a single one in bash (but not in old-school sh):

$ export FOO="bar"

Here's a quick example showing the difference between exported and non-exported variables. To understand what's happening know that sh -c creates a child shell process which inherits the parent shell's environment.

$ FOO=bar
$ sh -c 'echo $FOO'

$ export FOO
$ sh -c 'echo $FOO'
bar

Note: To get help on shell built-in commands use help export. Shell built-ins are commands that are part of your shell rather than independent executables like /bin/ls.

Set QLineEdit to accept only numbers

You could also set an inputMask:

QLineEdit.setInputMask("9")

This allows the user to type only one digit ranging from 0 to 9. Use multiple 9's to allow the user to enter multiple numbers. See also the complete list of characters that can be used in an input mask.

(My answer is in Python, but it should not be hard to transform it to C++)

MySQL Error 1264: out of range value for column

tl;dr

Make sure your AUTO_INCREMENT is not out of range. In that case, set a new value for it with:

ALTER TABLE table_name AUTO_INCREMENT=100 -- Change 100 to the desired number

Explanation

AUTO_INCREMENT can contain a number that is bigger than the maximum value allowed by the datatype. This can happen if you filled up a table that you emptied afterward but the AUTO_INCREMENT stayed the same, but there might be different reasons as well. In this case a new entry's id would be out of range.

Solution

If this is the cause of your problem, you can fix it by setting AUTO_INCREMENT to one bigger than the latest row's id. So if your latest row's id is 100 then:

ALTER TABLE table_name AUTO_INCREMENT=101

If you would like to check AUTO_INCREMENT's current value, use this command:

SELECT `AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND   TABLE_NAME   = 'TableName';

Variable's memory size in Python

Use sys.getsizeof to get the size of an object, in bytes.

>>> from sys import getsizeof
>>> a = 42
>>> getsizeof(a)
12
>>> a = 2**1000
>>> getsizeof(a)
146
>>>

Note that the size and layout of an object is purely implementation-specific. CPython, for example, may use totally different internal data structures than IronPython. So the size of an object may vary from implementation to implementation.

Permission denied (publickey) when SSH Access to Amazon EC2 instance

I struggled with the same permission denied error apparently due to

key_parse_private2: missing begin marker 

In my situation the cause was the ssh config file of the current user (~/.ssh/config).

Using the following:

ssh -i ~/myKey.pem ec2-user@<IP address> -v 'exit'

The initial output showed:

debug1: Reading configuration data /home/ec2-user/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 56: Applying options for *
debug1: Hostname has changed; re-reading configuration
debug1: Reading configuration data /home/ec2-user/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config

... many debug lines cut here ...

debug1: Next authentication method: publickey
debug1: Trying private key: /home/ec2-user/somekey.pem
debug1: key_parse_private2: missing begin marker
debug1: read PEM private key done: type RSA
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.

The third line above is where the problem actual was identified; however, I looked for at the debug message four lines from the bottom (above) and was misled. There isn't a problem with the key but I tested it and compared other configurations.

My user ssh config file reset the host via an unintended global setting as shown below. The first Host line should not have been a comment.

$ cat config
StrictHostKeyChecking=no
#Host myAlias
        user ec2-user
        Hostname bitbucket.org
#        IdentityFile ~/.ssh/somekey
#        IdentitiesOnly yes

Host my2ndAlias
        user myOtherUser
        Hostname bitbucket.org
        IdentityFile ~/.ssh/my2ndKey
        IdentitiesOnly yes

I hope someone else finds this helpful.

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

Don't know if this will be everybody's answer, but after some digging, here's what we came up with.

The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent

After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).

The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.

So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.

moment.js get current time in milliseconds?

var timeArr = moment().format('x');

returns the Unix Millisecond Timestamp as per the format() documentation.

Disabling vertical scrolling in UIScrollView

yes, pt2ph8's answer is right,

but if for some strange reason your contentSize should be higher than the UIScrollView, you can disable the vertical scrolling implementing the UIScrollView protocol method

 -(void)scrollViewDidScroll:(UIScrollView *)aScrollView;

just add this in your UIViewController

float oldY; // here or better in .h interface

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView
{
    [aScrollView setContentOffset: CGPointMake(aScrollView.contentOffset.x, oldY)];
    // or if you are sure you wanna it always on top:
    // [aScrollView setContentOffset: CGPointMake(aScrollView.contentOffset.x, 0)];
}

it's just the method called when the user scroll your UIScrollView, and doing so you force the content of it to have always the same .y

Override valueof() and toString() in Java enum

You still have an option to implement in your enum this:

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name){...}

Xcode 6 Bug: Unknown class in Interface Builder file

You need to check the box "Inherit Module From Target" Checkbox

enter image description here

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

The current spec of the CSS 3 Lists module does specify the ::marker pseudo-element which would do exactly what you want; FF has been tested to not support ::marker and I doubt that either Safari or Opera has it. IE, of course, does not support it.

So right now, the only way to do this is to use an image with list-style-image.

I guess you could wrap the contents of an li with a span and then you could set the color of each, but that seems a little hackish to me.

How to set caret(cursor) position in contenteditable element (div)?

Most answers you find on contenteditable cursor positioning are fairly simplistic in that they only cater for inputs with plain vanilla text. Once you using html elements within the container the text entered gets split into nodes and distributed liberally across a tree structure.

To set the cursor position I have this function which loops round all the child text nodes within the supplied node and sets a range from the start of the initial node to the chars.count character:

function createRange(node, chars, range) {
    if (!range) {
        range = document.createRange()
        range.selectNode(node);
        range.setStart(node, 0);
    }

    if (chars.count === 0) {
        range.setEnd(node, chars.count);
    } else if (node && chars.count >0) {
        if (node.nodeType === Node.TEXT_NODE) {
            if (node.textContent.length < chars.count) {
                chars.count -= node.textContent.length;
            } else {
                range.setEnd(node, chars.count);
                chars.count = 0;
            }
        } else {
           for (var lp = 0; lp < node.childNodes.length; lp++) {
                range = createRange(node.childNodes[lp], chars, range);

                if (chars.count === 0) {
                    break;
                }
            }
        }
    } 

    return range;
};

I then call the routine with this function:

function setCurrentCursorPosition(chars) {
    if (chars >= 0) {
        var selection = window.getSelection();

        range = createRange(document.getElementById("test").parentNode, { count: chars });

        if (range) {
            range.collapse(false);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    }
};

The range.collapse(false) sets the cursor to the end of the range. I've tested it with the latest versions of Chrome, IE, Mozilla and Opera and they all work fine.

PS. If anyone is interested I get the current cursor position using this code:

function isChildOf(node, parentId) {
    while (node !== null) {
        if (node.id === parentId) {
            return true;
        }
        node = node.parentNode;
    }

    return false;
};

function getCurrentCursorPosition(parentId) {
    var selection = window.getSelection(),
        charCount = -1,
        node;

    if (selection.focusNode) {
        if (isChildOf(selection.focusNode, parentId)) {
            node = selection.focusNode; 
            charCount = selection.focusOffset;

            while (node) {
                if (node.id === parentId) {
                    break;
                }

                if (node.previousSibling) {
                    node = node.previousSibling;
                    charCount += node.textContent.length;
                } else {
                     node = node.parentNode;
                     if (node === null) {
                         break
                     }
                }
           }
      }
   }

    return charCount;
};

The code does the opposite of the set function - it gets the current window.getSelection().focusNode and focusOffset and counts backwards all text characters encountered until it hits a parent node with id of containerId. The isChildOf function just checks before running that the suplied node is actually a child of the supplied parentId.

The code should work straight without change, but I have just taken it from a jQuery plugin I've developed so have hacked out a couple of this's - let me know if anything doesn't work!

jquery how to empty input field

if you hit the "back" button it usually tends to stick, what you can do is when the form is submitted clear the element then before it goes to the next page but after doing with the element what you need to.

    $('#shares').keyup(function(){
                payment = 0;
                calcTotal();
                gtotal = ($('#shares').val() * 1) + payment;
                gtotal = gtotal.toFixed(2);
                $('#shares').val('');
                $("p.total").html("Total Payment: <strong>" + gtotal + "</strong>");
            });

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

Adding one more answer for Windows users. If none of this solves the problems.

Do not add space before or after =

-DgroupId= com.company.module //Wrong , Watch the space after the equal to 
-DgroupId=com.company.module //Right 

Its better to put everything inside double quotes, like "-DgroupId=com.." This will give you exact error rather than some random error.

Weird that , maven does not even care to mention this in the documentation.

Android: Pass data(extras) to a fragment

Two things. First I don't think you are adding the data that you want to pass to the fragment correctly. What you need to pass to the fragment is a bundle, not an intent. For example if I wanted send an int value to a fragment I would create a bundle, put the int into that bundle, and then set that bundle as an argument to be used when the fragment was created.

Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

Second to retrieve that information you need to get the arguments sent to the fragment. You then extract the value based on the key you identified it with. For example in your fragment:

Bundle bundle = this.getArguments();
if (bundle != null) {
    int i = bundle.getInt(key, defaulValue);
}

What you are getting changes depending on what you put. Also the default value is usually null but does not need to be. It depends on if you set a default value for that argument.

Lastly I do not think you can do this in onCreateView. I think you must retrieve this data within your fragment's onActivityCreated method. My reasoning is as follows. onActivityCreated runs after the underlying activity has finished its own onCreate method. If you are placing the information you wish to retrieve within the bundle durring your activity's onCreate method, it will not exist during your fragment's onCreateView. Try using this in onActivityCreated and just update your ListView contents later.

TypeError: unsupported operand type(s) for -: 'str' and 'int'

For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str to int) so you must do this yourself. You'll like that in the long-run, trust me!

How to Publish Web with msbuild?

I don't know TeamCity so I hope this can work for you.

The best way I've found to do this is with MSDeploy.exe. This is part of the WebDeploy project run by Microsoft. You can download the bits here.

With WebDeploy, you run the command line

msdeploy.exe -verb:sync -source:contentPath=c:\webApp -dest:contentPath=c:\DeployedWebApp

This does the same thing as the VS Publish command, copying only the necessary bits to the deployment folder.

Ruby function to remove all white spaces?

I was trying to do this as I wanted to use a records "title" as an id in the view but the titles had spaces.

a solution is:

record.value.delete(' ') # Foo Bar -> FooBar

REST response code for invalid data

If the request could not be correctly parsed (including the request entity/body) the appropriate response is 400 Bad Request [1].

RFC 4918 states that 422 Unprocessable Entity is applicable when the request entity is syntactically well-formed, but semantically erroneous. So if the request entity is garbled (like a bad email format) use 400; but if it just doesn't make sense (like @example.com) use 422.

If the issue is that, as stated in the question, user name/email already exists, you could use 409 Conflict [2] with a description of the conflict, and a hint about how to fix it (in this case, "pick a different user name/email"). However in the spec as written, 403 Forbidden [3] can also be used in this case, arguments about HTTP Authorization notwithstanding.

412 Precondition Failed [4] is used when a precondition request header (e.g. If-Match) that was supplied by the client evaluates to false. That is, the client requested something and supplied preconditions, knowing full well that those preconditions might fail. 412 should never be sprung on the client out of the blue, and shouldn't be related to the request entity per se.

How to "perfectly" override a dict?

After trying out both of the top two suggestions, I've settled on a shady-looking middle route for Python 2.7. Maybe 3 is saner, but for me:

class MyDict(MutableMapping):
   # ... the few __methods__ that mutablemapping requires
   # and then this monstrosity
   @property
   def __class__(self):
       return dict

which I really hate, but seems to fit my needs, which are:

  • can override **my_dict
    • if you inherit from dict, this bypasses your code. try it out.
    • this makes #2 unacceptable for me at all times, as this is quite common in python code
  • masquerades as isinstance(my_dict, dict)
    • rules out MutableMapping alone, so #1 is not enough
    • I heartily recommend #1 if you don't need this, it's simple and predictable
  • fully controllable behavior
    • so I cannot inherit from dict

If you need to tell yourself apart from others, personally I use something like this (though I'd recommend better names):

def __am_i_me(self):
  return True

@classmethod
def __is_it_me(cls, other):
  try:
    return other.__am_i_me()
  except Exception:
    return False

As long as you only need to recognize yourself internally, this way it's harder to accidentally call __am_i_me due to python's name-munging (this is renamed to _MyDict__am_i_me from anything calling outside this class). Slightly more private than _methods, both in practice and culturally.

So far I have no complaints, aside from the seriously-shady-looking __class__ override. I'd be thrilled to hear of any problems that others encounter with this though, I don't fully understand the consequences. But so far I've had no problems whatsoever, and this allowed me to migrate a lot of middling-quality code in lots of locations without needing any changes.


As evidence: https://repl.it/repls/TraumaticToughCockatoo

Basically: copy the current #2 option, add print 'method_name' lines to every method, and then try this and watch the output:

d = LowerDict()  # prints "init", or whatever your print statement said
print '------'
splatted = dict(**d)  # note that there are no prints here

You'll see similar behavior for other scenarios. Say your fake-dict is a wrapper around some other datatype, so there's no reasonable way to store the data in the backing-dict; **your_dict will be empty, regardless of what every other method does.

This works correctly for MutableMapping, but as soon as you inherit from dict it becomes uncontrollable.


Edit: as an update, this has been running without a single issue for almost two years now, on several hundred thousand (eh, might be a couple million) lines of complicated, legacy-ridden python. So I'm pretty happy with it :)

Edit 2: apparently I mis-copied this or something long ago. @classmethod __class__ does not work for isinstance checks - @property __class__ does: https://repl.it/repls/UnitedScientificSequence

Remove quotes from String in Python

There are several ways this can be accomplished.

  • You can make use of the builtin string function .replace() to replace all occurrences of quotes in a given string:

    >>> s = '"abcd" efgh'
    >>> s.replace('"', '')
    'abcd efgh'
    >>> 
    
  • You can use the string function .join() and a generator expression to remove all quotes from a given string:

    >>> s = '"abcd" efgh'
    >>> ''.join(c for c in s if c not in '"')
    'abcd efgh'
    >>> 
    
  • You can use a regular expression to remove all quotes from given string. This has the added advantage of letting you have control over when and where a quote should be deleted:

    >>> s = '"abcd" efgh'
    >>> import re
    >>> re.sub('"', '', s)
    'abcd efgh'
    >>> 
    

Div with horizontal scrolling only

For horizontal scroll, keep these two properties in mind:

overflow-x:scroll;
white-space: nowrap;

See working link : click me

HTML

<p>overflow:scroll</p>
<div class="scroll">You can use the overflow property when you want to have better   control of the layout. The default value is visible.You can use the overflow property when you want     to have better control of the layout. The default value is visible.</div>

CSS

div.scroll
{
background-color:#00FFFF;
height:40px;
overflow-x:scroll;
white-space: nowrap;
}

Controlling a USB power supply (on/off) with Linux

The reason why folks post questions such as this is due to the dreaded- indeed "EVIL"- USB Auto-Suspend "feature".

Auto suspend winds-down the power to an "idle" USB device and unless the device's driver supports this feature correctly, the device can become uncontactable. So powering a USB port on/off is a symptom of the problem, not the problem in itself.

I'll show you how to GLOBALLY disable auto-suspend, negating the need to manually toggle the USB ports on & off:

Short Answer:

You do NOT need to edit "autosuspend_delay_ms" individually: USB autosuspend can be disabled globally and PERSISTENTLY using the following commands:

sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="/&usbcore.autosuspend=-1 /' /etc/default/grub

update-grub

systemctl reboot

An Ubuntu 18.04 screen-grab follows at the end of the "Long Answer" illustrating how my results were achieved.

Long Answer:

It's true that the USB Power Management Kernel Documentation states autosuspend is to be deprecated and in in its' place "autosuspend_delay_ms" used to disable USB autosuspend:

"In 2.6.38 the "autosuspend" file will be deprecated
and replaced by the "autosuspend_delay_ms" file."

HOWEVER my testing reveals that setting usbcore.autosuspend=-1 in /etc/default/grub as below can be used as a GLOBAL toggle for USB autosuspend functionality- you do NOT need to edit individual "autosuspend_delay_ms" files.

The same document linked above states a value of "0" is ENABLED and a negative value is DISABLED:

power/autosuspend_delay_ms

    <snip> 0 means to autosuspend
    as soon as the device becomes idle, and negative
    values mean never to autosuspend.  You can write a
    number to the file to change the autosuspend
    idle-delay time.

In the annotated Ubuntu 18.04 screen-grab below illustrating how my results were achieved (and reproducible), please remark the default is "0" (enabled) in autosuspend_delay_ms.

Then note that after ONLY setting usbcore.autosuspend=-1 in Grub, these values are now negative (disabled) after reboot. This will save me the bother of editing individual values and can now script disabling USB autosuspend.

screengrab: autosuspend values Before and after globally editing

Hope this makes disabling USB autosuspend a little easier and more scriptable-

How to abort a Task like aborting a Thread (Thread.Abort method)?

While it's possible to abort a thread, in practice it's almost always a very bad idea to do so. Aborthing a thread means the thread is not given a chance to clean up after itself, leaving resources undeleted, and things in unknown states.

In practice, if you abort a thread, you should only do so in conjunction with killing the process. Sadly, all too many people think ThreadAbort is a viable way of stopping something and continuing on, it's not.

Since Tasks run as threads, you can call ThreadAbort on them, but as with generic threads you almost never want to do this, except as a last resort.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

An easy solution to overcome this problem is to set your default encoding to utf8. Follow is an example

import sys

reload(sys)
sys.setdefaultencoding('utf8')

Bubble Sort Homework

def bubblesort(array):
    for i in range(len(array)-1):
        for j in range(len(array)-1-i):
            if array[j] > array[j+1]:
                array[j], array[j+1] = array[j+1], array[j]
    return(array)

print(bubblesort([3,1,6,2,5,4]))

What parameters should I use in a Google Maps URL to go to a lat-lon?

This should help with the new Google Maps:

http://maps.google.com/maps/place/<name>/@<lat>,<long>,15z/data=<mode-value>
  • The 'place' adds a marker.
  • 'name' could be a search term like "realtors"/"lawyers".
  • lat and long are the coordinates in decimal format and in that order.
  • 15z sets zoom level to 15 (between 1 ~ 20).
  • You can enforce a particular view mode (map is default) - earth or terrain by adding these: Terrain: /data=!5m1!1e4
    Earth: /data=!3m1!1e3

E.g.: https://www.google.com/maps/place/Lawyer/@48.8187768,2.3792362,15z/data=!3m1!1e3

References:
https://moz.com/blog/new-google-maps-url-parameters http://dddavemaps.blogspot.in/2015/07/google-maps-url-tricks.html

Another git process seems to be running in this repository

It is similar to above methods but in my case I had several of those

.git/refs/heads/<branch_name>.lock

and was able to remove all at once by this way

find -name "*.lock" -exec xargs rm {} \;

How do you make Vim unhighlight what you searched for?

            *:noh* *:nohlsearch*
:noh[lsearch]       Stop the highlighting for the 'hlsearch' option.  It
            is automatically turned back on when using a search
            command, or setting the 'hlsearch' option.
            This command doesn't work in an autocommand, because
            the highlighting state is saved and restored when
            executing autocommands |autocmd-searchpat|.
            Same thing for when invoking a user function.

I found it just under :help #, which I keep hitting all the time, and which highlights all the words on the current page like the current one.

How can I parse a YAML file from a Linux shell script?

Whenever you need a solution for "How to work with YAML/JSON/compatible data from a shell script" which works on just about every OS with Python (*nix, OSX, Windows), consider yamlpath, which provides several command-line tools for reading, writing, searching, and merging YAML, EYAML, JSON, and compatible files. Since just about every OS either comes with Python pre-installed or it is trivial to install, this makes yamlpath highly portable. Even more interesting: this project defines an intuitive path language with very powerful, command-line-friendly syntax that enables accessing one or more nodes.

To your specific question and after installing yamlpath using Python's native package manager or your OS's package manager (yamlpath is available via RPM to some OSes):

#!/bin/bash
# Read values directly from YAML (or EYAML, JSON, etc) for use in this shell script:
myShellVar=$(yaml-get --query=any.path.no[matter%how].complex source-file.yaml)

# Use the value any way you need:
echo "Retrieved ${myShellVar}"

# Perhaps change the value and write it back:
myShellVar="New Value"
yaml-set --change=/any/path/no[matter%how]/complex --value="$myShellVar" source-file.yaml

You didn't specify that the data was a simple Scalar value though, so let's up the ante. What if the result you want is an Array? Even more challenging, what if it's an Array-of-Hashes and you only want one property of each result? Suppose further that your data is actually spread out across multiple YAML files and you need all the results in a single query. That's a much more interesting question to demonstrate with. So, suppose you have these two YAML files:

File: data1.yaml

---
baubles:
  - name: Doohickey
    sku: 0-000-1
    price: 4.75
    weight: 2.7g
  - name: Doodad
    sku: 0-000-2
    price: 10.5
    weight: 5g
  - name: Oddball
    sku: 0-000-3
    price: 25.99
    weight: 25kg

File: data2.yaml

---
baubles:
  - name: Fob
    sku: 0-000-4
    price: 0.99
    weight: 18mg
  - name: Doohickey
    price: 10.5
  - name: Oddball
    sku: 0-000-3
    description: This ball is odd

How would you report only the sku of every item in inventory after applying the changes from data2.yaml to data1.yaml, all from a shell script? Try this:

#!/bin/bash
baubleSKUs=($(yaml-merge --aoh=deep data1.yaml data2.yaml | yaml-get --query=/baubles/sku -))

for sku in "${baubleSKUs[@]}"; do
    echo "Found bauble SKU:  ${sku}"
done

You get exactly what you need from only a few lines of code:

Found bauble SKU:  0-000-1
Found bauble SKU:  0-000-2
Found bauble SKU:  0-000-3
Found bauble SKU:  0-000-4

As you can see, yamlpath turns very complex problems into trivial solutions. Note that the entire query was handled as a stream; no YAML files were changed by the query and there were no temp files.

I realize this is "yet another tool to solve the same question" but after reading the other answers here, yamlpath appears more portable and robust than most alternatives. It also fully understands YAML/JSON/compatible files and it does not need to convert YAML to JSON to perform requested operations. As such, comments within the original YAML file are preserved whenever you need to change data in the source YAML file. Like some alternatives, yamlpath is also portable across OSes. More importantly, yamlpath defines a query language that is extremely powerful, enabling very specialized/filtered data queries. It can even operate against results from disparate parts of the file in a single query.

If you want to get or set many values in the data at once -- including complex data like hashes/arrays/maps/lists -- yamlpath can do that. Want a value but don't know precisely where it is in the document? yamlpath can find it and give you the exact path(s). Need to merge multiple data file together, including from STDIN? yamlpath does that, too. Further, yamlpath fully comprehends YAML anchors and their aliases, always giving or changing exactly the data you expect whether it is a concrete or referenced value.

Disclaimer: I wrote and maintain yamlpath, which is based on ruamel.yaml, which is in turn based on PyYAML. As such, yamlpath is fully standards-compliant.

Use of exit() function

Write header file #include<process.h> and replace exit(); with exit(0);. This will definitely work in Turbo C; for other compilers I don't know.

How to properly make a http web GET request

Adding to the responses already given, this is a complete example hitting JSON PlaceHolder site.

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Publish
{
    class Program
    {
        static async Task Main(string[] args)
        {
            
            // Get Reqeust
            HttpClient req = new HttpClient();
            var content = await req.GetAsync("https://jsonplaceholder.typicode.com/users");
            Console.WriteLine(await content.Content.ReadAsStringAsync());

            // Post Request
            Post p = new Post("Some title", "Some body", "1");
            HttpContent payload = new StringContent(JsonConvert.SerializeObject(p));
            content = await req.PostAsync("https://jsonplaceholder.typicode.com/posts", payload);
            Console.WriteLine("--------------------------");
            Console.WriteLine(content.StatusCode);
            Console.WriteLine(await content.Content.ReadAsStringAsync());
        }
    }

    public struct Post {
        public string Title {get; set;}
        public string Body {get;set;}
        public string UserID {get; set;}

        public Post(string Title, string Body, string UserID){
            this.Title = Title;
            this.Body = Body;
            this.UserID = UserID;
        }
    }
}

C++ Get name of type in template

Jesse Beder's solution is likely the best, but if you don't like the names typeid gives you (I think gcc gives you mangled names for instance), you can do something like:

template<typename T>
struct TypeParseTraits;

#define REGISTER_PARSE_TYPE(X) template <> struct TypeParseTraits<X> \
    { static const char* name; } ; const char* TypeParseTraits<X>::name = #X


REGISTER_PARSE_TYPE(int);
REGISTER_PARSE_TYPE(double);
REGISTER_PARSE_TYPE(FooClass);
// etc...

And then use it like

throw ParseError(TypeParseTraits<T>::name);

EDIT:

You could also combine the two, change name to be a function that by default calls typeid(T).name() and then only specialize for those cases where that's not acceptable.

Tick symbol in HTML/XHTML

The client machine needs a proper font that has a glyph for this character to display it. But Times New Roman doesn’t. Try Arial Unicode MS or Lucida Grande instead:

<span style="font-family: Arial Unicode MS, Lucida Grande">
    &#10003; &#10004;
</span>

This works for me on Windows XP in IE 5.5, IE 6.0, FF 3.0.6.

How to hide UINavigationBar 1px bottom line

In Swift 3.0

Edit your AppDelegate.swift by adding the following code to your application function:

// Override point for customization after application launch.

// Remove border in navigationBar
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)

What's the difference between unit tests and integration tests?

Unit test is usually done for a single functionality implemented in Software module. The scope of testing is entirely within this SW module. Unit test never fulfils the final functional requirements. It comes under whitebox testing methodology..

Whereas Integration test is done to ensure the different SW module implementations. Testing is usually carried out after module level integration is done in SW development.. This test will cover the functional requirements but not enough to ensure system validation.

How to make the web page height to fit screen height

As another guy described here, all you need to do is add

height: 100vh;

to the style of whatever you need to fill the screen

How to make a script wait for a pressed key?

os.system seems to always invoke sh, which does not recognize the s and n options for read. However the read command can be passed to bash:

 os.system("""bash -c 'read -s -n 1 -p "Press any key to continue..."'""")

Adding space/padding to a UILabel

Swift 3, iOS10 solution:

open class UIInsetLabel: UILabel {

    open var insets : UIEdgeInsets = UIEdgeInsets() {
        didSet {
            super.invalidateIntrinsicContentSize()
        }
    }

    open override var intrinsicContentSize: CGSize {
        var size = super.intrinsicContentSize
        size.width += insets.left + insets.right
        size.height += insets.top + insets.bottom
        return size
    }

    override open func drawText(in rect: CGRect) {
        return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
    }
}

How to printf long long

    // acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2 
    double pi = 2 * acos(0.0);
    int n; // upto 6 digit
    scanf("%d",&n); //precision with which you want the value of pi
    printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision

How can I maintain fragment state when added to the back stack?

I would suggest a very simple solution.

Take the View reference variable and set view in OnCreateView. Check if view already exists in this variable, then return same view.

   private View fragmentView;

   public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        if (fragmentView != null) {
            return fragmentView;
        }
        View view = inflater.inflate(R.layout.yourfragment, container, false);
        fragmentView = view;
        return view;
    }

Apache HttpClient Interim Error: NoHttpResponseException

Accepted answer is right but lacks solution. To avoid this error, you can add setHttpRequestRetryHandler (or setRetryHandler for apache components 4.4) for your HTTP client like in this answer.

How to assign an exec result to a sql variable?

Here is solution for dynamic queries.

For example if you have more tables with different suffix:

dbo.SOMETHINGTABLE_ONE, dbo.SOMETHINGTABLE_TWO

Code:

DECLARE @INDEX AS NVARCHAR(20)
DECLARE @CheckVALUE AS NVARCHAR(max) = 'SELECT COUNT(SOMETHING) FROM 
dbo.SOMETHINGTABLE_'+@INDEX+''
DECLARE @tempTable Table (TempVALUE int)
DECLARE @RESULTVAL INT

INSERT INTO @tempTable
    EXEC sp_executesql @CheckVALUE

SET @RESULTVAL = (SELECT * FROM @tempTable)

DELETE @tempTable

SELECT @RESULTVAL 

How to style UITextview to like Rounded Rect text field?

Edit: You have to import

#import <QuartzCore/QuartzCore.h>

for using corner radius.

Try this it will work for sure

UITextView* txtView = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 300, 100)];
txtView.layer.cornerRadius = 5.0;
txtView.clipsToBounds = YES;

As Rob figured it out setting the if you want the border color to be similar as UITextField then you need to change the border width to 2.0 and color to gray by adding the following line

[textView.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]]; 
[textView.layer setBorderWidth:2.0];

How can I solve equations in Python?

Python may be good, but it isn't God...

There are a few different ways to solve equations. SymPy has already been mentioned, if you're looking for analytic solutions.

If you're happy to just have a numerical solution, Numpy has a few routines that can help. If you're just interested in solutions to polynomials, numpy.roots will work. Specifically for the case you mentioned:

>>> import numpy
>>> numpy.roots([2,-6])
array([3.0])

For more complicated expressions, have a look at scipy.fsolve.

Either way, you can't escape using a library.

How to fix corrupted git repository?

This command worked for me:

$ git reset --mixed 

How to set max and min value for Y axis

_x000D_
_x000D_
var config = {_x000D_
            type: 'line',_x000D_
            data: {_x000D_
                labels: ["January", "February", "March", "April", "May", "June", "July"],_x000D_
                datasets: [{_x000D_
                        label: "My First dataset",_x000D_
                        data: [10, 80, 56, 60, 6, 45, 15],_x000D_
                        fill: false,_x000D_
                        backgroundColor: "#eebcde ",_x000D_
                        borderColor: "#eebcde",_x000D_
                        borderCapStyle: 'butt',_x000D_
                        borderDash: [5, 5],_x000D_
                    }]_x000D_
            },_x000D_
            options: {_x000D_
                responsive: true,_x000D_
                legend: {_x000D_
                    position: 'bottom',_x000D_
                },_x000D_
                hover: {_x000D_
                    mode: 'label'_x000D_
                },_x000D_
                scales: {_x000D_
                    xAxes: [{_x000D_
                            display: true,_x000D_
                            scaleLabel: {_x000D_
                                display: true,_x000D_
                                labelString: 'Month'_x000D_
                            }_x000D_
                        }],_x000D_
                    yAxes: [{_x000D_
                            display: true,_x000D_
                            ticks: {_x000D_
                                beginAtZero: true,_x000D_
                                steps: 10,_x000D_
                                stepValue: 5,_x000D_
                                max: 100_x000D_
                            }_x000D_
                        }]_x000D_
                },_x000D_
                title: {_x000D_
                    display: true,_x000D_
                    text: 'Chart.js Line Chart - Legend'_x000D_
                }_x000D_
            }_x000D_
        };_x000D_
_x000D_
        var ctx = document.getElementById("canvas").getContext("2d");_x000D_
       new Chart(ctx, config);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.1/Chart.bundle.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body>_x000D_
  <canvas id="canvas"></canvas>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Maven:Non-resolvable parent POM and 'parent.relativePath' points at wrong local POM

So In my case, After trying all the above options, I realized it was VPN (company firewall).once connected and ran cmd: clean install spring-boot:run. Issue is resolved. Step 1: check maven is configured correctly or not. Step 2: check settings.xml is mapped correctly or not. Step 3: verify if you are behind any firewall then map your repo urls accordingly. Step 4:run clean install spring-boot:run step 5: issue is resolved.

BAT file to open CMD in current directory

Create a new file startCmdLine.bat in your directory and put this line in it

call cmd

That is it. Now double click on the .bat file. It works for me.

You can replace call with start, it will also work.