Programs & Examples On #Variable names

A table name as a variable

Declare @fs_e int, @C_Tables CURSOR, @Table varchar(50)

SET @C_Tables = CURSOR FOR
        select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN @C_Tables
FETCH @C_Tables INTO @Table
    SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'

WHILE ( @fs_e <> -1)
    BEGIN
        exec('Select * from ' + @Table)
        FETCH @C_Tables INTO @Table
        SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'
    END

What is default color for text in textview?

Actually the color TextView is:

android:textColor="@android:color/tab_indicator_text"

or

#808080

IOS - How to segue programmatically using swift

You can do this thing using performSegueWithIdentifier function.

Screenshot

Syntax :

func performSegueWithIdentifier(identifier: String, sender: AnyObject?)

Example :

 performSegueWithIdentifier("homeScreenVC", sender: nil)

yii2 hidden input value

You can use this code line in view(form)

 <?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'your_value'])->label(false) ?>

Please refere this as example

If your need to pass currant date and time as hidden input : Model attribute is 'created_on' and its value is retrieve from date('Y-m-d H:i:s') , just like:"2020-03-10 09:00:00"

  <?= $form->field($model, 'created_on')->hiddenInput(['value'=>date('Y-m-d H:i:s')])->label(false) ?>

A button to start php script, how?

Having 2 files like you suggested would be the easiest solution.

For instance:

2 files solution:

index.html

(.. your html ..)
<form action="script.php" method="get">
  <input type="submit" value="Run me now!">
</form>
(...)

script.php

<?php
  echo "Hello world!"; // Your code here
?>

Single file solution:

index.php

<?php
  if (!empty($_GET['act'])) {
    echo "Hello world!"; //Your code here
  } else {
?>
(.. your html ..)
<form action="index.php" method="get">
  <input type="hidden" name="act" value="run">
  <input type="submit" value="Run me now!">
</form>
<?php
  }
?>

ADB error: cannot connect to daemon

I had this problem on my ubuntu. I just ran adb from sdk/platform-tools instead of pre-installed version on my system and it worked fine.

What is the difference between "::" "." and "->" in c++

1.-> for accessing object member variables and methods via pointer to object

Foo *foo = new Foo();
foo->member_var = 10;
foo->member_func();

2.. for accessing object member variables and methods via object instance

Foo foo;
foo.member_var = 10;
foo.member_func();

3.:: for accessing static variables and methods of a class/struct or namespace. It can also be used to access variables and functions from another scope (actually class, struct, namespace are scopes in that case)

int some_val = Foo::static_var;
Foo::static_method();
int max_int = std::numeric_limits<int>::max();

How to remove duplicate values from an array in PHP

<?php
$a=array("1"=>"302","2"=>"302","3"=>"276","4"=>"301","5"=>"302");
print_r(array_values(array_unique($a)));
?>//`output -> Array ( [0] => 302 [1] => 276 [2] => 301 )`

removing html element styles via javascript

Completly removing style, not only set to NULL

document.getElementById("id").removeAttribute("style")

How to load external webpage in WebView

Add below method in your activity class.Here browser is nothing but your webview object.

Now you can view web contain page wise easily.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && browser.canGoBack()) {
        browser.goBack();
        return true;
    }
    return false;
}

Use latest version of Internet Explorer in the webbrowser control

I saw Veer's answer. I think it's right, but it did not I work for me. Maybe I am using .NET 4 and am using 64x OS so kindly check this.

You may put in setup or check it in start-up of your application:

private void Form1_Load(object sender, EventArgs e)
{
    var appName = Process.GetCurrentProcess().ProcessName + ".exe";
    SetIE8KeyforWebBrowserControl(appName);
}

private void SetIE8KeyforWebBrowserControl(string appName)
{
    RegistryKey Regkey = null;
    try
    {
        // For 64 bit machine
        if (Environment.Is64BitOperatingSystem)
            Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Wow6432Node\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
        else  //For 32 bit machine
            Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);

        // If the path is not correct or
        // if the user haven't priviledges to access the registry
        if (Regkey == null)
        {
            MessageBox.Show("Application Settings Failed - Address Not found");
            return;
        }

        string FindAppkey = Convert.ToString(Regkey.GetValue(appName));

        // Check if key is already present
        if (FindAppkey == "8000")
        {
            MessageBox.Show("Required Application Settings Present");
            Regkey.Close();
            return;
        }

        // If a key is not present add the key, Key value 8000 (decimal)
        if (string.IsNullOrEmpty(FindAppkey))
            Regkey.SetValue(appName, unchecked((int)0x1F40), RegistryValueKind.DWord);

        // Check for the key after adding
        FindAppkey = Convert.ToString(Regkey.GetValue(appName));

        if (FindAppkey == "8000")
            MessageBox.Show("Application Settings Applied Successfully");
        else
            MessageBox.Show("Application Settings Failed, Ref: " + FindAppkey);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Application Settings Failed");
        MessageBox.Show(ex.Message);
    }
    finally
    {
        // Close the Registry
        if (Regkey != null)
            Regkey.Close();
    }
}

You may find messagebox.show, just for testing.

Keys are as the following:

  • 11001 (0x2AF9) - Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the !DOCTYPE directive.

  • 11000 (0x2AF8) - Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11.

  • 10001 (0x2711)- Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.

  • 10000 (0x2710)- Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.

  • 9999 (0x270F) - Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.

  • 9000 (0x2328) - Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.

  • 8888 (0x22B8) - Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.

  • 8000 (0x1F40) - Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.

  • 7000 (0x1B58) - Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.

Reference: MSDN: Internet Feature Controls

I saw applications like Skype use 10001. I do not know.

NOTE

The setup application will change the registry. You may need to add a line in the Manifest File to avoid errors due to permissions of change in registry:

<requestedExecutionLevel level="highestAvailable" uiAccess="false" />

UPDATE 1

This is a class will get the latest version of IE on windows and make changes as should be;

public class WebBrowserHelper
{


    public static int GetEmbVersion()
    {
        int ieVer = GetBrowserVersion();

        if (ieVer > 9)
            return ieVer * 1000 + 1;

        if (ieVer > 7)
            return ieVer * 1111;

        return 7000;
    } // End Function GetEmbVersion

    public static void FixBrowserVersion()
    {
        string appName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().Location);
        FixBrowserVersion(appName);
    }

    public static void FixBrowserVersion(string appName)
    {
        FixBrowserVersion(appName, GetEmbVersion());
    } // End Sub FixBrowserVersion

    // FixBrowserVersion("<YourAppName>", 9000);
    public static void FixBrowserVersion(string appName, int ieVer)
    {
        FixBrowserVersion_Internal("HKEY_LOCAL_MACHINE", appName + ".exe", ieVer);
        FixBrowserVersion_Internal("HKEY_CURRENT_USER", appName + ".exe", ieVer);
        FixBrowserVersion_Internal("HKEY_LOCAL_MACHINE", appName + ".vshost.exe", ieVer);
        FixBrowserVersion_Internal("HKEY_CURRENT_USER", appName + ".vshost.exe", ieVer);
    } // End Sub FixBrowserVersion 

    private static void FixBrowserVersion_Internal(string root, string appName, int ieVer)
    {
        try
        {
            //For 64 bit Machine 
            if (Environment.Is64BitOperatingSystem)
                Microsoft.Win32.Registry.SetValue(root + @"\Software\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", appName, ieVer);
            else  //For 32 bit Machine 
                Microsoft.Win32.Registry.SetValue(root + @"\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", appName, ieVer);


        }
        catch (Exception)
        {
            // some config will hit access rights exceptions
            // this is why we try with both LOCAL_MACHINE and CURRENT_USER
        }
    } // End Sub FixBrowserVersion_Internal 

    public static int GetBrowserVersion()
    {
        // string strKeyPath = @"HKLM\SOFTWARE\Microsoft\Internet Explorer";
        string strKeyPath = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer";
        string[] ls = new string[] { "svcVersion", "svcUpdateVersion", "Version", "W2kVersion" };

        int maxVer = 0;
        for (int i = 0; i < ls.Length; ++i)
        {
            object objVal = Microsoft.Win32.Registry.GetValue(strKeyPath, ls[i], "0");
            string strVal = System.Convert.ToString(objVal);
            if (strVal != null)
            {
                int iPos = strVal.IndexOf('.');
                if (iPos > 0)
                    strVal = strVal.Substring(0, iPos);

                int res = 0;
                if (int.TryParse(strVal, out res))
                    maxVer = Math.Max(maxVer, res);
            } // End if (strVal != null)

        } // Next i

        return maxVer;
    } // End Function GetBrowserVersion 


}

using of class as followed

WebBrowserHelper.FixBrowserVersion();
WebBrowserHelper.FixBrowserVersion("SomeAppName");
WebBrowserHelper.FixBrowserVersion("SomeAppName",intIeVer);

you may face a problem for in comparability of windows 10, may due to your website itself you may need to add this meta tag

<meta http-equiv="X-UA-Compatible" content="IE=11" >

Enjoy :)

Crontab Day of the Week syntax

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

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

Examples of Number or Abbreviation Use

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

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

In Detail

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

How to view the stored procedure code in SQL Server Management Studio

I guess this is a better way to view a stored procedure's code:

sp_helptext <name of your sp>

Rename file with Git

I had a similar problem going through a tutorial.

# git mv README README.markdown

fatal: bad source, source=README, destination=README.markdown

I included the filetype in the source file:

# git mv README.rdoc README.markdown

and it worked perfectly. Don't forget to commit the changes with i.e.:

# git commit -a -m "Improved the README"

Sometimes it is simple little things like that, that piss us off. LOL

Java : Accessing a class within a package, which is the better way?

As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang package is automatically imported, as is everything in the current package.

The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.

By the way, if you are using lots of static methods (from Math, for example), you could also write

import static java.lang.Math.*;

and then use

sqrt(x)

directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)

npm install error - unable to get local issuer certificate

In case you use yarn:

yarn config set strict-ssl false

Notepad++ Regular expression find and delete a line

Provide the following in the search dialog:

Find What: ^$\r\n
Replace With: (Leave it empty)

Click Replace All

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

How to select clear table contents without destroying the table?

I use this code to remove my data but leave the formulas in the top row. It also removes all rows except for the top row and scrolls the page up to the top.

Sub CleanTheTable()
    Application.ScreenUpdating = False
    Sheets("Data").Select
    ActiveSheet.ListObjects("TestTable").HeaderRowRange.Select
    'Remove the filters if one exists.
    If ActiveSheet.FilterMode Then
    Selection.AutoFilter
    End If
    'Clear all lines but the first one in the table leaving formulas for the next go round.
    With Worksheets("Data").ListObjects("TestTable")
    .Range.AutoFilter
    On Error Resume Next
    .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
    .DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
    ActiveWindow.SmallScroll Down:=-10000

    End With
Application.ScreenUpdating = True
End Sub

How I can print to stderr in C?

#include<stdio.h>

int main ( ) {
    printf( "hello " );
    fprintf( stderr, "HELP!" );
    printf( " world\n" );
    return 0;
}

$ ./a.exe
HELP!hello  world
$ ./a.exe 2> tmp1
hello  world
$ ./a.exe 1> tmp1
HELP!$
  1. stderr is usually unbuffered and stdout usually is. This can lead to odd looking output like this, which suggests code is executing in the wrong order. It isn't, it's just that the stdout buffer has yet to be flushed. Redirected or piped streams would of course not see this interleave as they would normally only see the output of stdout only or stderr only.

  2. Although initially both stdout and stderr come to the console, both are separate and can be individually redirected.

How to create a drop shadow only on one side of an element?

You could also use clip-path to clip (hide) all overflowing edges but the one you want to show:

.shadow {
  box-shadow: 0 4px 4px black;
  clip-path: polygon(0 0, 100% 0, 100% 200%, 0 200%);
}

See clip-path (MDN). The arguments to polygon are the top-left point, the top-right point, the bottom-right point, and the bottom-left point. By setting the bottom edge to 200% (or whatever number bigger than 100%) you constrain your overflow to only the bottom edge.

Examples:

example of boxes with top right bottom and left box-shadow isolated with clip-path

_x000D_
_x000D_
.shadow {
  box-shadow: 0 0 8px 5px rgba(200, 0, 0, 0.5);
}
.shadow-top {
  clip-path: polygon(0% -20%, 100% -20%, 100% 100%, 0% 100%);
}
.shadow-right {
  clip-path: polygon(0% 0%, 120% 0%, 120% 100%, 0% 100%);
}
.shadow-bottom {
  clip-path: polygon(0% 0%, 100% 0%, 100% 120%, 0% 120%);
}
.shadow-left {
  clip-path: polygon(-20% 0%, 100% 0%, 100% 100%, -20% 100%);
}

.shadow-bottom-right {
  clip-path: polygon(0% 0%, 120% 0%, 120% 120%, 0% 120%);
}

/* layout for example */
.box {
  display: inline-block;
  vertical-align: top;
  background: #338484;
  color: #fff;
  width: 4em;
  height: 2em;
  margin: 1em;
  padding: 1em;
}
_x000D_
<div class="box">none</div>
<div class="box shadow shadow-all">all</div>
<div class="box shadow shadow-top">top</div>
<div class="box shadow shadow-right">right</div>
<div class="box shadow shadow-bottom">bottom</div>
<div class="box shadow shadow-left">left</div>
<div class="box shadow shadow-bottom-right">bottom right</div>
_x000D_
_x000D_
_x000D_

Rounding SQL DateTime to midnight

Try using this.

WHERE Orders.OrderStatus = 'Shipped'  
AND Orders.ShipDate >= CONVERT(DATE, GETDATE())

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

You can use myDict.has_key(keyname) as well to validate if the key exists.

Edit based on the comments -

This would work only on versions lower than 3.1. has_key has been removed from Python 3.1. You should use the in operator if you are using Python 3.1

How do you validate a URL with a regular expression in Python?

note - Lepl is no longer maintained or supported.

RFC 3696 defines "best practices" for URL validation - http://www.faqs.org/rfcs/rfc3696.html

The latest release of Lepl (a Python parser library) includes an implementation of RFC 3696. You would use it something like:

from lepl.apps.rfc3696 import Email, HttpUrl

# compile the validators (do once at start of program)
valid_email = Email()
valid_http_url = HttpUrl()

# use the validators (as often as you like)
if valid_email(some_email):
    # email is ok
else:
    # email is bad
if valid_http_url(some_url):
    # url is ok
else:
    # url is bad

Although the validators are defined in Lepl, which is a recursive descent parser, they are largely compiled internally to regular expressions. That combines the best of both worlds - a (relatively) easy to read definition that can be checked against RFC 3696 and an efficient implementation. There's a post on my blog showing how this simplifies the parser - http://www.acooke.org/cute/LEPLOptimi0.html

Lepl is available at http://www.acooke.org/lepl and the RFC 3696 module is documented at http://www.acooke.org/lepl/rfc3696.html

This is completely new in this release, so may contain bugs. Please contact me if you have any problems and I will fix them ASAP. Thanks.

Failed to install *.apk on device 'emulator-5554': EOF

Run the next command:

adb kill-server
adb start-server

Is possible that drawn the next messages DeviceMonitor]Connection attempts: 1 DeviceMonitor]Connection attempts:2

How to subtract 30 days from the current date using SQL Server

TRY THIS:

Cast your VARCHAR value to DATETIME and add -30 for subtraction. Also, In sql-server the format Fri, 14 Nov 2014 23:03:35 GMT was not converted to DATETIME. Try substring for it:

SELECT DATEADD(dd, -30, 
       CAST(SUBSTRING ('Fri, 14 Nov 2014 23:03:35 GMT', 6, 21) 
       AS DATETIME))

"Repository does not have a release file" error

#For Unable to 'apt update' my Ubuntu 19.04

The repositories for older releases that are not supported (like 11.04, 11.10 and 13.04) get moved to an archive server. There are repositories available at http://old-releases.ubuntu.com.

first break up this file

cp /etc/apt/sources.list /etc/apt/sources.list.bak sudo sed -i -re 's/([a-z]{2}.)?archive.ubuntu.com|security.ubuntu.com/old-releases.ubuntu.com/g' /etc/apt/sources.list

then

sudo apt-get update && sudo apt-get dist-upgrade

Getting value of HTML text input

If you want to use the value of the email input somewhere else on the same page, for example to do some sort of validation, you could use JavaScript. First I would assign an "id" attribute to your email textbox:

<input type="text" name="email" id="email"/>

and then I would retrieve the value with JavaScript:

var email = document.getElementById('email').value;

From there, you can do additional processing on the value of 'email'.

How to pad a string to a fixed length with spaces in Python?

I know this is a bit of an old question, but I've ended up making my own little class for it.

Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:

class consolePrinter():
'''
Class to write to the console

Objective is to make it easy to write to console, with user able to 
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------    
#Class variables
stringLen = 0    
# -------------------------------------------------------------------------    
    
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteFlag=False):
    import sys
    #Get length of stringIn and update stringLen if needed
    if len(stringIn) > consolePrinter.stringLen:
        consolePrinter.stringLen = len(stringIn)+1
    
    ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
    if overwriteFlag:
        sys.stdout.write("\r" + ctrlString.format(stringIn))
    else:
        sys.stdout.write("\n" + stringIn)
    sys.stdout.flush()
    
    return

Which then is called via:

consolePrinter.writeline("text here", True) 

If you want to overwrite the previous line, or

consolePrinter.writeline("text here",False)

if you don't.

Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.

HTML/CSS: how to put text both right and left aligned in a paragraph

I have used this in the past:

html

January<span class="right">2014</span>

Css

.right {
    margin-left:100%;
}

Demonstration

"Prevent saving changes that require the table to be re-created" negative effects

Reference - Turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore,Microsoft recommend that you do not work around this problem by turning off the option.

Merging Cells in Excel using C#

take a list of string as like

List<string> colValListForValidation = new List<string>();

and match string before the task. it will help you bcz all merge cells will have same value

Could not autowire field in spring. why?

I had exactly the same problem try to put the two classes in the same package and add line in the pom.xml

<dependency> 
            <groupId> org.springframework.boot </groupId> 
            <artifactId> spring-boot-starter-web </artifactId> 
            <version> 1.2.0.RELEASE </version> 
</dependency>

counting number of directories in a specific directory

Using zsh:

a=(*(/N)); echo ${#a}

The N is a nullglob, / makes it match directories, # counts. It will neatly cope with spaces in directory names as well as returning 0 if there are no directories.

How do I start PowerShell from Windows Explorer?

One fairly simple alternative is to invoke PowerShell via a shortcut. There is a shortcut property labeled "Start in" that says what directory(folder) to use when the shortcut is invoked.

If the Start In box is blank, it means use the current directory.

When you first create a shortcut to PowerShell in the usual way, the start in box specifies the home directory. If you blank out the start in box, you now have a shortcut to powershell that opens PS in the current directory, whatever that is.

If you now copy this shortcut to the target directory, and use explorer to invoke it, you'll start a PS that's pointed at the target directory.

There's already an accepted answer to this question, but I offer this as another way.

Resolve absolute path from relative path and/or file name

Most of these answers seem crazy over complicated and super buggy, here's mine -- it works on any environment variable, no %CD% or PUSHD/POPD, or for /f nonsense -- just plain old batch functions. -- The directory & file don't even have to exist.

CALL :NORMALIZEPATH "..\..\..\foo\bar.txt"
SET BLAH=%RETVAL%

ECHO "%BLAH%"

:: ========== FUNCTIONS ==========
EXIT /B

:NORMALIZEPATH
  SET RETVAL=%~f1
  EXIT /B

Can anyone explain me StandardScaler?

The idea behind StandardScaler is that it will transform your data such that its distribution will have a mean value 0 and standard deviation of 1.
In case of multivariate data, this is done feature-wise (in other words independently for each column of the data).
Given the distribution of the data, each value in the dataset will have the mean value subtracted, and then divided by the standard deviation of the whole dataset (or feature in the multivariate case).

How to pause a vbscript execution?

With 'Enter' is better use ReadLine() or Read(2), because key 'Enter' generate 2 symbols. If user enter any text next Pause() also wil be skipped even with Read(2). So ReadLine() is better:

Sub Pause()
    WScript.Echo ("Press Enter to continue")
    z = WScript.StdIn.ReadLine()
End Sub

More examples look in http://technet.microsoft.com/en-us/library/ee156589.aspx

How to run a script at a certain time on Linux?

The at command exists specifically for this purpose (unlike cron which is intended for scheduling recurring tasks).

at $(cat file) </path/to/script

Exception thrown in catch and finally clause

To handle this kind of situation i.e. handling the exception raised by finally block. You can surround the finally block by try block: Look at the below example in python:

try:
   fh = open("testfile", "w")
   try:
      fh.write("This is my test file for exception handling!!")
   finally:
      print "Going to close the file"
      fh.close()
except IOError:
   print "Error: can\'t find file or read data"

Python - Check If Word Is In A String

Advanced way to check the exact word, that we need to find in a long string:

import re
text = "This text was of edited by Rock"
#try this string also
#text = "This text was officially edited by Rock" 
for m in re.finditer(r"\bof\b", text):
    if m.group(0):
        print "Present"
    else:
        print "Absent"

How to execute an oracle stored procedure?

Have you tried to correct the syntax like this?:

create or replace procedure temp_proc AS
begin
  DBMS_OUTPUT.PUT_LINE('Test');
end;

AsyncTask Android example

private class AsyncTaskDemo extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {

        // Do code here

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onCancelled() {

        super.onCancelled();
        progressDialog.dismiss();
        Toast toast = Toast.makeText(
                          getActivity(),
                          "An error is occurred due to some problem",
                          Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 25, 400);
        toast.show();
    }

}

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

how to count the spaces in a java string?

s.length() - s.replaceAll(" ", "").length() returns you number of spaces.

There are more ways. For example"

int spaceCount = 0;
for (char c : str.toCharArray()) {
    if (c == ' ') {
         spaceCount++;
    }
}

etc., etc.

In your case you tried to split string using \t - TAB. You will get right result if you use " " instead. Using \s may be confusing since it matches all whitepsaces - regular spaces and TABs.

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

As a supplement to the question and above answers there is also an important difference between plt.subplots() and plt.subplot(), notice the missing 's' at the end.

One can use plt.subplots() to make all their subplots at once and it returns the figure and axes (plural of axis) of the subplots as a tuple. A figure can be understood as a canvas where you paint your sketch.

# create a subplot with 2 rows and 1 columns
fig, ax = plt.subplots(2,1)

Whereas, you can use plt.subplot() if you want to add the subplots separately. It returns only the axis of one subplot.

fig = plt.figure() # create the canvas for plotting
ax1 = plt.subplot(2,1,1) 
# (2,1,1) indicates total number of rows, columns, and figure number respectively
ax2 = plt.subplot(2,1,2)

However, plt.subplots() is preferred because it gives you easier options to directly customize your whole figure

# for example, sharing x-axis, y-axis for all subplots can be specified at once
fig, ax = plt.subplots(2,2, sharex=True, sharey=True)

Shared axes whereas, with plt.subplot(), one will have to specify individually for each axis which can become cumbersome.

How can one develop iPhone apps in Java?

There is anew tool called Codename one: One SDK based on JAVA to code in WP8, Android, iOS with all extensive features

Features:

  1. Full Android environment with super fast android simulator
  2. An iPhone/iPad simulator with easy to take iPhone apps to large screen iPad in minutes.
  3. Full support for standard java debugging, profiling for apps on any platform.
  4. Easy themeing / styling – Only a click away

More at Develop Android, iOS iPhone, WP8 apps using Java

How does tuple comparison work in Python?

The Python documentation does explain it.

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

Having both a Created and Last Updated timestamp columns in MySQL 4.0

For mysql 5.7.21 I use the following and works fine:

CREATE TABLE Posts ( modified_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP )

Create a new txt file using VB.NET

open C:\myfile.txt for append as #1
write #1, text1.text, text2.text
close()

This is the code I use in Visual Basic 6.0. It helps me to create a txt file on my drive, write two pieces of data into it, and then close the file... Give it a try...

Why Java Calendar set(int year, int month, int date) not returning correct date?

Months in Calendar object start from 0

0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY

Regular expression include and exclude special characters

For the allowed characters you can use

^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$

to validate a complete string that should consist of only allowed characters. Note that - is at the end (because otherwise it'd be a range) and a few characters are escaped.

For the invalid characters you can use

[<>'"/;`%]

to check for them.

To combine both into a single regex you can use

^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%])

but you'd need a regex engine that allows lookahead.

How do I add a new class to an element dynamically?

:hover is a pseudoclass, so you can put your CSS declarations there:

a:hover {
    color: #f00;
}

You can also use a list of selectors to apply CSS declarations to a hovered element or an element with a certain class:

.some-class,
a:hover {
    color: #f00;
}

Get a timestamp in C in microseconds?

First we need to know on the range of microseconds i.e. 000_000 to 999_999 (1000000 microseconds is equal to 1second). tv.tv_usec will return value from 0 to 999999 not 000000 to 999999 so when using it with seconds we might get 2.1seconds instead of 2.000001 seconds because when only talking about tv_usec 000001 is essentially 1. Its better if you insert

if(tv.tv_usec<10)
{
 printf("00000");
} 
else if(tv.tv_usec<100&&tv.tv_usec>9)// i.e. 2digits
{
 printf("0000");
}

and so on...

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

If the activity created by yourself, you can try this in the Activity:

@Override
public void setRequestedOrientation(int requestedOrientation) {
    try {
        super.setRequestedOrientation(requestedOrientation);
    } catch (IllegalStateException e) {
        // Only fullscreen activities can request orientation
        e.printStackTrace();
    }
}

This should be the easiest solution.

How to get the Touch position in android?

Here is the Koltin style, I use this in my project and it works very well:

this.yourview.setOnTouchListener(View.OnTouchListener { _, event ->
        val x = event.x
        val y = event.y

        when(event.action) {
            MotionEvent.ACTION_DOWN -> {
                Log.d(TAG, "ACTION_DOWN \nx: $x\ny: $y")
            }
            MotionEvent.ACTION_MOVE -> {
                Log.d(TAG, "ACTION_MOVE \nx: $x\ny: $y")
            }
            MotionEvent.ACTION_UP -> {
                Log.d(TAG, "ACTION_UP \nx: $x\ny: $y")
            }
        }
        return@OnTouchListener  true
    })

PHP Warning: Module already loaded in Unknown on line 0

To fix this problem, you must edit your php.ini (or extensions.ini) file and comment-out the extensions that are already compiled-in. For example, after editing, your ini file may look like the lines below:

;extension=pcre.so
;extension=spl.so

Source: http://www.somacon.com/p520.php

Can Python test the membership of multiple values in a list?

If you want to check all of your input matches,

>>> all(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])

if you want to check at least one match,

>>> any(x in ['b', 'a', 'foo', 'bar'] for x in ['a', 'b'])

How to execute a .sql script from bash

If you want to run a script to a database:

mysql -u user -p data_base_name_here < db.sql

SQL Server check case-sensitivity?

Collation can be set at various levels:

  1. Server
  2. Database
  3. Column

So you could have a Case Sensitive Column in a Case Insensitive database. I have not yet come across a situation where a business case could be made for case sensitivity of a single column of data, but I suppose there could be.

Check Server Collation

SELECT SERVERPROPERTY('COLLATION')

Check Database Collation

SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;

Check Column Collation

select table_name, column_name, collation_name
from INFORMATION_SCHEMA.COLUMNS
where table_name = @table_name

PowerShell: Comparing dates

I wanted to show how powerful it can be aside from just checking "-lt".

Example: I used it to calculate time differences take from Windows event view Application log:

Get the difference between the two date times:

PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))

Object created:

PS> $Obj


Days              : 0
Hours             : 0
Minutes           : 31
Seconds           : 0
Milliseconds      : 0
Ticks             : 18600000000
TotalDays         : 0.0215277777777778
TotalHours        : 0.516666666666667
TotalMinutes      : 31
TotalSeconds      : 1860
TotalMilliseconds : 1860000

Access an item directly:

PS> $Obj.Minutes
31

When to use pthread_exit() and when to use pthread_join() in Linux?

Hmm.

POSIX pthread_exit description from http://pubs.opengroup.org/onlinepubs/009604599/functions/pthread_exit.html:

After a thread has terminated, the result of access to local (auto) variables of the thread is 
undefined. Thus, references to local variables of the exiting thread should not be used for 
the pthread_exit() value_ptr parameter value.

Which seems contrary to the idea that local main() thread variables will remain accessible.

What is the best (idiomatic) way to check the type of a Python variable?

That should work - so no, there is nothing wrong with your code. However, it could also be done with a dict:

{type(str()): do_something_with_a_string,
 type(dict()): do_something_with_a_dict}.get(type(x), errorhandler)()

A bit more concise and pythonic wouldn't you say?


Edit.. Heeding Avisser's advice, the code also works like this, and looks nicer:

{str: do_something_with_a_string,
 dict: do_something_with_a_dict}.get(type(x), errorhandler)()

How to make JavaScript execute after page load?

Just define <body onload="aFunction()"> that will be called after the page has been loaded. Your code in the script is than enclosed by aFunction() { }.

Gunicorn worker timeout error

We had the same problem using Django+nginx+gunicorn. From Gunicorn documentation we have configured the graceful-timeout that made almost no difference.

After some testings, we found the solution, the parameter to configure is: timeout (And not graceful timeout). It works like a clock..

So, Do:

1) open the gunicorn configuration file

2) set the TIMEOUT to what ever you need - the value is in seconds

NUM_WORKERS=3
TIMEOUT=120

exec gunicorn ${DJANGO_WSGI_MODULE}:application \
--name $NAME \
--workers $NUM_WORKERS \
--timeout $TIMEOUT \
--log-level=debug \
--bind=127.0.0.1:9000 \
--pid=$PIDFILE

Pass arguments into C program from command line

Take a look at the getopt library; it's pretty much the gold standard for this sort of thing.

How to auto adjust the div size for all mobile / tablet display formats?

I don't have much time and your jsfidle did not work right now.
But maybe this will help you getting started.

First of all you should avoid to put css in your html tags. Like align="center".
Put stuff like that in your css since it is much clearer and won't deprecate that fast.

If you want to design responsive layouts you should use media queries wich were introduced in css3 and are supported very well by now.

Example css:

@media screen and (min-width: 100px) and (max-width: 199px)
{
    .button
    {
        width: 25px;
    }
}

@media screen and (min-width: 200px) and (max-width: 299px)
{
    .button
    {
        width: 50px;
    }
}

You can use any css you want inside a media query.
http://www.w3.org/TR/css3-mediaqueries/

How to Implement DOM Data Binding in JavaScript

Bind any html input

<input id="element-to-bind" type="text">

define two functions:

function bindValue(objectToBind) {
var elemToBind = document.getElementById(objectToBind.id)    
elemToBind.addEventListener("change", function() {
    objectToBind.value = this.value;
})
}

function proxify(id) { 
var handler = {
    set: function(target, key, value, receiver) {
        target[key] = value;
        document.getElementById(target.id).value = value;
        return Reflect.set(target, key, value);
    },
}
return new Proxy({id: id}, handler);
}

use the functions:

var myObject = proxify('element-to-bind')
bindValue(myObject);

How to debug .htaccess RewriteRule not working

Generally any change in the .htaccess should have visible effects. If no effect, check your configuration apache files, something like:

<Directory ..>
    ...
    AllowOverride None
    ...
</Directory>

Should be changed to

AllowOverride All

And you'll be able to change directives in .htaccess files.

Django check for any exists for a query

As of Django 1.2, you can use exists():

https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists

if some_queryset.filter(pk=entity_id).exists():
    print("Entry contained in queryset")

does linux shell support list data structure?

It supports lists, but not as a separate data structure (ignoring arrays for the moment).

The for loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:

for i in 1 2 3; do
    echo "$i"
done

or via parameter expansion:

listVar="1 2 3"
for i in $listVar; do
    echo "$i"
done

or command substitution:

for i in $(echo 1; echo 2; echo 3); do
    echo "$i"
done

An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:

array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do   # The quotes are necessary here
    echo "$i"
done

list='"item 1" "item 2" "item 3"'
for i in $list; do
    echo $i
done
for i in "$list"; do
    echo $i
done
for i in ${array[@]}; do
    echo $i
done

Submitting a form by pressing enter without a submit button

I added it to a function on document ready. If there is no submit button on the form (all of my Jquery Dialog Forms don't have submit buttons), append it.

$(document).ready(function (){
    addHiddenSubmitButtonsSoICanHitEnter();
});
function addHiddenSubmitButtonsSoICanHitEnter(){
    var hiddenSubmit = "<input type='submit' style='position: absolute; left: -9999px; width: 1px; height: 1px;' tabindex='-1'/>";
    $("form").each(function(i,el){
        if($(this).find(":submit").length==0)
            $(this).append(hiddenSubmit);
    });
}

How to capture multiple repeated groups?

After reading Byte Commander's answer, I want to introduce a tiny possible improvement:

You can generate a regexp that will match either n words, as long as your n is predetermined. For instance, if I want to match between 1 and 3 words, the regexp:

^([A-Z]+)(?:,([A-Z]+))?(?:,([A-Z]+))?$

will match the next sentences, with one, two or three capturing groups.

HELLO,LITTLE,WORLD
HELLO,WORLD
HELLO

You can see a fully detailed explanation about this regular expression on Regex101.

As I said, it is pretty easy to generate this regexp for any groups you want using your favorite language. Since I'm not much of a swift guy, here's a ruby example:

def make_regexp(group_regexp, count: 3, delimiter: ",")
  regexp_str = "^(#{group_regexp})"
  (count - 1).times.each do
    regexp_str += "(?:#{delimiter}(#{group_regexp}))?"
  end
  regexp_str += "$"
  return regexp_str
end

puts make_regexp("[A-Z]+")

That being said, I'd suggest not using regular expression in that case, there are many other great tools from a simple split to some tokenization patterns depending on your needs. IMHO, a regular expression is not one of them. For instance in ruby I'd use something like str.split(",") or str.scan(/[A-Z]+/)

Difference between File.separator and slash in paths

The pathname for a file or directory is specified using the naming conventions of the host system. However, the File class defines platform-dependent constants that can be used to handle file and directory names in a platform-independent way.

Files.seperator defines the character or string that separates the directory and the file com- ponents in a pathname. This separator is '/', '\' or ':' for Unix, Windows, and Macintosh, respectively.

What's the simplest way to extend a numpy array in 2 dimensions?

I find it much easier to "extend" via assigning in a bigger matrix. E.g.

import numpy as np
p = np.array([[1,2], [3,4]])
g = np.array(range(20))
g.shape = (4,5)
g[0:2, 0:2] = p

Here are the arrays:

p

   array([[1, 2],
       [3, 4]])

g:

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

and the resulting g after assignment:

   array([[ 1,  2,  2,  3,  4],
       [ 3,  4,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

How to get a unix script to run every 15 seconds?

To avoid possible overlapping of execution, use a locking mechanism as described in that thread.

What are some good Python ORM solutions?

SQLAlchemy is very, very powerful. However it is not thread safe make sure you keep that in mind when working with cherrypy in thread-pool mode.

HTTP Basic Authentication - what's the expected web browser experience?

WWW-Authenticate header

You may also get this if the server is sending a 401 response code but not setting the WWW-Authenticate header correctly - I should know, I've just fixed that in out own code because VB apps weren't popping up the authentication prompt.

Invalid column count in CSV input on line 1 Error

If the table was already created, and you were lazy enough not to specify the columns in the fields names input, then all you have to do is to select the empty columns at right to the file content and delete them.

How can I center an image in Bootstrap?

Since the img is an inline element, Just use text-center on it's container. Using mx-auto will center the container (column) too.

<div class="row">
    <div class="col-4 mx-auto text-center">
        <img src="..">
    </div>
</div>

By default, images are display:inline. If you only want the center the image (and not the other column content), make the image display:block using the d-block class, and then mx-auto will work.

<div class="row">
  <div class="col-4">
    <img class="mx-auto d-block" src="..">
  </div>
</div>

Demo: http://codeply.com/go/iakGGLdB8s

Messagebox with input field

You can do it by making form and displaying it using ShowDialogBox....

Form.ShowDialog Method - Shows the form as a modal dialog box.

Example:

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();

   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.
      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

Replace Your JS with

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

Source link

Delete all files in directory (but not directory) - one liner solution

public class DeleteFile {
    public static void main(String[] args) {
        String path="D:\test"; 
        File file = new File(path);
        File[] files = file.listFiles(); 
        for (File f:files) 
        {if (f.isFile() && f.exists) 
            { f.delete();
system.out.println("successfully deleted");
            }else{
system.out.println("cant delete a file due to open or error");
} }  }}

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

Find from root path find / -name "index.html"

Find from current path find . -name "index.html"

Showing an image from an array of images - Javascript

Also, when checking for the last image, you must compare with imgArray.length-1 because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:

if(i == imgArray.length-1)

Python not working in command prompt?

Kalle posted a link to a page that has this video on it, but it's done on XP. If you use Windows 7:

  1. Press the windows key.
  2. Type "system env". Press enter.
  3. Press alt + n
  4. Press alt + e
  5. Press right, and then ; (that's a semicolon)
  6. Without adding a space, type this at the end: C:\Python27
  7. Hit enter twice. Hit esc.
  8. Use windows key + r to bring up the run dialog. Type in python and press enter.

Defining an abstract class without any abstract methods

Yes you can. Sometimes you may get asked this question that what is the purpose doing this? The answer is: sometimes we have to restrict the class from instantiating by its own. In that case, we want user to extend our Abstract class and instantiate child class

How to revert initial git commit?

git reset --hard make changes, then do

git add -A
git commit --amend --no-edit 

or

git add -A
git commit --amend -m "commit_message"

and then

git push origin master --force

--force will rewrite that commit you've reseted to in the first step.

Don't do this, because you're about to go against the whole idea of VCS systems and git in particular. The only good method is to create new and delete unneeded branch. See git help branch for info.

What is the meaning of git reset --hard origin/master?

git reset --hard origin/master

says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

In my case the problem was that GNOME keyring was holding an invalid passphrase for the ssh key to be used. After spending indecent amount of time troubleshooting this issue I ran seahorse and found the entry to hold empty string. I can only guess that it was caused by mistyping the passphrase at first use some time earlier, and then probably cancelling the requester or so in order to fall back to command line. Updating the entry with correct passphrase immediately solved the problem. Deleting that entry (from "login" keyring) and reentering passphrase at that first prompt (and checking the appropriate checkbox) solves this too. Now agent gets the correct passphrase from the unlocked at login keyring named "login" and neither asks for passphrase nor "refuses operation" anymore. Of course YMMV.

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

SnappySnippet

I finally found some time to create this tool. You can install SnappySnippet from Github. It allows easy HTML+CSS extraction from the specified (last inspected) DOM node. Additionally, you can send your code straight to CodePen or JSFiddle. Enjoy!

SnappySnippet Chrome extension

Other features

  • cleans up HTML (removing unnecessary attributes, fixing indentation)
  • optimizes CSS to make it readable
  • fully configurable (all filters can be turned off)
  • works with ::before and ::after pseudo-elements
  • nice UI thanks to Bootstrap & Flat-UI projects

Code

SnappySnippet is open source, and you can find the code on GitHub.

Implementation

Since I've learned quite a lot while making this, I've decided to share some of the problems I've experienced and my solutions to them, maybe someone will find it interesting.

First attempt - getMatchedCSSRules()

At first I've tried retrieving the original CSS rules (coming from CSS files on the website). Quite amazingly, this is very simple thanks to window.getMatchedCSSRules(), however, it didn't work out well. The problem was that we were taking only a part of the HTML and CSS selectors that were matching in the context of the whole document, which were not matching anymore in the context of an HTML snippet. Since parsing and modifying selectors didn't seem like a good idea, I gave up on this attempt.

Second attempt - getComputedStyle()

Then, I've started from something that @CollectiveCognition suggested - getComputedStyle(). However, I really wanted to separate CSS form HTML instead of inlining all styles.

Problem 1 - separating CSS from HTML

The solution here wasn't very beautiful but quite straightforward. I've assigned IDs to all nodes in the selected subtree and used that ID to create appropriate CSS rules.

Problem 2 - removing properties with default values

Assigning IDs to the nodes worked out nicely, however I found out that each of my CSS rules has ~300 properties making the whole CSS unreadable.
Turns out that getComputedStyle() returns all possible CSS properties and values calculated for the given element. Some of them where empty, some had browser default values. To remove default values I had to get them from the browser first (and each tag has different default values). The solution was to compare the styles of the element coming from the website with the same element inserted into an empty <iframe>. The logic here was that there are no style sheets in an empty <iframe>, so each element I've appended there had only default browser styles. This way I was able to get rid of most of the properties that were insignificant.

Problem 3 - keeping only shorthand properties

Next thing I have spotted was that properties having shorthand equivalent were unnecessarily printed out (e.g. there was border: solid black 1px and then border-color: black;, border-width: 1px itd.).
To solve this I've simply created a list of properties that have shorthand equivalents and filtered them out from the results.

Problem 4 - removing prefixed properties

The number of properties in each rule was significantly lower after the previous operation, but I've found that I sill had a lot of -webkit- prefixed properties that I've never hear of (-webkit-app-region? -webkit-text-emphasis-position?).
I was wondering if I should keep any of these properties because some of them seemed useful (-webkit-transform-origin, -webkit-perspective-origin etc.). I haven't figured out how to verify this, though, and since I knew that most of the time these properties are just garbage, I decided to remove them all.

Problem 5 - combining same CSS rules

The next problem I have spotted was that the same CSS rules are repeated over and over (e.g. for each <li> with the exact same styles there was the same rule in the CSS output created).
This was just a matter of comparing rules with each other and combining these that had exactly the same set of properties and values. As a result, instead of #LI_1{...}, #LI_2{...} I got #LI_1, #LI_2 {...}.

Problem 6 - cleaning up and fixing indentation of HTML

Since I was happy with the result, I moved to HTML. It looked like a mess, mostly because the outerHTML property keeps it formatted exactly as it was returned from the server.
The only thing HTML code taken from outerHTML needed was a simple code reformatting. Since it's something available in every IDE, I was sure that there is a JavaScript library that does exactly that. And it turns out that I was right (jquery-clean). What's more, I've got unnecessary attributes removal extra (style, data-ng-repeat etc.).

Problem 7 - filters breaking CSS

Since there is a chance that in some circumstances filters mentioned above may break CSS in the snippet, I've made all of them optional. You can disable them from the Settings menu.

Scraping html tables into R data frames using the XML package

…or a shorter try:

library(XML)
library(RCurl)
library(rlist)
theurl <- getURL("https://en.wikipedia.org/wiki/Brazil_national_football_team",.opts = list(ssl.verifypeer = FALSE) )
tables <- readHTMLTable(theurl)
tables <- list.clean(tables, fun = is.null, recursive = FALSE)
n.rows <- unlist(lapply(tables, function(t) dim(t)[1]))

the picked table is the longest one on the page

tables[[which.max(n.rows)]]

How to add a title to a html select tag

Typically, I would suggest that you use the <optgroup> option, as that gives some nice styling and indenting to the element.

The HTML element creates a grouping of options within a element. (Source: MDN Web Docs: <optgroup>.

But, since an <optgroup> cannot be a selected value, you can make an <option selected disabled> and then stylize it with CSS so that it behaves like an <optgroup>....

_x000D_
_x000D_
.optionGroup {
    font-weight: bold;
    font-style: italic;
}
_x000D_
<select>
    <option class="optionGroup" selected disabled>Choose one</option>
    <option value="sydney" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Sydney</option>
    <option value="melbourne" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Melbourne</option>
    <option value="cromwell" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Cromwell</option>
    <option value="queenstown" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Queenstown</option>
</select>
_x000D_
_x000D_
_x000D_

Which version of C# am I using

The current answers are outdated. You should be able to use #error version (at the top of any C# file in the project, or nearly anywhere in the code). The compiler treats this in a special way and reports a compiler error, CS8304, indicating the language version, and also the compiler version. The message of CS8304 is something that looks like the following:

error CS8304: Compiler version: '3.7.0-3.20312.3 (ec484126)'. Language version: 6.

The type java.lang.CharSequence cannot be resolved in package declaration

Make your Project and Workspace to point to JDK7 which will resolve the issue. https://developers.google.com/eclipse/docs/jdk_compliance has given ways to modify Compliance and Facet level changes.

How to change the color of winform DataGridview header?

The way to do this is to set the EnableHeadersVisualStyles flag for the data grid view to False, and set the background colour via the ColumnHeadersDefaultCellStyle.BackColor property. For example, to set the background colour to blue, use the following (or set in the designer if you prefer):

_dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
_dataGridView.EnableHeadersVisualStyles = false;

If you do not set the EnableHeadersVisualStyles flag to False, then the changes you make to the style of the header will not take effect, as the grid will use the style from the current users default theme. The MSDN documentation for this property is here.

How do I cancel an HTTP fetch() request?

Let's polyfill:

if(!AbortController){
  class AbortController {
    constructor() {
      this.aborted = false;
      this.signal = this.signal.bind(this);
    }
    signal(abortFn, scope) {
      if (this.aborted) {
        abortFn.apply(scope, { name: 'AbortError' });
        this.aborted = false;
      } else {
        this.abortFn = abortFn.bind(scope);
      }
    }
    abort() {
      if (this.abortFn) {
        this.abortFn({ reason: 'canceled' });
        this.aborted = false;
      } else {
        this.aborted = true;
      }
    }
  }

  const originalFetch = window.fetch;

  const customFetch = (url, options) => {
    const { signal } = options || {};

    return new Promise((resolve, reject) => {
      if (signal) {
        signal(reject, this);
      }
      originalFetch(url, options)
        .then(resolve)
        .catch(reject);
    });
  };

  window.fetch = customFetch;
}

Please have in mind that the code is not tested! Let me know if you have tested it and something didn't work. It may give you warnings that you try to overwrite the 'fetch' function from the JavaScript official library.

How to filter rows containing a string pattern from a Pandas dataframe

If you want to set the column you filter on as a new index, you could also consider to use .filter; if you want to keep it as a separate column then str.contains is the way to go.

Let's say you have

df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': [u'aball', u'bball', u'cnut', u'fball', 'ballxyz']})

       ids  vals
0    aball     1
1    bball     2
2     cnut     3
3    fball     4
4  ballxyz     5

and your plan is to filter all rows in which ids contains ball AND set ids as new index, you can do

df.set_index('ids').filter(like='ball', axis=0)

which gives

         vals
ids          
aball       1
bball       2
fball       4
ballxyz     5

But filter also allows you to pass a regex, so you could also filter only those rows where the column entry ends with ball. In this case you use

df.set_index('ids').filter(regex='ball$', axis=0)

       vals
ids        
aball     1
bball     2
fball     4

Note that now the entry with ballxyz is not included as it starts with ball and does not end with it.

If you want to get all entries that start with ball you can simple use

df.set_index('ids').filter(regex='^ball', axis=0)

yielding

         vals
ids          
ballxyz     5

The same works with columns; all you then need to change is the axis=0 part. If you filter based on columns, it would be axis=1.

How to create a Rectangle object in Java using g.fillRect method

Try this:

public void paint (Graphics g) {    
    Rectangle r = new Rectangle(xPos,yPos,width,height);
    g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());  
}

[edit]

// With explicit casting
public void paint (Graphics g) {    
        Rectangle r = new Rectangle(xPos, yPos, width, height);
        g.fillRect(
           (int)r.getX(),
           (int)r.getY(),
           (int)r.getWidth(),
           (int)r.getHeight()
        );  
    }

How to terminate the script in JavaScript?

i use this piece of code to stop execution:

throw new FatalError("!! Stop JS !!");

you will get a console error though but it works good for me.

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

XAMPP - Port 80 in use by “Unable to open process” with PID 4! 12

run the comment in cmd tasklist

and find which the PID and process name related to this now open window task manager

you can also open window task manager by using CTRL+ALT+DEL

now click on the process tab and find the name which using PID and right click on that and end process

now again restart the xampp

Automatically open default email client and pre-populate content

As described by RFC 6068, mailto allows you to specify subject and body, as well as cc fields. For example:

mailto:[email protected]?subject=Subject&body=message%20goes%20here

User doesn't need to click a link if you force it to be opened with JavaScript

window.location.href = "mailto:[email protected]?subject=Subject&body=message%20goes%20here";

Be aware that there is no single, standard way in which browsers/email clients handle mailto links (e.g. subject and body fields may be discarded without a warning). Also there is a risk that popup and ad blockers, anti-virus software etc. may silently block forced opening of mailto links.

What are DDL and DML?

DDL is Data Definition Language : Specification notation for defining the database schema. It works on Schema level.

DDL commands are:

create,drop,alter,rename

For example:

create table account (
  account_number  char(10),
 balance integer);

DML is Data Manipulation Language .It is used for accessing and manipulating the data.

DML commands are:

select,insert,delete,update,call

For example :

update account set balance = 1000 where account_number = 01;

How can I connect to a Tor hidden service using cURL in PHP?

You need to set option CURLOPT_PROXYTYPE to CURLPROXY_SOCKS5_HOSTNAME, which sadly wasn't defined in old PHP versions, circa pre-5.6; if you have earlier in but you can explicitly use its value, which is equal to 7:

curl_setopt($ch, CURLOPT_PROXYTYPE, 7);

javascript compare strings without being case sensitive

You can also use string.match().

var string1 = "aBc";
var match = string1.match(/AbC/i);

if(match) {
}

How to make Bootstrap carousel slider use mobile left/right swipe

See this solution: Bootstrap TouchCarousel. A drop-in perfection for Twitter Bootstrap's Carousel (v3) to enable gestures on touch devices. http://ixisio.github.io/bootstrap-touch-carousel/

MySQL: Grant **all** privileges on database

This will be helpful for some people:

From MySQL command line:

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

Sadly, at this point newuser has no permissions to do anything with the databases. In fact, if newuser even tries to login (with the password, password), they will not be able to reach the MySQL shell.

Therefore, the first thing to do is to provide the user with access to the information they will need.

GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

The asterisks in this command refer to the database and table (respectively) that they can access—this specific command allows to the user to read, edit, execute and perform all tasks across all the databases and tables.

Once you have finalized the permissions that you want to set up for your new users, always be sure to reload all the privileges.

FLUSH PRIVILEGES;

Your changes will now be in effect.

For more information: http://dev.mysql.com/doc/refman/5.6/en/grant.html

If you are not comfortable with the command line then you can use a client like MySQL workbench, Navicat or SQLyog

How can I revert a single file to a previous version?

Let's start with a qualitative description of what we want to do (much of this is said in Ben Straub's answer). We've made some number of commits, five of which changed a given file, and we want to revert the file to one of the previous versions. First of all, git doesn't keep version numbers for individual files. It just tracks content - a commit is essentially a snapshot of the work tree, along with some metadata (e.g. commit message). So, we have to know which commit has the version of the file we want. Once we know that, we'll need to make a new commit reverting the file to that state. (We can't just muck around with history, because we've already pushed this content, and editing history messes with everyone else.)

So let's start with finding the right commit. You can see the commits which have made modifications to given file(s) very easily:

git log path/to/file

If your commit messages aren't good enough, and you need to see what was done to the file in each commit, use the -p/--patch option:

git log -p path/to/file

Or, if you prefer the graphical view of gitk

gitk path/to/file

You can also do this once you've started gitk through the view menu; one of the options for a view is a list of paths to include.

Either way, you'll be able to find the SHA1 (hash) of the commit with the version of the file you want. Now, all you have to do is this:

# get the version of the file from the given commit
git checkout <commit> path/to/file
# and commit this modification
git commit

(The checkout command first reads the file into the index, then copies it into the work tree, so there's no need to use git add to add it to the index in preparation for committing.)

If your file may not have a simple history (e.g. renames and copies), see VonC's excellent comment. git can be directed to search more carefully for such things, at the expense of speed. If you're confident the history's simple, you needn't bother.

How to position a CSS triangle using ::after?

You can set triangle with position see this code for reference

.top-left-corner {
    width: 0px;
    height: 0px;
    border-top: 0px solid transparent;
    border-bottom: 55px solid transparent;
    border-left: 55px solid #289006;
    position: absolute;
    left: 0px;
    top: 0px;
}

How to prevent Right Click option using jquery

Here is a working example, the red links can't be right clicked anymore.

_x000D_
_x000D_
$("ul.someLinks1 a").each(function(i, obj) {_x000D_
_x000D_
  $(obj).on("contextmenu",function(){_x000D_
     return false;_x000D_
  }); _x000D_
  _x000D_
  $(obj).css("color", "red");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul class="someLinks1">_x000D_
  <li><a href="www.google.de">google</a></li>_x000D_
  <li><a href="www.stackoverflow.de">stackoverflow</a></li>_x000D_
  <li><a href="www.test.de">test</a></li>_x000D_
</ul>_x000D_
_x000D_
<ul class="someLinks2">_x000D_
  <li><a href="www.foobar.de">foobar</a></li>_x000D_
  <li><a href="www.foo.de">foo</a></li>_x000D_
  <li><a href="www.bar.de">bar</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Can't connect Nexus 4 to adb: unauthorized

It happened for me after my backup software changed the permission to my user directory. I opened it in File Explorer, it prompted me to set permissions and it fixed the issue.

FYI: Android has a special directory under "\User\.android" If you can't access it, it won't prompt you.

ES6 Map in Typescript

As a bare minimum:

tsconfig:

 "lib": [
      "es2015"
    ]

and install a polyfill such as https://github.com/zloirock/core-js if you want IE < 11 support: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

show validation error messages on submit in angularjs

http://jsfiddle.net/LRD5x/30/ A simple solution.

HTML

<form ng-submit="sendForm($event)" ng-class={submitted:submitted}>

JS

$scope.sendForm = function($event) {
  $event.preventDefault()
  $scope.submitted = true
};

CSS

.submitted input.ng-invalid:not(:focus) {
    background-color: #FA787E;
}

input.ng-invalid ~ .alert{
    display:none;
}
.submitted input.ng-invalid ~ .alert{
    display:block;
}

Web API optional parameters

you need only set default value to parameters(you do not need the Route attribute):

public IHttpActionResult Get(string apc = null, string xpc = null, int? sku = null)
{ ... }

Deactivate or remove the scrollbar on HTML

put this code in your html header:

<style type="text/css">
html {
        overflow: auto;
}
</style>

How to remove the default link color of the html hyperlink 'a' tag?

This is also possible:

        a {
            all: unset;
        }

unset: This keyword indicates to change all the properties applying to the element or the element's parent to their parent value if they are inheritable or to their initial value if not. unicode-bidi and direction values are not affected.

Source: Mozilla description of all

Using String Format to show decimal up to 2 places or simple integer

Try:

String.Format("{0:0.00}", Convert.ToDecimal(totalPrice));

How to Import 1GB .sql file to WAMP/phpmyadmin

Before importing just make sure you have max_allowed_pack value set some thing large else you will get an error: Error 2006 MySQL server gone away.

Then try the command: mysql -u root -p database_name < file.sql

How to disable Google asking permission to regularly check installed apps on my phone?

In Nexus 5, Go to Settings -> Google -> Security and uncheck "Scan device for Security threats" and "Improve harmful app detection".

WPF MVVM: How to close a window

Simple approach is close window on saveComand Implementation. Use below code to close window.

Application.Current.Windows[1].Close();

It will close the child window.

How to Remove the last char of String in C#?

var input = "12342";
var output = input.Substring(0, input.Length - 1); 

or

var output = input.Remove(input.Length - 1);

Check if value exists in column in VBA

Simplest is to use Match

If Not IsError(Application.Match(ValueToSearchFor, RangeToSearchIn, 0)) Then
    ' String is in range

Converting Pandas dataframe into Spark dataframe error

I received a similar error message once, in my case it was because my pandas dataframe contained NULLs. I will recommend to try & handle this in pandas before converting to spark (this resolved the issue in my case).

How to send email from Terminal?

For SMTP hosts and Gmail I like to use Swaks -> https://easyengine.io/tutorials/mail/swaks-smtp-test-tool/

On a Mac:

  1. brew install swaks
  2. swaks --to [email protected] --server smtp.example.com

How to set a time zone (or a Kind) of a DateTime value?

While the DateTime.Kind property does not have a setter, the static method DateTime.SpecifyKind creates a DateTime instance with a specified value for Kind.

Altenatively there are several DateTime constructor overloads that take a DateTimeKind parameter

How to suppress binary file matching results in grep

This is an old question and its been answered but I thought I'd put the --binary-files=text option here for anyone who wants to use it. The -I option ignores the binary file but if you want the grep to treat the binary file as a text file use --binary-files=text like so:

bash$ grep -i reset mediaLog*
Binary file mediaLog_dc1.txt matches
bash$ grep --binary-files=text -i reset mediaLog*
mediaLog_dc1.txt:2016-06-29 15:46:02,470 - Media [uploadChunk  ,315] - ERROR - ('Connection aborted.', error(104, 'Connection reset by peer'))
mediaLog_dc1.txt:ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer'))
bash$

In Gradle, is there a better way to get Environment Variables?

I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:

home = System.getenv('HOME')

It helps to keep in mind that anything that works in pure Java will work in Gradle too.

Why does CSS not support negative padding?

This could help, by the way:

The box-sizing CSS property is used to alter the default CSS box model used to calculate widths and heights of elements.

http://www.w3.org/TR/css3-ui/#box-sizing
https://developer.mozilla.org/En/CSS/Box-sizing

How to detect running app using ADB command

No need to use grep. ps in Android can filter by COMM value (last 15 characters of the package name in case of java app)

Let's say we want to check if com.android.phone is running:

adb shell ps m.android.phone
USER     PID   PPID  VSIZE  RSS     WCHAN    PC         NAME
radio     1389  277   515960 33964 ffffffff 4024c270 S com.android.phone

Filtering by COMM value option has been removed from ps in Android 7.0. To check for a running process by name in Android 7.0 you can use pidof command:

adb shell pidof com.android.phone

It returns the PID if such process was found or an empty string otherwise.

How to Bulk Insert from XLSX file extension?

It can be done using SQL Server Import and Export Wizard. But if you're familiar with SSIS and don't want to run the SQL Server Import and Export Wizard, create an SSIS package that uses the Excel Source and the SQL Server Destination in the data flow.

Java List.contains(Object with field value equal to x)

This is how to do it using Java 8+ :

boolean isJohnAlive = list.stream().anyMatch(o -> o.getName().equals("John"));

Difference between innerText, innerHTML and value?

Unlike innerText, though, innerHTML lets you work with HTML rich text and doesn't automatically encode and decode text. In other words, innerText retrieves and sets the content of the tag as plain text, whereas innerHTML retrieves and sets the content in HTML format.

End-line characters from lines read from text file, using Python

The idiomatic way to do this in Python is to use rstrip('\n'):

for line in open('myfile.txt'):  # opened in text-mode; all EOLs are converted to '\n'
    line = line.rstrip('\n')
    process(line)

Each of the other alternatives has a gotcha:

  • file('...').read().splitlines() has to load the whole file in memory at once.
  • line = line[:-1] will fail if the last line has no EOL.

JavaScript is in array

Use Underscore.js

It cross-browser compliant and can perform a binary search if your data is sorted.

_.indexOf

_.indexOf(array, value, [isSorted]) Returns the index at which value can be found in the array, or -1 if value is not present in the array. Uses the native indexOf function unless it's missing. If you're working with a large array, and you know that the array is already sorted, pass true for isSorted to use a faster binary search.

Example

//Tell underscore your data is sorted (Binary Search)
if(_.indexOf(['2','3','4','5','6'], '4', true) != -1){
    alert('true');
}else{
    alert('false');   
}

//Unsorted data works to!
if(_.indexOf([2,3,6,9,5], 9) != -1){
    alert('true');
}else{
    alert('false');   
}

Generate MD5 hash string with T-SQL

declare @hash nvarchar(50)
--declare @hash varchar(50)

set @hash = '1111111-2;20190110143334;001'  -- result a5cd84bfc56e245bbf81210f05b7f65f
declare @value varbinary(max);
set @value = convert(varbinary(max),@hash);


select  
 SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', '1111111-2;20190110143334;001')),3,32) as 'OK'
,SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', @hash)),3,32) as 'ERROR_01'
,SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5',convert(varbinary(max),@hash))),3,32) as 'ERROR_02'
,SUBSTRING(sys.fn_sqlvarbasetostr(sys.fn_repl_hash_binary(convert(varbinary(max),@hash))),3,32)
,SUBSTRING(sys.fn_sqlvarbasetostr(master.sys.fn_repl_hash_binary(@value)),3,32)

Skip the headers when editing a csv file using Python

Another way of solving this is to use the DictReader class, which "skips" the header row and uses it to allowed named indexing.

Given "foo.csv" as follows:

FirstColumn,SecondColumn
asdf,1234
qwer,5678

Use DictReader like this:

import csv
with open('foo.csv') as f:
    reader = csv.DictReader(f, delimiter=',')
    for row in reader:
        print(row['FirstColumn'])  # Access by column header instead of column number
        print(row['SecondColumn'])

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

Get jQuery version from inspecting the jQuery object

For older versions of jQuery

jQuery().jquery  (or)

jQuery().fn.jquery

For newer versions of jQuery

$().jquery  (or)

$().fn.jquery

Query to list all users of a certain group

memberOf (in AD) is stored as a list of distinguishedNames. Your filter needs to be something like:

(&(objectCategory=user)(memberOf=cn=MyCustomGroup,ou=ouOfGroup,dc=subdomain,dc=domain,dc=com))

If you don't yet have the distinguished name, you can search for it with:

(&(objectCategory=group)(cn=myCustomGroup))

and return the attribute distinguishedName. Case may matter.

Passing parameters to JavaScript files

I'd recommend not using global variables if possible. Use a namespace and OOP to pass your arguments through to an object.

This code belongs in file.js:

var MYLIBRARY = MYLIBRARY || (function(){
    var _args = {}; // private

    return {
        init : function(Args) {
            _args = Args;
            // some other initialising
        },
        helloWorld : function() {
            alert('Hello World! -' + _args[0]);
        }
    };
}());

And in your html file:

<script type="text/javascript" src="file.js"></script>
<script type="text/javascript">
   MYLIBRARY.init(["somevalue", 1, "controlId"]);
   MYLIBRARY.helloWorld();
</script>

Is it possible to set async:false to $.getJSON call

I think you both are right. The later answer works fine but its like setting a global option so you have to do the following:

    $.ajaxSetup({
        async: false
    });

    //ajax call here

    $.ajaxSetup({
        async: true
    });

Insert line break inside placeholder attribute of a textarea?

Add only &#10 for breaking line, no need to write any CSS or javascript.

_x000D_
_x000D_
textarea{_x000D_
    width:300px;_x000D_
    height:100px;_x000D_
_x000D_
}
_x000D_
<textarea placeholder='This is a line this &#10should be a new line'></textarea>_x000D_
_x000D_
<textarea placeholder=' This is a line _x000D_
_x000D_
should this be a new line?'></textarea>
_x000D_
_x000D_
_x000D_

Case Insensitive String comp in C

Additional pitfalls to watch out for when doing case insensitive compares:


Comparing as lower or as upper case? (common enough issue)

Both below will return 0 with strcicmpL("A", "a") and strcicmpU("A", "a").
Yet strcicmpL("A", "_") and strcicmpU("A", "_") can return different signed results as '_' is often between the upper and lower case letters.

This affects the sort order when used with qsort(..., ..., ..., strcicmp). Non-standard library C functions like the commonly available stricmp() or strcasecmp() tend to be well defined and favor comparing via lowercase. Yet variations exist.

int strcicmpL(char const *a, char const *b) {
  while (*b) {
    int d = tolower(*a) - tolower(*b);
    if (d) {
        return d;
    } 
    a++;
    b++;
  } 
  return tolower(*a);
}

int strcicmpU(char const *a, char const *b) {
  while (*b) {
    int d = toupper(*a) - toupper(*b);
    if (d) {
        return d;
    } 
    a++;
    b++;
  } 
  return toupper(*a);
}

char can have a negative value. (not rare)

touppper(int) and tolower(int) are specified for unsigned char values and the negative EOF. Further, strcmp() returns results as if each char was converted to unsigned char, regardless if char is signed or unsigned.

tolower(*a); // Potential UB
tolower((unsigned char) *a); // Correct (Almost - see following)

char can have a negative value and not 2's complement. (rare)

The above does not handle -0 nor other negative values properly as the bit pattern should be interpreted as unsigned char. To properly handle all integer encodings, change the pointer type first.

// tolower((unsigned char) *a);
tolower(*(const unsigned char *)a); // Correct

Locale (less common)

Although character sets using ASCII code (0-127) are ubiquitous, the remainder codes tend to have locale specific issues. So strcasecmp("\xE4", "a") might return a 0 on one system and non-zero on another.


Unicode (the way of the future)

If a solution needs to handle more than ASCII consider a unicode_strcicmp(). As C lib does not provide such a function, a pre-coded function from some alternate library is recommended. Writing your own unicode_strcicmp() is a daunting task.


Do all letters map one lower to one upper? (pedantic)

[A-Z] maps one-to-one with [a-z], yet various locales map various lower case chracters to one upper and visa-versa. Further, some uppercase characters may lack a lower case equivalent and again, visa-versa.

This obliges code to covert through both tolower() and tolower().

int d = tolower(toupper(*a)) - tolower(toupper(*b));

Again, potential different results for sorting if code did tolower(toupper(*a)) vs. toupper(tolower(*a)).


Portability

@B. Nadolson recommends to avoid rolling your own strcicmp() and this is reasonable, except when code needs high equivalent portable functionality.

Below is an approach that even performed faster than some system provided functions. It does a single compare per loop rather than two by using 2 different tables that differ with '\0'. Your results may vary.

static unsigned char low1[UCHAR_MAX + 1] = {
  0, 1, 2, 3, ...
  '@', 'a', 'b', 'c', ... 'z', `[`, ...  // @ABC... Z[...
  '`', 'a', 'b', 'c', ... 'z', `{`, ...  // `abc... z{...
}
static unsigned char low2[UCHAR_MAX + 1] = {
// v--- Not zero, but A which matches none in `low1[]`
  'A', 1, 2, 3, ...
  '@', 'a', 'b', 'c', ... 'z', `[`, ...
  '`', 'a', 'b', 'c', ... 'z', `{`, ...
}

int strcicmp_ch(char const *a, char const *b) {
  // compare using tables that differ slightly.
  while (low1[*(const unsigned char *)a] == low2[*(const unsigned char *)b]) {
    a++;
    b++;
  }
  // Either strings differ or null character detected.
  // Perform subtraction using same table.
  return (low1[*(const unsigned char *)a] - low1[*(const unsigned char *)b]);
}

What's the difference between & and && in MATLAB?

&& and || take scalar inputs and short-circuit always. | and & take array inputs and short-circuit only in if/while statements. For assignment, the latter do not short-circuit.

See these doc pages for more information.

Condition within JOIN or WHERE

I typically see performance increases when filtering on the join. Especially if you can join on indexed columns for both tables. You should be able to cut down on logical reads with most queries doing this too, which is, in a high volume environment, a much better performance indicator than execution time.

I'm always mildly amused when someone shows their SQL benchmarking and they've executed both versions of a sproc 50,000 times at midnight on the dev server and compare the average times.

How to import set of icons into Android Studio project

For custom images you created yourself, you can do without the plugin:

Right click on res folder, selecting New > Image Asset. browse image file. Select the largest image you have.

It will create all densities for you. Make sure you select an original image, not an asset studio image with an alpha, or you will semi-transpartent it twice.

How to escape a while loop in C#

Use break; to escape the first loop:

if (s.Contains("mp4:production/CATCHUP/"))
{
   RemoveEXELog();
   Process p = new Process();
   p.StartInfo.WorkingDirectory = "dump";
   p.StartInfo.FileName = "test.exe"; 
   p.StartInfo.Arguments = s; 
   p.Start();
   break;
}

If you want to also escape the second loop, you might need to use a flag and check in the out loop's guard:

        boolean breakFlag = false;
        while (!breakFlag)
        {
            Thread.Sleep(5000);
            if (!System.IO.File.Exists("Command.bat")) continue;
            using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    if (s.Contains("mp4:production/CATCHUP/"))
                    {

                        RemoveEXELog();

                        Process p = new Process();
                        p.StartInfo.WorkingDirectory = "dump";
                        p.StartInfo.FileName = "test.exe"; 
                        p.StartInfo.Arguments = s; 
                        p.Start();

                        breakFlag = true;
                        break;
                    }
                }
            }

Or, if you want to just exit the function completely from within the nested loop, put in a return; instead of a break;.

But these aren't really considered best practices. You should find some way to add the necessary Boolean logic into your while guards.

Clicking the back button twice to exit an activity

I've tried to create a utils class for this, so any activity or fragment can implement this to be simpler.

The code was written with Kotlin & has Java-interop as well.

I'm using coroutine to delay and reset the flag variable. But you can modify it to your needs.

Additional files: SafeToast.kt

lateinit var toast: Toast

fun Context.safeToast(msg: String, length: Int = Toast.LENGTH_LONG, action: (Context) -> Toast = default) {
    toast = SafeToast.makeText(this@safeToast, msg, length).apply {
        // do anything new here
        action(this@safeToast)
        show()
    }
}

fun Context.toastSpammable(msg: String) {
    cancel()
    safeToast(msg, Toast.LENGTH_SHORT)
}

fun Fragment.toastSpammable(msg: String) {
    cancel()
    requireContext().safeToast(msg, Toast.LENGTH_SHORT)
}

private val default: (Context) -> Toast = { it -> SafeToast.makeText(it, "", Toast.LENGTH_LONG) }

private fun cancel() {
    if (::toast.isInitialized) toast.cancel()
}

ActivityUtils.kt

@file:JvmMultifileClass
@file:JvmName("ActivityUtils")
package your.company.com

import android.app.Activity
import your.company.com.R
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


private var backButtonPressedTwice = false

fun Activity.onBackPressedTwiceFinish() {
    onBackPressedTwiceFinish(getString(R.string.msg_back_pressed_to_exit), 2000)
}

fun Activity.onBackPressedTwiceFinish(@StringRes message: Int, time: Long) {
    onBackPressedTwiceFinish(getString(message), time)
}

fun Activity.onBackPressedTwiceFinish(message: String, time: Long) {
    if (backButtonPressedTwice) {
        onBackPressed()
    } else {
        backButtonPressedTwice = true
        toastSpammable(message)
        GlobalScope.launch {
            delay(time)
            backButtonPressedTwice = false
        }
    }
}

Usage in Kotlin

// ActivityA.kt
override fun onBackPressed() {
    onBackPressedTwiceFinish()
}

Usage in Java

@Override 
public void onBackPressed() {
    ActivityUtils.onBackPressedTwiceFinish()
}

This code was inspired by @webserveis here

Best practice for localization and globalization of strings and labels

jQuery.i18n is a lightweight jQuery plugin for enabling internationalization in your web pages. It allows you to package custom resource strings in ‘.properties’ files, just like in Java Resource Bundles. It loads and parses resource bundles (.properties) based on provided language or language reported by browser.

to know more about this take a look at the How to internationalize your pages using JQuery?

Why are elementwise additions much faster in separate loops than in a combined loop?

OK, the right answer definitely has to do something with the CPU cache. But to use the cache argument can be quite difficult, especially without data.

There are many answers, that led to a lot of discussion, but let's face it: Cache issues can be very complex and are not one dimensional. They depend heavily on the size of the data, so my question was unfair: It turned out to be at a very interesting point in the cache graph.

@Mysticial's answer convinced a lot of people (including me), probably because it was the only one that seemed to rely on facts, but it was only one "data point" of the truth.

That's why I combined his test (using a continuous vs. separate allocation) and @James' Answer's advice.

The graphs below shows, that most of the answers and especially the majority of comments to the question and answers can be considered completely wrong or true depending on the exact scenario and parameters used.

Note that my initial question was at n = 100.000. This point (by accident) exhibits special behavior:

  1. It possesses the greatest discrepancy between the one and two loop'ed version (almost a factor of three)

  2. It is the only point, where one-loop (namely with continuous allocation) beats the two-loop version. (This made Mysticial's answer possible, at all.)

The result using initialized data:

Enter image description here

The result using uninitialized data (this is what Mysticial tested):

Enter image description here

And this is a hard-to-explain one: Initialized data, that is allocated once and reused for every following test case of different vector size:

Enter image description here

Proposal

Every low-level performance related question on Stack Overflow should be required to provide MFLOPS information for the whole range of cache relevant data sizes! It's a waste of everybody's time to think of answers and especially discuss them with others without this information.

How are people unit testing with Entity Framework 6, should you bother?

I have fumbled around sometime to reach these considerations:

1- If my application access the database, why the test should not? What if there is something wrong with data access? The tests must know it beforehand and alert myself about the problem.

2- The Repository Pattern is somewhat hard and time consuming.

So I came up with this approach, that I don't think is the best, but fulfilled my expectations:

Use TransactionScope in the tests methods to avoid changes in the database.

To do it it's necessary:

1- Install the EntityFramework into the Test Project. 2- Put the connection string into the app.config file of Test Project. 3- Reference the dll System.Transactions in Test Project.

The unique side effect is that identity seed will increment when trying to insert, even when the transaction is aborted. But since the tests are made against a development database, this should be no problem.

Sample code:

[TestClass]
public class NameValueTest
{
    [TestMethod]
    public void Edit()
    {
        NameValueController controller = new NameValueController();

        using(var ts = new TransactionScope()) {
            Assert.IsNotNull(controller.Edit(new Models.NameValue()
            {
                NameValueId = 1,
                name1 = "1",
                name2 = "2",
                name3 = "3",
                name4 = "4"
            }));

            //no complete, automatically abort
            //ts.Complete();
        }
    }

    [TestMethod]
    public void Create()
    {
        NameValueController controller = new NameValueController();

        using (var ts = new TransactionScope())
        {
            Assert.IsNotNull(controller.Create(new Models.NameValue()
            {
                name1 = "1",
                name2 = "2",
                name3 = "3",
                name4 = "4"
            }));

            //no complete, automatically abort
            //ts.Complete();
        }
    }
}

How to get the Power of some Integer in Swift language?

Or just :

var a:Int = 3
var b:Int = 3
println(pow(Double(a),Double(b)))

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

In my case a misplaced session.clear() was causing this problem.

How do I test a website using XAMPP?

Just edit the httpd-vhost-conf scroll to the bottom and on the last example/demo for creating a virtual host, remove the hash-tags for DocumentRoot and ServerName. You may have hash-tags just before the <VirtualHost *.80> and </VirtualHost>

After DocumentRoot, just add the path to your web-docs ... and add your domain-name after ServerNmane

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs/www"
    ServerName example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

Be sure to create the www folder under htdocs. You do not have to name the folder www but I did just to be simple about it. Be sure to restart Apache and bang! you can now store files in the newly created directory. To test things out just create a simple index.html or index.php file and place in the www folder, then go to your browser and test it out localhost/ ... Note: if your server is serving php files over html then remember to add localhost/index.html if the html file is the one you choose to use for this test.

Something I should add, in order to still have access to the xampp homepage then you will need to create another VirtualHost. To do this just add

<VirtualHost *:80>
    ##ServerAdmin [email protected]
    DocumentRoot "C:/xampp/htdocs"
    ServerName htdocs.example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

underneath the last VirtualHost that you created. Next make the necessary changes to your host file and restart Apache. Now go to your browser and visit htdocs.example.com and your all set.

What does question mark and dot operator ?. mean in C# 6.0?

This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.

old way to achieve the same thing was:

var functionCaller = this.member;
if (functionCaller!= null)
    functionCaller.someFunction(var someParam);

and now it has been made much easier with just:

member?.someFunction(var someParam);

I strongly recommend this doc page.

Check date with todays date

tl;dr

LocalDate
.parse( "2021-01-23" )
.isBefore(
    LocalDate.now(
        ZoneId.of( "Africa/Tunis" ) 
    )
)

… or:

try 
{
    org.threeten.extra.LocalDateRange range =         
        LocalDateRange.of( 
            LocalDate.of( "2021-01-23" ) ,
            LocalDate.of( "2021-02-21" )
        )
    ;
    if( range.isAfter( 
        LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
    ) { … }
    else { … handle today being within or after the range. }
} catch ( java.time.DateTimeException e ) {
    // Handle error where end is before start.
}

Details

The other answers ignore the crucial issue of time zone.

The other answers use outmoded classes.

Avoid old date-time classes

The old date-time classes bundled with the earliest versions of Java are poorly designed, confusing, and troublesome. Avoid java.util.Date/.Calendar and related classes.

java.time

LocalDate

For date-only values, without time-of-day and without time zone, use the LocalDate class.

LocalDate start = LocalDate.of( 2016 , 1 , 1 );
LocalDate stop = start.plusWeeks( 1 );

Time Zone

Be aware that while LocalDate does not store a time zone, determining a date such as “today” requires a time zone. For any given moment, the date may vary around the world by time zone. For example, a new day dawns earlier in Paris than in Montréal. A moment after midnight in Paris is still “yesterday” in Montréal.

If all you have is an offset-from-UTC, use ZoneOffset. If you have a full time zone (continent/region), then use ZoneId. If you want UTC, use the handy constant ZoneOffset.UTC.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );

Comparing is easy with isEqual, isBefore, and isAfter methods.

boolean invalidInterval = stop.isBefore( start );

We can check to see if today is contained within this date range. In my logic shown here I use the Half-Open approach where the beginning is inclusive while the ending is exclusive. This approach is common in date-time work. So, for example, a week runs from a Monday going up to but not including the following Monday.

// Is today equal or after start (not before) AND today is before stop.
boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ) ;

LocalDateRange

If working extensively with such spans of time, consider adding the ThreeTen-Extra library to your project. This library extends the java.time framework, and is the proving ground for possible additions to java.time.

ThreeTen-Extra includes an LocalDateRange class with handy methods such as abuts, contains, encloses, overlaps, and so on.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

reducing number of plot ticks

Alternatively, if you want to simply set the number of ticks while allowing matplotlib to position them (currently only with MaxNLocator), there is pyplot.locator_params,

pyplot.locator_params(nbins=4)

You can specify specific axis in this method as mentioned below, default is both:

# To specify the number of ticks on both or any single axes
pyplot.locator_params(axis='y', nbins=6)
pyplot.locator_params(axis='x', nbins=10)

inserting characters at the start and end of a string

Strings are immutable so you can't insert characters into an existing string. You have to create a new string. You can use string concatenation to do what you want:

yourstring = "L" + yourstring + "LL"

Note that you can also create a string with n Ls by using multiplication:

m = 1
n = 2
yourstring = ("L" * m) + yourstring + ("L" * n)

ImportError: cannot import name

This can also happen if you've been working on your scripts and functions and have been moving them around (i.e. changed the location of the definition) which could have accidentally created a looping reference.

You may find that the situation is solved if you just reset the iPython kernal to clear any old assignments:

%reset

or menu->restart terminal

Get current URL path in PHP

it should be :

$_SERVER['REQUEST_URI'];

Take a look at : Get the full URL in PHP

How to use systemctl in Ubuntu 14.04

I just encountered this problem myself and found that Ubuntu 14.04 uses Upstart instead of Systemd, so systemctl commands will not work. This changed in 15.04, so one way around this would be to update your ubuntu install.

If this is not an option for you (it's not for me right now), you need to find the Upstart command that does what you need to do.

For enable, the generic looks to be the following:

update-rc.d <service> enable

Link to Ubuntu documentation: https://wiki.ubuntu.com/SystemdForUpstartUsers

How to stop an unstoppable zombie job on Jenkins without restarting the server?

I had many zombi-jobs, so I used the following script:

for(int x = 1000; x < 1813; x = x + 1) {
    Jenkins .instance.getItemByFullName("JOBNAME/BRANCH")
    .getBuildByNumber(x)
    .finish(hudson.model.Result.ABORTED, new java.io.IOException("Aborting build"))
}

Can someone explain how to append an element to an array in C programming?

int arr[10] = {0, 5, 3, 64};
arr[4] = 5;

EDIT: So I was asked to explain what's happening when you do:

int arr[10] = {0, 5, 3, 64};

you create an array with 10 elements and you allocate values for the first 4 elements of the array.

Also keep in mind that arr starts at index arr[0] and ends at index arr[9] - 10 elements

arr[0] has value 0;
arr[1] has value 5;
arr[2] has value 3;
arr[3] has value 64;

after that the array contains garbage values / zeroes because you didn't allocated any other values

But you could still allocate 6 more values so when you do

arr[4] = 5;

you allocate the value 5 to the fifth element of the array.

You could do this until you allocate values for the last index of the arr that is arr[9];

Sorry if my explanation is choppy, but I have never been good at explaining things.

JavaScript - onClick to get the ID of the clicked button

This is improvement of Prateek answer - event is pass by parameter so reply_click not need to use global variable (and as far no body presents this variant)

_x000D_
_x000D_
function reply_click(e) {
  console.log(e.target.id);
}
_x000D_
<button id="1" onClick="reply_click(event)">B1</button>
<button id="2" onClick="reply_click(event)">B2</button>
<button id="3" onClick="reply_click(event)">B3</button>
_x000D_
_x000D_
_x000D_

How do I check if a directory exists? "is_dir", "file_exists" or both?

I think realpath() may be the best way to validate if a path exist http://www.php.net/realpath

Here is an example function:

<?php
/**
 * Checks if a folder exist and return canonicalized absolute pathname (long version)
 * @param string $folder the path being checked.
 * @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
 */
function folder_exist($folder)
{
    // Get canonicalized absolute pathname
    $path = realpath($folder);

    // If it exist, check if it's a directory
    if($path !== false AND is_dir($path))
    {
        // Return canonicalized absolute pathname
        return $path;
    }

    // Path/folder does not exist
    return false;
}

Short version of the same function

<?php
/**
 * Checks if a folder exist and return canonicalized absolute pathname (sort version)
 * @param string $folder the path being checked.
 * @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
 */
function folder_exist($folder)
{
    // Get canonicalized absolute pathname
    $path = realpath($folder);

    // If it exist, check if it's a directory
    return ($path !== false AND is_dir($path)) ? $path : false;
}

Output examples

<?php
/** CASE 1 **/
$input = '/some/path/which/does/not/exist';
var_dump($input);               // string(31) "/some/path/which/does/not/exist"
$output = folder_exist($input);
var_dump($output);              // bool(false)

/** CASE 2 **/
$input = '/home';
var_dump($input);
$output = folder_exist($input);         // string(5) "/home"
var_dump($output);              // string(5) "/home"

/** CASE 3 **/
$input = '/home/..';
var_dump($input);               // string(8) "/home/.."
$output = folder_exist($input);
var_dump($output);              // string(1) "/"

Usage

<?php

$folder = '/foo/bar';

if(FALSE !== ($path = folder_exist($folder)))
{
    die('Folder ' . $path . ' already exist');
}

mkdir($folder);
// Continue do stuff

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Another way

@Html.TextAreaFor(model => model.Comments[0].Comment)

And in your css do this

textarea
{
    font-family: inherit;
    width: 650px;
    height: 65px;
}

That DataType dealie allows carriage returns in the data, not everybody likes those.

Does uninstalling a package with "pip" also remove the dependent packages?

You can install and use the pip-autoremove utility to remove a package plus unused dependencies.

# install pip-autoremove
pip install pip-autoremove
# remove "somepackage" plus its dependencies:
pip-autoremove somepackage -y

How do I create a new class in IntelliJ without using the mouse?

I also searched this answer. Equivalent of command+N on Mac OS for Windows is ctr + alt + insert which @manyways already answered. If you searching this in settings it is in Settings > IDE Settings > Keymap, Other > New ...

How do I disable TextBox using JavaScript?

You can use disabled attribute to disable the textbox.

document.getElementById('color').disabled = true;

Oracle Age calculation from Date of birth and Today

Or how about this?

with some_birthdays as
( 
    select date '1968-06-09' d from dual union all
    select date '1970-06-10' from dual union all
    select date '1972-06-11' from dual union all
    select date '1974-12-11' from dual union all
    select date '1976-09-17' from dual
)
select trunc(sysdate) today
, d birth_date
, floor(months_between(trunc(sysdate),d)/12) age
from some_birthdays;

How to get N rows starting from row M from sorted table in T-SQL

Following is the simple query will list N rows from M+1th row of the table. Replace M and N with your preferred numbers.

Select Top N B.PrimaryKeyColumn from 
    (SELECT 
        top M PrimaryKeyColumn
     FROM 
        MyTable
) A right outer join MyTable B 
on 
    A.PrimaryKeyColumn = B.PrimaryKeyColumn
where 
    A.PrimaryKeyColumn IS NULL

Please let me know whether this is usefull for your situation.

Why am I getting string does not name a type Error?

Just use the std:: qualifier in front of string in your header files.

In fact, you should use it for istream and ostream also - and then you will need #include <iostream> at the top of your header file to make it more self contained.

Notice: Trying to get property of non-object error

@Balamanigandan your Original Post :- PHP Notice: Trying to get property of non-object error

Your are trying to access the Null Object. From AngularJS your are not passing any Objects instead you are passing the $_GET element. Try by using $_GET['uid'] instead of $objData->token

Installing Python 3 on RHEL

You can download a source RPMs and binary RPMs for RHEL6 / CentOS6 from here

This is a backport from the newest Fedora development source rpm to RHEL6 / CentOS6

How do I write the 'cd' command in a makefile?

To change dir

foo: 
    $(MAKE) -C mydir

multi:
    $(MAKE) -C / -C my-custom-dir   ## Equivalent to /my-custom-dir

Java: Clear the console

You can use following code to clear command line console:

public static void clearScreen() {  
    System.out.print("\033[H\033[2J");  
    System.out.flush();  
}  

For further references visit: http://techno-terminal.blogspot.in/2014/12/clear-command-line-console-and-bold.html

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

On Windows (OpenJDK11, Maven 3.6.0, SUREFIRE 3.0.0-M1) I got that root cause:

# Created at 2018-11-14T14:28:15.629
OpenJDK 64-Bit Server VM warning: INFO: os::commit_memory(0x00000006c7500000, 522190848, 0) failed; error='The paging file is too small for this operation to complete' (DOS error/errno=1455)

and resolved by increasing the paging file size, e.g like this.

git commit error: pathspec 'commit' did not match any file(s) known to git

Please try adding the double quotes git commit -m "initial commit". This will solve your problem.

How do I execute a stored procedure in a SQL Agent job?

You just need to add this line to the window there:

exec (your stored proc name) (and possibly add parameters)

What is your stored proc called, and what parameters does it expect?

json_decode() expects parameter 1 to be string, array given

here is the solution for similar problem which i was facing while extracting name from user profile facebook json object

$uname=json_encode($userprof);
$uname=json_decode($uname);
echo "Welcome " . $uname -> name  ;

PostgreSQL how to see which queries have run

PostgreSql is very advanced when related to logging techniques

Logs are stored in Installationfolder/data/pg_log folder. While log settings are placed in postgresql.conf file.

Log format is usually set as stderr. But CSV log format is recommended. In order to enable CSV format change in

log_destination = 'stderr,csvlog'   
logging_collector = on

In order to log all queries, very usefull for new installations, set min. execution time for a query

log_min_duration_statement = 0

In order to view active Queries on your database, use

SELECT * FROM pg_stat_activity

To log specific queries set query type

log_statement = 'all'           # none, ddl, mod, all

For more information on Logging queries see PostgreSql Log.

How to delete selected text in the vi editor

Highlighting with your mouse only highlights characters on the terminal. VI doesn't really get this information, so you have to highlight differently.

Press 'v' to enter a select mode, and use arrow keys to move that around. To delete, press x. To select lines at a time, press shift+v. To select blocks, try ctrl+v. That's good for, say, inserting lots of comment lines in front of your code :).

I'm OK with VI, but it took me a while to improve. My work mates recommended me this cheat sheet. I keep a printout on the wall for those odd moments when I forget something.

Happy hacking!

What is meant with "const" at end of function declaration?

Consider two class-typed variables:

class Boo { ... };

Boo b0;       // mutable object
const Boo b1; // non-mutable object

Now you are able to call any member function of Boo on b0, but only const-qualified member functions on b1.

In vb.net, how to get the column names from a datatable

You can loop through the columns collection of the datatable.

VB

Dim dt As New DataTable()
For Each column As DataColumn In dt.Columns
    Console.WriteLine(column.ColumnName)
Next

C#

DataTable dt = new DataTable();
foreach (DataColumn column in dt.Columns)
{
Console.WriteLine(column.ColumnName);
}

Hope this helps!

Avoid printStackTrace(); use a logger call instead

If you call printStackTrace() on an exception the trace is written to System.err and it's hard to route it elsewhere (or filter it). Instead of doing this you are adviced to use a logging framework (or a wrapper around multiple logging frameworks, like Apache Commons Logging) and log the exception using that framework (e.g. logger.error("some exception message", e)).

Doing that allows you to:

  • write the log statement to different locations at once, e.g. the console and a file
  • filter the log statements by severity (error, warning, info, debug etc.) and origin (normally package or class based)
  • have some influence on the log format without having to change the code
  • etc.

how to use the Box-Cox power transformation in R

Applying the BoxCox transformation to data, without the need of any underlying model, can be done currently using the package geoR. Specifically, you can use the function boxcoxfit() for finding the best parameter and then predict the transformed variables using the function BCtransform().

Why do python lists have pop() but not push()

FYI, it's not terribly difficult to make a list that has a push method:

>>> class StackList(list):
...     def push(self, item):
...             self.append(item)
... 
>>> x = StackList([1,2,3])
>>> x
[1, 2, 3]
>>> x.push(4)
>>> x
[1, 2, 3, 4]

A stack is a somewhat abstract datatype. The idea of "pushing" and "popping" are largely independent of how the stack is actually implemented. For example, you could theoretically implement a stack like this (although I don't know why you would):

l = [1,2,3]
l.insert(0, 1)
l.pop(0)

...and I haven't gotten into using linked lists to implement a stack.

Java AES encryption and decryption

You state that you want to encrypt/decrypt a password. I'm not sure exactly of what your specific use case is but, generally, passwords are not stored in a form where they can be decrypted. General practice is to salt the password and use suitably powerful one-way hash (such as PBKDF2).

Take a look at the following link for more information.

http://crackstation.net/hashing-security.htm

What is the difference between properties and attributes in HTML?

Difference HTML properties and attributes:

Let's first look at the definitions of these words before evaluating what the difference is in HTML:

English definition:

  • Attributes are referring to additional information of an object.
  • Properties are describing the characteristics of an object.

In HTML context:

When the browser parses the HTML, it creates a tree data structure wich basically is an in memory representation of the HTML. It the tree data structure contains nodes which are HTML elements and text. Attributes and properties relate to this is the following manner:

  • Attributes are additional information which we can put in the HTML to initialize certain DOM properties.
  • Properties are formed when the browser parses the HTML and generates the DOM. Each of the elements in the DOM have their own set of properties which are all set by the browser. Some of these properties can have their initial value set by HTML attributes. Whenever a DOM property changes which has influence on the rendered page, the page will be immediately re rendered

It is also important to realize that the mapping of these properties is not 1 to 1. In other words, not every attribute which we give on an HTML element will have a similar named DOM property.

Furthermore have different DOM elements different properties. For example, an <input> element has a value property which is not present on a <div> property.

Example:

Let's take the following HTML document:

 <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">  <!-- charset is a attribute -->
  <meta name="viewport" content="width=device-width"> <!-- name and content are attributes -->
  <title>JS Bin</title>
</head>
<body>
<div id="foo" class="bar foobar">hi</div> <!-- id and class are attributes -->
</body>
</html>

Then we inspect the <div>, in the JS console:

 console.dir(document.getElementById('foo'));

We see the following DOM properties (chrome devtools, not all properties shown):

html properties and attributes

  • We can see that the attribute id in the HTML is now also a id property in the DOM. The id has been initialized by the HTML (although we could change it with javascript).
  • We can see that the class attribute in the HTML has no corresponding class property (class is reserved keyword in JS). But actually 2 properties, classList and className.

Download File Using jQuery

  • Using jQuery function

        var valFileDownloadPath = 'http//:'+'your url';
    
       window.open(valFileDownloadPath , '_blank');
    

Get the second largest number in a list in linear time

This can be done in [N + log(N) - 2] time, which is slightly better than the loose upper bound of 2N (which can be thought of O(N) too).

The trick is to use binary recursive calls and "tennis tournament" algorithm. The winner (the largest number) will emerge after all the 'matches' (takes N-1 time), but if we record the 'players' of all the matches, and among them, group all the players that the winner has beaten, the second largest number will be the largest number in this group, i.e. the 'losers' group.

The size of this 'losers' group is log(N), and again, we can revoke the binary recursive calls to find the largest among the losers, which will take [log(N) - 1] time. Actually, we can just linearly scan the losers group to get the answer too, the time budget is the same.

Below is a sample python code:

def largest(L):
    global paris
    if len(L) == 1:
        return L[0]
    else:
        left = largest(L[:len(L)//2])
        right = largest(L[len(L)//2:])
        pairs.append((left, right))
        return max(left, right)

def second_largest(L):
    global pairs
    biggest = largest(L)
    second_L = [min(item) for item in pairs if biggest in item]

    return biggest, largest(second_L)  



if __name__ == "__main__":
    pairs = []
    # test array
    L = [2,-2,10,5,4,3,1,2,90,-98,53,45,23,56,432]    

    if len(L) == 0:
        first, second = None, None
    elif len(L) == 1:
        first, second = L[0], None
    else:
        first, second = second_largest(L)

    print('The largest number is: ' + str(first))
    print('The 2nd largest number is: ' + str(second))

Callback when DOM is loaded in react.js

In modern browsers, it should be like

try() {
     if (!$("#element").size()) {
       window.requestAnimationFrame(try);
     } else {
       // do your stuff
     }
};

componentDidMount(){
     this.try();
}

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

  1. Click Properties in a project.
  2. Go to Java Build Path.
  3. Click Add Library.
  4. Click Next on JRE System Library. Select the one you need if not selected by default.
  5. Click Finish.

You're done!

pass JSON to HTTP POST Request

I think the following should work:

// fire request
request({
    url: url,
    method: "POST",
    json: requestData
}, ...

In this case, the Content-type: application/json header is automatically added.

UILabel Align Text to center

In Swift 4.2 and Xcode 10

let lbl = UILabel(frame: CGRect(x: 10, y: 50, width: 230, height: 21))
lbl.textAlignment = .center //For center alignment
lbl.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl.textColor = .white
lbl.backgroundColor = .lightGray//If required
lbl.font = UIFont.systemFont(ofSize: 17)

 //To display multiple lines in label
lbl.numberOfLines = 0
lbl.lineBreakMode = .byWordWrapping

lbl.sizeToFit()//If required
yourView.addSubview(lbl)

How do I get monitor resolution in Python?

You could use PyMouse. To get the screen size just use the screen_size() attribute:

from pymouse import PyMouse
m = PyMouse()
a = m.screen_size()

a will return a tuple, (X, Y), where X is the horizontal position and Y is the vertical position.

Link to function in documentation.

Can I extend a class using more than 1 class in PHP?

EDIT: 2020 PHP 5.4+ and 7+

As of PHP 5.4.0 there are "Traits" - you can use more traits in one class, so the final deciding point would be whether you want really an inheritance or you just need some "feature"(trait). Trait is, vaguely said, an already implemented interface that is meant to be just used.


Currently accepted answer by @Franck will work but it is not in fact multiple inheritance but a child instance of class defined out of scope, also there is the `__call()` shorthand - consider using just `$this->childInstance->method(args)` anywhere you need ExternalClass class method in "extended" class.

Exact answer

No you can't, respectively, not really, as manual of extends keyword says:

An extended class is always dependent on a single base class, that is, multiple inheritance is not supported.

Real answer

However as @adam suggested correctly this does NOT forbids you to use multiple hierarchal inheritance.

You CAN extend one class, with another and another with another and so on...

So pretty simple example on this would be:

class firstInheritance{}
class secondInheritance extends firstInheritance{}
class someFinalClass extends secondInheritance{}
//...and so on...

Important note

As you might have noticed, you can only do multiple(2+) intehritance by hierarchy if you have control over all classes included in the process - that means, you can't apply this solution e.g. with built-in classes or with classes you simply can't edit - if you want to do that, you are left with the @Franck solution - child instances.

...And finally example with some output:

class A{
  function a_hi(){
    echo "I am a of A".PHP_EOL."<br>".PHP_EOL;  
  }
}

class B extends A{
  function b_hi(){
    echo "I am b of B".PHP_EOL."<br>".PHP_EOL;  
  }
}

class C extends B{
  function c_hi(){
    echo "I am c of C".PHP_EOL."<br>".PHP_EOL;  
  }
}

$myTestInstance = new C();

$myTestInstance->a_hi();
$myTestInstance->b_hi();
$myTestInstance->c_hi();

Which outputs

I am a of A 
I am b of B 
I am c of C 

Proper way to initialize a C# dictionary with values?

You can initialize a Dictionary (and other collections) inline. Each member is contained with braces:

Dictionary<int, StudentName> students = new Dictionary<int, StudentName>
{
    { 111, new StudentName { FirstName = "Sachin", LastName = "Karnik", ID = 211 } },
    { 112, new StudentName { FirstName = "Dina", LastName = "Salimzianova", ID = 317 } },
    { 113, new StudentName { FirstName = "Andy", LastName = "Ruth", ID = 198 } }
};

See Microsoft Docs for details.

What is the difference between field, variable, attribute, and property in Java POJOs?

Variables are comprised of fields and non-fields.

Fields can be either:

  1. Static fields or
  2. non-static fields also called instantiations e.g. x = F()

Non-fields can be either:

  1. local variables, the analog of fields but inside a methods rather than outside all of them, or
  2. parameters e.g. y in x = f(y)

In conclusion, the key distinction between variables is whether they are fields or non-fields, meaning whether they are inside a methods or outside all methods.

Basic Example (excuse me for my syntax, I am just a beginner)

Class {    
    //fields    

    method1 {              
         //non-fields    

    }    
}