Programs & Examples On #Mysqlbinlog

How do I mock an open used in a with statement (using the Mock framework in Python)?

The way to do this has changed in mock 0.7.0 which finally supports mocking the python protocol methods (magic methods), particularly using the MagicMock:

http://www.voidspace.org.uk/python/mock/magicmock.html

An example of mocking open as a context manager (from the examples page in the mock documentation):

>>> open_name = '%s.open' % __name__
>>> with patch(open_name, create=True) as mock_open:
...     mock_open.return_value = MagicMock(spec=file)
...
...     with open('/some/path', 'w') as f:
...         f.write('something')
...
<mock.Mock object at 0x...>
>>> file_handle = mock_open.return_value.__enter__.return_value
>>> file_handle.write.assert_called_with('something')

Force IE compatibility mode off using tags

There is the "edge" mode.

<html>
   <head>
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <title>My Web Page</title>
   </head>
   <body>
      <p>Content goes here.</p>
   </body>
</html>

From the linked MSDN page:

Edge mode tells Windows Internet Explorer to display content in the highest mode available, which actually breaks the “lock-in” paradigm. With Internet Explorer 8, this is equivalent to IE8 mode. If a (hypothetical) future release of Internet Explorer supported a higher compatibility mode, pages set to Edge mode would appear in the highest mode supported by that version; however, those same pages would still appear in IE8 mode when viewed with Internet Explorer 8.

However, "edge" mode is not encouraged in production use:

It is recommended that Web developers restrict their use of Edge mode to test pages and other non-production uses because of the possible unexpected results of rendering page content in future versions of Windows Internet Explorer.

I honestly don't entirely understand why. But according to this, the best way to go at the moment is using IE=8.

How do I fix an "Invalid license data. Reinstall is required." error in Visual C# 2010 Express?

I have faced this problem when installing the Visual studio 2010 - C# express using the local administrator account, then trying to register the application using another account that doesn't have Admin privileges, due to corporate polices this account can’t edit in the Registry by any means, so suddenly that’s how I figured out how to solve this issue I open VS 2010 as a local administrator then entered the registration key, and it is worked , I don’t understand how do that Microsoft itself didn’t mention this solution or even try hard to investigate or solve this issue

NodeJs : TypeError: require(...) is not a function

Just wrap in Arrow function where you requiring the files

HTTPS connections over proxy servers

as far as i can remember, you need to use a HTTP CONNECT query on the proxy. this will convert the request connection to a transparent TCP/IP tunnel.

so you need to know if the proxy server you use support this protocol.

Detect change to ngModel on a select tag (Angular 2)

Update:

Separate the event and property bindings:

<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
    console.log(newValue);
    this.selectedItem = newValue;  // don't forget to update the model here
    // ... do other stuff here ...
}

You could also use

<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">

and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.


Old answer, before they fixed a bug in beta.1:

Create a local template variable and attach a (change) event:

<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">

plunker

See also How can I get new selection in "select" in Angular 2?

How do I change the default index page in Apache?

You can also set DirectoryIndex in apache's httpd.conf file.

CentOS keeps this file in /etc/httpd/conf/httpd.conf Debian: /etc/apache2/apache2.conf

Open the file in your text editor and find the line starting with DirectoryIndex

To load landing.html as a default (but index.html if that's not found) change this line to read:

DirectoryIndex  landing.html index.html

appending array to FormData and send via AJAX

add all type inputs to FormData

const formData = new FormData();
for (let key in form) {
    Array.isArray(form[key])
        ? form[key].forEach(value => formData.append(key + '[]', value))
        : formData.append(key, form[key]) ;
}

Why aren't python nested functions called closures?

def nested1(num1): 
    print "nested1 has",num1
    def nested2(num2):
        print "nested2 has",num2,"and it can reach to",num1
        return num1+num2    #num1 referenced for reading here
    return nested2

Gives:

In [17]: my_func=nested1(8)
nested1 has 8

In [21]: my_func(5)
nested2 has 5 and it can reach to 8
Out[21]: 13

This is an example of what a closure is and how it can be used.

How do I debug Windows services in Visual Studio?

I use a great Nuget package called ServiceProcess.Helpers.

And I quote...

It helps windows services debugging by creating a play/stop/pause UI when running with a debugger attached, but also allows the service to be installed and run by the windows server environment.

All this with one line of code.

http://windowsservicehelper.codeplex.com/

Once installed and wired in all you need to do is set your windows service project as the start-up project and click start on your debugger.

Checking for an empty file in C++

if (nfile.eof()) // Prompt data from the Priming read:
    nfile >> CODE >> QTY >> PRICE;
else
{
    /*used to check that the file is not empty*/
    ofile << "empty file!!" << endl;
    return 1;
}

How to import a SQL Server .bak file into MySQL?

SQL Server databases are very Microsoft proprietary. Two options I can think of are:

  1. Dump the database in CSV, XML or similar format that you'd then load into MySQL.

  2. Setup ODBC connection to MySQL and then using DTS transport the data. As Charles Graham has suggested, you may need to build the tables before doing this. But that's as easy as a cut and paste from SQL Enterprise Manager windows to the corresponding MySQL window.

Amazon Linux: apt-get: command not found

Try to install your application by using yum command yum install application_name

Android - Start service on boot

I have found a way to make your application run well when the device reboots, please follow the steps below to be successful.

AndroidManifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.saltriver" android:versionCode="1" android:versionName="1.0">
<uses-permission 
android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name=".UIBootReceiver" android:enabled="true" 
    android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>
     <service android:name=".class_Service" />
</application>

UIBootReceiver

public class UIBootReceiver extends BroadcastReceiver {

private static final String TAG = "UIBootReceiver";
@Override

    public void onReceive(Context context, Intent arg1)
    {
        Toast.makeText(context, "started", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(context,class_Service.class);
        context.startService(intent);
    }
  }

This is asking permission to not need to manage battery saving for this app so you can run in the background stably.

Declare this code in onCreate () of MainActivity class:

   Intent myIntent = new Intent();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        myIntent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        myIntent.setData(Uri.parse("package:" + 
   DeviceMovingSpeed.this.getPackageName()));
    }
    startActivity(myIntent);

Usage of MySQL's "IF EXISTS"

You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.

Turn the EXISTS clause into a subquery instead within an IF function

SELECT IF( EXISTS(
             SELECT *
             FROM gdata_calendars
             WHERE `group` =  ? AND id = ?), 1, 0)

In fact, booleans are returned as 1 or 0

SELECT EXISTS(
         SELECT *
         FROM gdata_calendars
         WHERE `group` =  ? AND id = ?)

Default property value in React component using TypeScript

From a comment by @pamelus on the accepted answer:

You either have to make all interface properties optional (bad) or specify default value also for all required fields (unnecessary boilerplate) or avoid specifying type on defaultProps.

Actually you can use Typescript's interface inheritance. The resulting code is only a little bit more verbose.

interface OptionalGoogleAdsProps {
    format?: string;
    className?: string;
    style?: any;
    scriptSrc?: string
}

interface GoogleAdsProps extends OptionalGoogleAdsProps {
    client: string;
    slot: string;
}


/**
 * Inspired by https://github.com/wonism/react-google-ads/blob/master/src/google-ads.js
 */
export default class GoogleAds extends React.Component<GoogleAdsProps, void> {
    public static defaultProps: OptionalGoogleAdsProps = {
        format: "auto",
        style: { display: 'block' },
        scriptSrc: "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
    };

How to run an application as "run as administrator" from the command prompt?

See this TechNet article: Runas command documentation

From a command prompt:

C:\> runas /user:<localmachinename>\administrator cmd

Or, if you're connected to a domain:

C:\> runas /user:<DomainName>\<AdministratorAccountName> cmd

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

Actually, the solutions is to open the php.ini file edit the include_path line and either completely change it to

include_path='.:/usr/share/php:/usr/share/pear' 

or append the

'.:/usr/share/php:/usr/share/pear' 

to the current value of include_path.

It is further explained in : http://pear.php.net/manual/en/installation.checking.php#installation.checking.cli.phpdir

How can I use a reportviewer control in an asp.net mvc 3 razor view?

It is possible to get an SSRS report to appear on an MVC page without using iFrames or an aspx page.

The bulk of the work is explained here:

http://geekswithblogs.net/stun/archive/2010/02/26/executing-reporting-services-web-service-from-asp-net-mvc-using-wcf-add-service-reference.aspx

The link explains how to create a web service and MVC action method that will allow you to call the reporting service and render result of the web service as an Excel file. With a small change to the code in the example you can render it as HTML.

All you need to do then is use a button to call a javascript function that makes an AJAX call to your MVC action which returns the HTML of the report. When the AJAX call returns with the HTML just replace a div with this HTML.

We use AngularJS so my example below is in that format, but it could be any javascript function

$scope.getReport = function()
{
    $http({
        method: "POST",
        url: "Report/ExportReport",
        data: 
                [
                    { Name: 'DateFrom', Value: $scope.dateFrom },
                    { Name: 'DateTo', Value: $scope.dateTo },
                    { Name: 'LocationsCSV', Value: $scope.locationCSV }
                ]

    })
    .success(function (serverData)
    {
        $("#ReportDiv").html(serverData);
    });

};

And the Action Method - mainly taken from the above link...

    [System.Web.Mvc.HttpPost]
    public FileContentResult ExportReport([FromBody]List<ReportParameterModel> parameters)
    {
         byte[] output;
         string extension, mimeType, encoding;
         string reportName = "/Reports/DummyReport";
         ReportService.Warning[] warnings;
         string[] ids;

     ReportExporter.Export(
            "ReportExecutionServiceSoap" 
            new NetworkCredential("username", "password", "domain"),
            reportName,
            parameters.ToArray(),
            ExportFormat.HTML4,
            out output,
            out extension,
            out mimeType,
            out encoding,
            out warnings,
            out ids
        );

        //-------------------------------------------------------------
        // Set HTTP Response Header to show download dialog popup
        //-------------------------------------------------------------
        Response.AddHeader("content-disposition", string.Format("attachment;filename=GeneratedExcelFile{0:yyyyMMdd}.{1}", DateTime.Today, extension));
        return new FileContentResult(output, mimeType);
    }

So the result is that you get to pass parameters to an SSRS reporting server which returns a report which you render as HTML. Everything appears on the one page. This is the best solution I could find

How to display Base64 images in HTML?

put base64()

_x000D_
_x000D_
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0CAIAAABEtEjdAAAACXBIWXMAAA7zAAAO8wEcU5k6AAAAEXRFWHRUaXRsZQBQREYgQ3JlYXRvckFevCgAAAATdEVYdEF1dGhvcgBQREYgVG9vbHMgQUcbz3cwAAAALXpUWHREZXNjcmlwdGlvbgAACJnLKCkpsNLXLy8v1ytISdMtyc/PKdZLzs8FAG6fCPGXryy4AAPW0ElEQVR42uy9Z5djV3Yl+ByAB+9deG8yMzLSMA1tkeWk6pJKKmla06MlafRB3/UX9BP0eTSj1RpperpLKpXKscgii0xDZpLpIyMiM7yPQCCAgLfPzr73AUikYVVR00sqUvcwVxABIICHB2Dfc/fZZx/eNE2OBQsWLFh8uUJgp4AFCxYsGLizYMGCBQsG7ixYsGDBgoE7CxYsWLBg4M6CBQsWLBi4s2DBggUDdxYsWLBgwcCdBQsWLFgwcGfBggULFgzcWbBgwYIFA3cWLFiwYODOggULFiwYuLNgwYIFCwbuLFiwYMGCgTsLFixYsGDgzoIFCxYsGLizYMGCBQN3FixYsGDBwJ0FCxYsWDBwZ8GCBQsWDNxZsGDBggUDdxYsWLBg4M6CBQsWLBi4s2DBggULBu4sWLBgwYKBOwsWLFiwYODOggULFiwYuLNgwYIFA3cWLFiwYMHAnQULFixYMHBnwYIFCxYM3FmwYMGCBQN3FixYsGDgzoIFCxYsGLizYMGCBQsG7ixYsGDBgoE7CxYsWLBg4M6CBQsWLBi4s2DBggUDdxYsWLBgwcCdBQsWLFgwcGfBggULFgzcWbBgwYIFA3cWLFiwYODOggULFiwYuLNgwYIFCwbuLFiwYMHi3zokdgpY/FuG/oLrjK4Uw+hc4lv315/LRfjnHsHsuoftcx0P/8Jrzc+4jOMRtBclRoLJvmAsGLizYPE0NAodTOe7LrdvE1/0R93Aavz/O5AXgTXf/tV8Fv6F5za7xnOLhMneXRa/AcGbJvsosvi3C/MzE2fjV68CvxI4+c8NrDynfs7MXnj+qF74pNbrEdlbzoKBOwuG9//KO3Tf9wlt8q9/ev7FsG7dXfocCwELFv9+wWgZFr95gG4+jZj85/rzz5us2D7XQ/DmZyO7yRCfBQN3Fv/Rd4yfAaKfdQ3/6yIm/znR1DQ/J/6an3EMJoNyFgzcWfyHTtnBRQv8Z+Hj8+DIW9y18auy6s5ffj51L99+SJP/9f/g107PGdazYODO4j9IGJ8NwDz/QgB/BtZ/Vd3V/JytG60nNZ7DYcN88YbC9vnwnQULBu4svmxJOo02cJPABc0E+hpmG8itO9DbeKF1TRfKc1YB06R/a3Ql2fxnpu0muaNp0IdrPSJn6hwv0T82n1tY+ObzGwfT1Dh6SO3lxTBNXSCPiOsIR28YTxYkXngW/s2uI2SYz+LfK5hahsW/aaifAXyarlkoL/K8wAtdH9DOUkF/FZ5K5+nyYX2GBfqAPK9a8NuGa6NLjai3wd1aKSwwtzW7l6MWYwTwFgR6hcF3HYxu6KLgemoBo/c1DIMcBw5eFAD3RmdN0XWHyPInFgzcWXyJQtM0viusjxl+6vyz2b1FqYiC+BRqI/nWdICmYMitnFzkhDZMA0sFke/gq6FTWBYI9Bs1DZCq0sAFC3ZxL6fTics4EjsNwDBnpfbNJidJFMrN9qPwLemLQZcOod23pJt4UdhIWFsQ63UJ1hrQtToYZFtC7mKR+IJpbTtYsGDgzuLLzdV05eFt1DO6eByd0iFdaKhKTzJ85Mi6oWpNTVNqtRruCbxuNtV6va40gekEu7VmQVGUZrOJx5IkyWazWc8CQG/SsK7Hrw6HAz9lIYBfRZvNulKWXaJNslYjySZw9vZBd/gc24s6Wk1B1VQAvSiypiUWDNxZ/IfC9A75bj5dNgXxoaumbogSxXTKihiqWqtVqtWq0mgUsgqSY4A+MB0ZuSCaokiwF6htAbTN5hAESeAlkYTk9ds5kpULLXaFPKbwJK+2lg1VVer1RqNBMvGGBz8B+vhVaaqaoSsktIaiOJ1up9tlkxx4XDwdLjudLldAtX7lke/zrWchFD9+7TgW6ISQAdbz0vNuBa1ShCAwzz4WDNxZ/Cah87MfoM/gHICYHe6iU00loVjceYd413FXQ1MqFaB5pVjIAdMB4gBuECn46fc4ZVkGhguiwYuWLZjB6SqBbItCMSnJTdQuFqPS3gdYdwC+k8fXBAvxAcG4gNeCw8NPkmi7WsuATqFfJLQLeUDcQTcB99VGvVrBPqGGBUCjqwHAnaT4suxBuH0ul1uw2w1VF/Dgkv3pHQpniuYzZ4mBOwsG7iy+wOBuPsc14xqwKKIuck2lRqC8ivQc/0jKrDZ8Pq/ssAEtfT6PwyUTFKYENieVwMdzkK80arrWaDarpXKhXC4eHBzoNEh2ziGVBsciI6HeP8yTB1QUJPVerxc/cRm8DdYJi64BFw909vl8yWQyEom47IROwaHq0PHwYG9ku0MGQyN7vXhUAtat9NzaByDr9+qNRqVSK5VK1Uodj6kjTzc5t9uL1cjr9fu8AZvLxVklAZPTRf3Z5e1FJ4cFCwbuLL4Y4N4J4C8gtU4DwFo/KIAxB8oDiP1+bzDkd/v9nN1GZTEGzcrh8quYzUaz3sD9d3ZvVCqlo6PD9FGqXC40mkDVQrFY4AWTgHWDVE3B0ABbkUQDynNVrkHDegpgukh5nHK5jF9xB0A58m/c2mJ1uENcQMJOrtQB5lhgfE7Z5fJ4w+FoNB4PBsOy0+V2u32+AH4K2jDJ90kNlspgNINTDVRac4VCuVQtFEpYPvCwfl/Q7/cju5ciLqEd7FPEgoE7i/+JqPzMG/55705YDqAX5Ilgx7mOGBEQTFkRvXU3qGDafUDIY1WTkxxcVatmq8fpUiFX0RqmW/YhsXX0V/0Br+TzcrxGOBlIF034MjY5Qctm9ra213Z21/cPd/P541qd8DPp7Gy9jnRbtwF3bU7Cm0gOu01G7gs0pul/DWAai8Wi0ShyZ87lQE5dLBZJkq5rQHbsBpBPA7sJiAuCpZ/Bz0qtCsRPF/cB2X5PSLa7eY1XGyrodggzRVMz1JqhVjijbhc1l8wHgq6A39c/RfYHHo8rEvZHo5FQwIdUnxPAFoGQcXCmzCmiWlRyx9VsJl8p1W3KqM/njiSCgbjEeaEKwvmsc4KC1B7HYZgSLzhxslRaHSCEUFuNyeMguCrPNSRk/4R7ElpPYbjJmTbaak77c+9s91vMd/d8WZeZNJOBO4svHbb/OkSARpnnTj8RmBGelAsNodNGBOk3pOOE7DaRkDtcpmroPAqikpszbWpVKx6Xq8Xa7va2XQKG28MhfyTs5X1ODuwzcNxxTPDF1Bvl6nE2nzrMHBwcHudKa2vrtYZWKVNyW4GMUgRSkww6OkAB2hcKRTxuv8PhlMHayG5JtBMuhagedaA2yByXy0XEKrLNKpAiWum5ywk4xj0hg+FoMYBKHE3sJPBkxUbDCSJGlrF0cLqmKyoKAKi4FnM5pVFp1spKs9qs15RGVcf1nHFU2IOuBkJMCHZUtely2qPRMDB+aGAw4Pci1Y8EQzanh6xtJASuqteL5XT6KHtcrDcNtyeQ6OmPxhKSbOPtdFXE2SXgDVTXsVuxO3wWEPOk19akHbcG7Yoi7BM1NZZasG7p9H+5PId/vqGXbSAYuLP4MibubeD4zC+8otEqI9+6lsIK/un0oUzak88T8Tcwx5Kdm3WAk6ma+Ux5Zzt1nC3JdmcgEBgfG7I7kWjqnIg7VMk/rgYdTKNR290/WFx4tLK8dZTO1xqm2hQ0FTR1xO0Mef0xlxwkjUK8zSl7oFcJDtWAz6BcgO9QxWChgVYFEI9dBCAbXAc+wLTCicsASgMcic1GDgyKF/x0OCRcj7xYsgqlBq2k0moraqNkATBlgb4UkkljaTOanIGfioryKRYZRcMrRYMrdg/1ah2bgVpToYuKWq/WiqV8sXBcrRY1BeR72Wbn3E7B55MjUd/gQHJkdDAej9qdJU4A0Hs5062V+KOjRi7brNVMrycYCAX9AbckQ3OpC7JJGrzI5BAvPfuC1W2L12uarQau1vtC8Bo7I4W+KbgcetHb3oXpz/gxMKqfgTuLLwu4Gy/+zj8B8KdCb19jWjDCQzwOeCD31SkrDR7burlZM4vFci2rZrPpfCHj9shDw8megSiYA86sgX8w1apuKEhzkeFu7+0uLi5ub29njyhX3gSQ8Xabyy67RcEJTUkgGA8Foz29Q6FgTBQdOrhsUYIM0RU6hqKQ4rhInl8jOhOUPSnYSRSvDdoaCuQzqACR3Bm/GUarJwk/UXaVHALdbLTkkVa9FtySRAU1LR8Z8P68Dg6KpwQUcnxdAwsFkaYNrak4ZkVRRZvYANAjCdegdzQb1drx8XGxkMXCoCrlSu0YBYJKLavrVZvdxH4gGFJARvX1Do6NTfX3jUj2AKcJWtMs5atH6eNcroADDvmDIRqCx8MpKsn6hbaqsu2JYPV64WhMQmc1DbISqHRCYejp9/RpA7XnnXYYuDNwZ/FlAffPHF7xwvzdmlkKAQhvWEJG0VIZilyrb1NXuEIeIpd6Hrz4cb7XNdI/EHYmLX6gyIkFTqwBfY4LqWwunz4qZdKV3d38/n5BU5CMe2VuiBQ2nQ7Q1h6vCz/dXpfsROVTsDsdbg9ELxIMBdCrRPNxCX2qlsEArdyCjhZstOHIklqS9QpaFXJrqwPWaXe2nQBE0hOl63QZIDVVof2KO+VN0gFLlgHDuhvfupIk8A67jOvB4ND2VyxxWNsMwteLNfIrTg9ZArBlQSmCnCKw/LpKKseNRimfz2SyB4X8cb1eVUzQULrTKURjgcH+2OBgvDcZDQZ8AuFtZMKhF7W9neP0QZ7nZK/L3z86jBICLztaPvMdfLfRAoipmeSNMemaDUYHzy0KTy3SAj1LfOsyA3cG7iy+rKF3jZ"></img>
_x000D_
_x000D_
_x000D_

in Javascript

var id=document.getElementById("image");

id.src=base64Url;

PHP Get all subdirectories of a given directory

<?php
    /*this will do what you asked for, it only returns the subdirectory names in a given
      path, and you can make hyperlinks and use them:
    */

    $yourStartingPath = "photos\\";
    $iterator = new RecursiveIteratorIterator( 
        new RecursiveDirectoryIterator($yourStartingPath),  
        RecursiveIteratorIterator::SELF_FIRST);

    foreach($iterator as $file) { 
        if($file->isDir()) { 
            $path = strtoupper($file->getRealpath()) ; 
            $path2 = PHP_EOL;
            $path3 = $path.$path2;

            $result = end(explode('/', $path3)); 

            echo "<br />". basename($result );
        } 
    } 

    /* best regards,
        Sanaan Barzinji
        Erbil
    */
?>

What does %~dp0 mean, and how does it work?

Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0 first, then cd %~dp0. This will change the directory to the batch file's drive, then change to its folder.

Alternatively, for #oneLinerLovers, as @Omni pointed out in the comments cd /d %~dp0 will change both the drive and directory :)

Hope this helps someone.

Create a folder and sub folder in Excel VBA

For those looking for a cross-platform way that works on both Windows and Mac, the following works:

Sub CreateDir(strPath As String)
    Dim elm As Variant
    Dim strCheckPath As String

    strCheckPath = ""
    For Each elm In Split(strPath, Application.PathSeparator)
        strCheckPath = strCheckPath & elm & Application.PathSeparator
        If (Len(strCheckPath) > 1 And Not FolderExists(strCheckPath)) Then
            MkDir strCheckPath
        End If
    Next
End Sub

Function FolderExists(FolderPath As String) As Boolean
     FolderExists = True
     On Error Resume Next
     ChDir FolderPath
     If Err <> 0 Then FolderExists = False
     On Error GoTo 0
End Function

How can I stream webcam video with C#?

The usual API for this is DirectShow.

You can use P/Invoke to import the C++ APIs, but I think there are already a few projects out there that have done this.

http://channel9.msdn.com/forums/TechOff/93476-Programatically-Using-A-Webcam-In-C/

http://www.codeproject.com/KB/directx/DirXVidStrm.aspx

To get the streaming part, you probably want to use DirectShow to apply a compression codec to reduce lag, then you can get a Stream and transmit it. You could consider using multicast to reduce network load.

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

WAMP Cannot access on local network 403 Forbidden

For those who may be running WAMP 3.1.4 with Apache 2.4.35 on Windows 10 (64-bit)

If you're having issues with external devices connecting to your localhost, and receiving a 403 Forbidden error, it may be an issue with your httpd.conf and the httpd-vhosts.conf files and the "Require local" line they both have within them.

[Before] httpd-vhosts.conf

<VirtualHost *:80>
 ServerName localhost
 ServerAlias localhost
 DocumentRoot "${INSTALL_DIR}/www"
 <Directory "${INSTALL_DIR}/www/">
   Options +Indexes +Includes +FollowSymLinks +MultiViews
   AllowOverride All
   Require local     <--- This is the offending line.
 </Directory>
</VirtualHost>

[After] httpd-vhosts.conf

<VirtualHost *:80>
 ServerName localhost
 ServerAlias localhost
 DocumentRoot "${INSTALL_DIR}/www"
 <Directory "${INSTALL_DIR}/www/">
   Options +Indexes +Includes +FollowSymLinks +MultiViews
   AllowOverride All
 </Directory>
</VirtualHost>

Additionally, you'll need to update your httpd.conf file as follows:

[Before] httpd.conf

DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
#   onlineoffline tag - don't remove

    Require local  #<--- This is the offending line.
</Directory>

[After] httpd.conf

DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
#   onlineoffline tag - don't remove

#   Require local
</Directory>

Make sure to restart your WAMP server via (System tray at bottom-right of screen --> left-click WAMP icon --> "Restart all Services").

Then refresh your machine's browser on localhost to ensure you've still got proper connectivity there, and then refresh your other external devices that you were previously attempting to connect.

Disclaimer: If you're in a corporate setting, this is untested from a security perspective; please ensure you're keenly aware of your local development environment's access protocols before implementing any sweeping changes.

Python integer division yields float

Hope it might help someone instantly.

Behavior of Division Operator in Python 2.7 and Python 3

In Python 2.7: By default, division operator will return integer output.

to get the result in double multiple 1.0 to "dividend or divisor"

100/35 => 2 #(Expected is 2.857142857142857)
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857

In Python 3

// => used for integer output
/ => used for double output

100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0    # floating-point result if divsor or dividend real

Get position/offset of element relative to a parent container?

in pure js just use offsetLeft and offsetTop properties.
Example fiddle: http://jsfiddle.net/WKZ8P/

_x000D_
_x000D_
var elm = document.querySelector('span');_x000D_
console.log(elm.offsetLeft, elm.offsetTop);
_x000D_
p   { position:relative; left:10px; top:85px; border:1px solid blue; }_x000D_
span{ position:relative; left:30px; top:35px; border:1px solid red; }
_x000D_
<p>_x000D_
    <span>paragraph</span>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Testing pointers for validity (C/C++)

AFAIK there is no way. You should try to avoid this situation by always setting pointers to NULL after freeing memory.

How to change the data type of a column without dropping the column with query?

it's simple! just type bellow query

alter table table_Name alter column column_name datatype

alter table Message alter column message nvarchar(1024);

it will work happy programming

what is difference between success and .done() method of $.ajax

In short, decoupling success callback function from the ajax function so later you can add your own handlers without modifying the original code (observer pattern).

Please find more detailed information from here: https://stackoverflow.com/a/14754681/1049184

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

How to name and retrieve a stash by name in git?

git stash save is deprecated as of 2.15.x/2.16, instead you can use git stash push -m "message"

You can use it like this:

git stash push -m "message"

where "message" is your note for that stash.

In order to retrieve the stash you can use: git stash list. This will output a list like this, for example:

stash@{0}: On develop: perf-spike
stash@{1}: On develop: node v10

Then you simply use apply giving it the stash@{index}:

git stash apply stash@{1}

References git stash man page

Prevent any form of page refresh using jQuery/Javascript

Although its not a good idea to disable F5 key you can do it in JQuery as below.

<script type="text/javascript">
function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); };

$(document).ready(function(){
     $(document).on("keydown", disableF5);
});
</script>

Hope this will help!

How do I get the max and min values from a set of numbers entered?

This is what I did and it works try and play around with it. It calculates total,avarage,minimum and maximum.

public static void main(String[] args) {
   int[] score= {56,90,89,99,59,67};
   double avg;
   int sum=0;
   int maxValue=0;
   int minValue=100;

   for(int i=0;i<6;i++){
       sum=sum+score[i];
   if(score[i]<minValue){
    minValue=score[i];
   }
   if(score[i]>maxValue){
    maxValue=score[i];
   }
   }
   avg=sum/6.0;
System.out.print("Max: "+maxValue+"," +" Min: "+minValue+","+" Avarage: "+avg+","+" Sum: "+sum);}

 }

How can I create persistent cookies in ASP.NET?

You need to add this as the last line...

HttpContext.Current.Response.Cookies.Add(userid);

When you need to read the value of the cookie, you'd use a method similar to this:

    string cookieUserID= String.Empty;

    try
    {
        if (HttpContext.Current.Request.Cookies["userid"] != null)
        {
            cookieUserID = HttpContext.Current.Request.Cookies["userid"];
        }
    }
    catch (Exception ex)
    {
       //handle error
    }

    return cookieUserID;

Import Python Script Into Another?

It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named __init__.py in the same directory.

How to build an android library with Android Studio and gradle?

Gradle Build Tools 2.2.0+ - Everything just works

This is the correct way to do it

In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild and pointing ndkBuild path argument at an Android.mk or change ndkBuild to cmake and point the path argument at a CMakeLists.txt build script.

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 19

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'x86'
        }

        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11'
                arguments '-DANDROID_TOOLCHAIN=clang',
                        '-DANDROID_PLATFORM=android-19',
                        '-DANDROID_STL=gnustl_static',
                        '-DANDROID_ARM_NEON=TRUE',
                        '-DANDROID_CPP_FEATURES=exceptions rtti'
            }
        }
    }

    externalNativeBuild {
        cmake {
             path 'src/main/jni/CMakeLists.txt'
        }
        //ndkBuild {
        //   path 'src/main/jni/Android.mk'
        //}
    }
}

For much more detail check Google's page on adding native code.

After this is setup correctly you can ./gradlew installDebug and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.

Android emulator failed to allocate memory 8

For Skin remove No Skin and add some skin into it

enter image description here

jQuery Toggle Text?

$(function() {
    $("#show-background").click(function () {
        $("#content-area").animate({opacity: 'toggle'}, 'slow'); 
    });

    var text = $('#show-background').text();
    $('#show-background').text(
        text == "Show Background" ? "Show Text" : "Show Background");
});

Toggle hides or shows elements. You could achieve the same effect using toggle by having 2 links and toggling them when either is clicked.

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

you have to add fulltext index on specific fields you want to search.

ALTER TABLE news ADD FULLTEXT(headline, story);

where "news" is your table and "headline, story" fields you wont to enable for fulltext search

PageSpeed Insights 99/100 because of Google Analytics - How can I cache GA?

You can minify all your scripts in page, including analytics.js using:

Remember to minify the files before using it. Otherwise it will consume more processing time.

What is a simple command line program or script to backup SQL server databases?

I found this on a Microsoft Support page http://support.microsoft.com/kb/2019698.

It works great! And since it came from Microsoft, I feel like it's pretty legit.

Basically there are two steps.

  1. Create a stored procedure in your master db. See msft link or if it's broken try here: http://pastebin.com/svRLkqnq
  2. Schedule the backup from your task scheduler. You might want to put into a .bat or .cmd file first and then schedule that file.

    sqlcmd -S YOUR_SERVER_NAME\SQLEXPRESS -E -Q "EXEC sp_BackupDatabases @backupLocation='C:\SQL_Backup\', @backupType='F'"  1>c:\SQL_Backup\backup.log            
    

Obviously replace YOUR_SERVER_NAME with your computer name or optionally try .\SQLEXPRESS and make sure the backup folder exists. In this case it's trying to put it into c:\SQL_Backup

Angular ui-grid dynamically calculate height of the grid

following @tony's approach, changed the getTableHeight() function to

<div id="grid1" ui-grid="$ctrl.gridOptions" class="grid" ui-grid-auto-resize style="{{$ctrl.getTableHeight()}}"></div>

getTableHeight() {
    var offsetValue = 365;
    return "height: " + parseInt(window.innerHeight - offsetValue ) + "px!important";
}

the grid would have a dynamic height with regards to window height as well.

Tomcat Server Error - Port 8080 already in use

Open below application

C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Apache Tomcat 8.5 Tomcat8

right click on Apache tomcat in system tray and click on stop services

Run your application from eclipse.

http://siddartech.com/apache/apachi-tomcat-server-already-in-use/

How to split a String by space

OK, so we have to do splitting as you already got the answer I would generalize it.

If you want to split any string by spaces, delimiter(special chars).

First, remove the leading space as they create most of the issues.

str1 = "    Hello I'm your       String    ";
str2 = "    Are you serious about this question_  boy, aren't you?   ";

First remove the leading space which can be space, tab etc.

String s = str1.replaceAll("^\\s+","");//starting with whitespace one or more

Now if you want to split by space or any special char.

String[] sa = s.split("[^\\w]+");//split by any non word char

But as w contains [a-zA-Z_0-9] ,so if you want to split by underscore(_) also use

 String[] sa = s.split("[!,? ._'@]+");//for str2 after removing leading space

What is time(NULL) in C?

The call to time(NULL) returns the current calendar time (seconds since Jan 1, 1970). See this reference for details. Ordinarily, if you pass in a pointer to a time_t variable, that pointer variable will point to the current time.

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
  {
       InitializeComponent();
       Load += new EventHandler(ProgramViwer_Load);
  }
  private void ProgramViwer_Load(object sender, System.EventArgs e)
  {
       formPanel.Controls.Clear();
       formPanel.Controls.Add(wel);
  }
}

Pdf.js: rendering a pdf file using a base64 file source instead of url

Used the Accepted Answer to do a check for IE and convert the dataURI to UInt8Array; an accepted form by PDFJS

_x000D_
_x000D_
        Ext.isIE ? pdfAsDataUri = me.convertDataURIToBinary(pdfAsDataUri): '';_x000D_
_x000D_
        convertDataURIToBinary: function(dataURI) {_x000D_
          var BASE64_MARKER = ';base64,',_x000D_
            base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length,_x000D_
            base64 = dataURI.substring(base64Index),_x000D_
            raw = window.atob(base64),_x000D_
            rawLength = raw.length,_x000D_
            array = new Uint8Array(new ArrayBuffer(rawLength));_x000D_
_x000D_
          for (var i = 0; i < rawLength; i++) {_x000D_
            array[i] = raw.charCodeAt(i);_x000D_
          }_x000D_
          return array;_x000D_
        },
_x000D_
_x000D_
_x000D_

Java Reflection Performance

If there really is need for something faster than reflection, and it's not just a premature optimization, then bytecode generation with ASM or a higher level library is an option. Generating the bytecode the first time is slower than just using reflection, but once the bytecode has been generated, it is as fast as normal Java code and will be optimized by the JIT compiler.

Some examples of applications which use code generation:

  • Invoking methods on proxies generated by CGLIB is slightly faster than Java's dynamic proxies, because CGLIB generates bytecode for its proxies, but dynamic proxies use only reflection (I measured CGLIB to be about 10x faster in method calls, but creating the proxies was slower).

  • JSerial generates bytecode for reading/writing the fields of serialized objects, instead of using reflection. There are some benchmarks on JSerial's site.

  • I'm not 100% sure (and I don't feel like reading the source now), but I think Guice generates bytecode to do dependency injection. Correct me if I'm wrong.

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

I had the same problem. I use the MSSQL Server Management Studio 2017 and solved this problem using these steps:

  1. Check for working fine SQL Server Services services or not.
  2. Also check for working in good condition SQL Server (MSSQLSERVER).
  3. Also check for working fine SQL Server Browser.
  4. Restart SQL Server (MSSQLSERVER)

and fixed it.

How to get to a particular element in a List in java?

The List interface supports random access via the get method - to get line 0, use list.get(0). You'll need to use array access on that, ie, lines.get(0)[0] is the first element of the first line.

See the javadoc here.

Byte Array to Image object

According to the Java docs, it looks like you need to use the MemoryImageSource Class to put your byte array into an object in memory, and then use Component.createImage(ImageProducer) next (passing in your MemoryImageSource, which implements ImageProducer).

How can I change or remove HTML5 form validation default error messages?

To prevent the browser validation message from appearing in your document, with jQuery:

$('input, select, textarea').on("invalid", function(e) {
    e.preventDefault();
});

TSQL: How to convert local time to UTC? (SQL Server 2008)

I tend to lean towards using DateTimeOffset for all date-time storage that isn't related to a local event (ie: meeting/party, etc, 12pm-3pm at the museum).

To get the current DTO as UTC:

DECLARE @utcNow DATETIMEOFFSET = CONVERT(DATETIMEOFFSET, SYSUTCDATETIME())
DECLARE @utcToday DATE = CONVERT(DATE, @utcNow);
DECLARE @utcTomorrow DATE = DATEADD(D, 1, @utcNow);
SELECT  @utcToday [today]
        ,@utcTomorrow [tomorrow]
        ,@utcNow [utcNow]

NOTE: I will always use UTC when sending over the wire... client-side JS can easily get to/from local UTC. See: new Date().toJSON() ...

The following JS will handle parsing a UTC/GMT date in ISO8601 format to a local datetime.

if (typeof Date.fromISOString != 'function') {
  //method to handle conversion from an ISO-8601 style string to a Date object
  //  Date.fromISOString("2009-07-03T16:09:45Z")
  //    Fri Jul 03 2009 09:09:45 GMT-0700
  Date.fromISOString = function(input) {
    var date = new Date(input); //EcmaScript5 includes ISO-8601 style parsing
    if (!isNaN(date)) return date;

    //early shorting of invalid input
    if (typeof input !== "string" || input.length < 10 || input.length > 40) return null;

    var iso8601Format = /^(\d{4})-(\d{2})-(\d{2})((([T ](\d{2}):(\d{2})(:(\d{2})(\.(\d{1,12}))?)?)?)?)?([Zz]|([-+])(\d{2})\:?(\d{2}))?$/;

    //normalize input
    var input = input.toString().replace(/^\s+/,'').replace(/\s+$/,'');

    if (!iso8601Format.test(input))
      return null; //invalid format

    var d = input.match(iso8601Format);
    var offset = 0;

    date = new Date(+d[1], +d[2]-1, +d[3], +d[7] || 0, +d[8] || 0, +d[10] || 0, Math.round(+("0." + (d[12] || 0)) * 1000));

    //use specified offset
    if (d[13] == 'Z') offset = 0-date.getTimezoneOffset();
    else if (d[13]) offset = ((parseInt(d[15],10) * 60) + (parseInt(d[16],10)) * ((d[14] == '-') ? 1 : -1)) - date.getTimezoneOffset();

    date.setTime(date.getTime() + (offset * 60000));

    if (date.getTime() <= new Date(-62135571600000).getTime()) // CLR DateTime.MinValue
      return null;

    return date;
  };
}

Why is an OPTIONS request sent and can I disable it?

Have gone through this issue, below is my conclusion to this issue and my solution.

According to the CORS strategy (highly recommend you read about it) You can't just force the browser to stop sending OPTIONS request if it thinks it needs to.

There are two ways you can work around it:

  1. Make sure your request is a "simple request"
  2. Set Access-Control-Max-Age for the OPTIONS request

Simple request

A simple cross-site request is one that meets all the following conditions:

The only allowed methods are:

  • GET
  • HEAD
  • POST

Apart from the headers set automatically by the user agent (e.g. Connection, User-Agent, etc.), the only headers which are allowed to be manually set are:

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type

The only allowed values for the Content-Type header are:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

A simple request will not cause a pre-flight OPTIONS request.

Set a cache for the OPTIONS check

You can set a Access-Control-Max-Age for the OPTIONS request, so that it will not check the permission again until it is expired.

Access-Control-Max-Age gives the value in seconds for how long the response to the preflight request can be cached for without sending another preflight request.

Limitation Noted

  • For Chrome, the maximum seconds for Access-Control-Max-Age is 600 which is 10 minutes, according to chrome source code
  • Access-Control-Max-Age only works for one resource every time, for example, GET requests with same URL path but different queries will be treated as different resources. So the request to the second resource will still trigger a preflight request.

NuGet Package Restore Not Working

I had NuGet packages breaking after I did a System Restore on my system, backing it up about two days. (The NuGet packages had been installed in the meantime.) To fix it, I had to go to the .nuget\packages folder in my user profile, find the packages, and delete them. Only then would Visual Studio pull the packages down fresh and properly add them as references.

How to extract elements from a list using indices in Python?

Use Numpy direct array indexing, as in MATLAB, Julia, ...

a = [10, 11, 12, 13, 14, 15];
s = [1, 2, 5] ;

import numpy as np
list(np.array(a)[s])
# [11, 12, 15]

Better yet, just stay with Numpy arrays

a = np.array([10, 11, 12, 13, 14, 15])
a[s]
#array([11, 12, 15])

How to get the browser to navigate to URL in JavaScript

Try these:

  1. window.location.href = 'http://www.google.com';
  2. window.location.assign("http://www.w3schools.com");
  3. window.location = 'http://www.google.com';

For more see this link: other ways to reload the page with JavaScript

Get battery level and state in Android

one mistake in official docs, you must use double instead float. Because 0.53F * 100F = 52F

int level = batteryStatus != null ? 
batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1; int scale = 
batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1; 
double batteryPct = (double) level / (double) scale; int percent = (int) (batteryPct * 100D);

How to identify all stored procedures referring a particular table

SELECT
    o.name
FROM
    sys.sql_modules sm
INNER JOIN sys.objects o ON
    o.object_id = sm.object_id
WHERE
    sm.definition LIKE '%<table name>%'

Just keep in mind that this will also turn up SPs where the table name is in the comments or where the table name is a substring of another table name that is being used. For example, if you have tables named "test" and "test_2" and you try to search for SPs with "test" then you'll get results for both.

Shell script to get the process ID on Linux

Using grep on the results of ps is a bad idea in a script, since some proportion of the time it will also match the grep process you've just invoked. The command pgrep avoids this problem, so if you need to know the process ID, that's a better option. (Note that, of course, there may be many processes matched.)

However, in your example, you could just use the similar command pkill to kill all matching processes:

pkill ruby

Incidentally, you should be aware that using -9 is overkill (ho ho) in almost every case - there's some useful advice about that in the text of the "Useless Use of kill -9 form letter ":

No no no. Don't use kill -9.

It doesn't give the process a chance to cleanly:

  1. shut down socket connections
  2. clean up temp files
  3. inform its children that it is going away
  4. reset its terminal characteristics

and so on and so on and so on.

Generally, send 15, and wait a second or two, and if that doesn't work, send 2, and if that doesn't work, send 1. If that doesn't, REMOVE THE BINARY because the program is badly behaved!

Don't use kill -9. Don't bring out the combine harvester just to tidy up the flower pot.

Can I add jars to maven 2 build classpath without installing them?

Using <scope>system</scope> is a terrible idea for reasons explained by others, installing the file manually to your local repository makes the build unreproducible, and using <url>file://${project.basedir}/repo</url> is not a good idea either because (1) that may not be a well-formed file URL (e.g. if the project is checked out in a directory with unusual characters), (2) the result is unusable if this project’s POM is used as a dependency of someone else’s project.

Assuming you are unwilling to upload the artifact to a public repository, Simeon’s suggestion of a helper module does the job. But there is an easier way now…

The Recommendation

Use non-maven-jar-maven-plugin. Does exactly what you were asking for, with none of the drawbacks of the other approaches.

How to format date and time in Android?

This is my method, you can define and input and output format.

public static String formattedDateFromString(String inputFormat, String outputFormat, String inputDate){
    if(inputFormat.equals("")){ // if inputFormat = "", set a default input format.
        inputFormat = "yyyy-MM-dd hh:mm:ss";
    }
    if(outputFormat.equals("")){
        outputFormat = "EEEE d 'de' MMMM 'del' yyyy"; // if inputFormat = "", set a default output format.
    }
    Date parsed = null;
    String outputDate = "";

    SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, java.util.Locale.getDefault());
    SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, java.util.Locale.getDefault());

    // You can set a different Locale, This example set a locale of Country Mexico.
    //SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, new Locale("es", "MX"));
    //SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, new Locale("es", "MX"));

    try {
        parsed = df_input.parse(inputDate);
        outputDate = df_output.format(parsed);
    } catch (Exception e) { 
        Log.e("formattedDateFromString", "Exception in formateDateFromstring(): " + e.getMessage());
    }
    return outputDate;

}

Play sound on button click android

public class MainActivity extends AppCompatActivity {

    public void clickMe (View view) {

        MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
        mp.start();

    }

create a button with a method could be called when the button pressed (onCreate),

then create a variable for (MediaPlayer) class with the path of your file

MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);

finally run start method in that class

mp.start();

the file will run when the button pressed, hope this was helpful!

CURL ERROR: Recv failure: Connection reset by peer - PHP Curl

So what is the URL that Yii::app()->params['pdfUrl'] gives? You say it should be https, but the log shows it's connecting on port 80... which almost no server is setup to accept https connections on. cURL is smart enough to know https should be on port 443... which would suggest that your URL has something wonky in it like: https://196.41.139.168:80/serve/?r=pdf/generatePdf

That's going to cause the connection to be terminated, when the Apache at the other end cannot do https communication with you on that port.

You realize your first $body definition gets replaced when you set $body to an array two lines later? {Probably just an artifact of you trying to solve the problem} You're also not encoding the client_url and client_id values (the former quite possibly containing characters that need escaping!) Oh and you're appending to $body_str without first initializing it.

From your verbose output we can see cURL is adding a content-length header, but... is it correct? I can see some comments out on the internets of that number being wrong (especially with older versions)... if that number was to small (for example) you'd get a connection-reset before all the data is sent. You can manually insert the header:

curl_setopt ($c, CURLOPT_HTTPHEADER, 
   array("Content-Length: ". strlen($body_str))); 

Oh and there's a handy function http_build_query that'll convert an array of name/value pairs into a URL encoded string for you.

All this rolls up into the final code:

$post=http_build_query(array(
  "client_url"=>Yii::app()->params['pdfClientURL'],
  "client_id"=>Yii::app()->params['pdfClientID'],
  "title"=>$title,
  "content"=>$content));

//Open to URL
$c=curl_init(Yii::app()->params['pdfUrl']);
//Send post
curl_setopt ($c, CURLOPT_POST, true);
//Optional: [try with/without]
curl_setopt ($c, CURLOPT_HTTPHEADER, array("Content-Length: ".strlen($post))); 
curl_setopt ($c, CURLOPT_POSTFIELDS, $post);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($c, CURLOPT_CONNECTTIMEOUT , 0);
curl_setopt ($c, CURLOPT_TIMEOUT  , 20);
//Collect result
$pdf = curl_exec ($c);
$curlInfo = curl_getinfo($c);
curl_close($c);

Handle spring security authentication exceptions with @ExceptionHandler

We need to use HandlerExceptionResolver in that case.

@Component
public class RESTAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    //@Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        resolver.resolveException(request, response, null, authException);
    }
}

Also, you need to add in the exception handler class to return your object.

@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(AuthenticationException.class)
    public GenericResponseBean handleAuthenticationException(AuthenticationException ex, HttpServletResponse response){
        GenericResponseBean genericResponseBean = GenericResponseBean.build(MessageKeys.UNAUTHORIZED);
        genericResponseBean.setError(true);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return genericResponseBean;
    }
}

may you get an error at the time of running a project because of multiple implementations of HandlerExceptionResolver, In that case you have to add @Qualifier("handlerExceptionResolver") on HandlerExceptionResolver

Angular window resize event

Here is an update to @GiridharKamik answer above with the latest version of Rxjs.

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject, fromEvent } from 'rxjs';
import { pluck, distinctUntilChanged, map } from 'rxjs/operators';

@Injectable()
export class WindowService {
    height$: Observable<number>;
    constructor() {
        const windowSize$ = new BehaviorSubject(getWindowSize());

        this.height$ = windowSize$.pipe(pluck('height'), distinctUntilChanged());

        fromEvent(window, 'resize').pipe(map(getWindowSize))
            .subscribe(windowSize$);
    }

}

function getWindowSize() {
    return {
        height: window.innerHeight
        //you can sense other parameters here
    };
};

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

&& and || are short circuit operators operating on scalars. & and | operate on arrays, and use short-circuiting only in the context of if or while loop expressions.

Reading value from console, interactively

Blocking readline unblocked behaviour

Imagine you have three questions to be answered from the console, as you now know this code will not run because readline standard module has 'unblocked' behaviour say each rl.question is an independent thread so this code will not run.

'use strict';

var questionaire=[['First Question: ',''],['Second Question: ',''],['Third Question: ','']];

function askaquestion(question) {
const readline = require('readline');

const rl = readline.createInterface(
    {input: process.stdin, output:process.stdout}
    );
  rl.question(question[0], function(answer) {
    console.log(answer);
    question[1] = answer;
    rl.close();
  });
};

var i=0;  
for (i=0; i < questionaire.length; i++) {
askaquestion(questionaire[i]);
}

console.log('Results:',questionaire );

Running output:

node test.js
Third Question: Results: [ [ 'First Question: ', '' ],
  [ 'Second Question: ', '' ],
  [ 'Third Question: ', '' ] ]        <--- the last question remain unoverwritten and then the final line of the program is shown as the threads were running waiting for answers (see below)
aaa        <--- I responded with a single 'a' that was sweeped by 3 running threads
a        <--- Response of one thread

a        <--- Response of another thread

a        <--- Response of another thread (there is no order on threads exit)

The proposed solution uses an event emitter to signal the end of an unblocking thread, and includes the loop logic and end of program into its listener function.

'use strict';

var questionaire=[['First Question: ',''],['Second Question: ',''],['Third Question: ','']];

// Introduce EventEmitter object
const EventEmitter = require('events');

class MyEmitter extends EventEmitter {};

const myEmitter = new MyEmitter();
myEmitter.on('continue', () => {
  console.log('continue...');
  i++; if (i< questionaire.length) askaquestion(questionaire[i],myEmitter);    // add here relevant loop logic
           else console.log('end of loop!\nResults:',questionaire );
});
//

function askaquestion(p_question,p_my_Emitter) { // add a parameter to include my_Emitter
const readline = require('readline');

const rl = readline.createInterface(
    {input: process.stdin, output:process.stdout}
    );
  rl.question(p_question[0], function(answer) {
    console.log(answer);
    p_question[1] = answer;
    rl.close();
    myEmitter.emit('continue');    // Emit 'continue' event after the question was responded (detect end of unblocking thread)
  });
};

/*var i=0;  
for (i=0; i < questionaire.length; i++) {
askaquestion(questionaire[i],myEmitter);
}*/

var i=0;
askaquestion(questionaire[0],myEmitter);        // entry point to the blocking loop


// console.log('Results:',questionaire )    <- moved to the truly end of the program

Running output:

node test2.js
First Question: 1
1
continue...
Second Question: 2
2
continue...
Third Question: 3
3
continue...
done!
Results: [ [ 'First Question: ', '1' ],
  [ 'Second Question: ', '2' ],
  [ 'Third Question: ', '3' ] ]

Set min-width in HTML table's <td>

<table style="border:2px solid #ddedde">
    <tr>
        <td style="border:2px solid #ddedde;width:50%">a</td>
        <td style="border:2px solid #ddedde;width:20%">b</td>
        <td style="border:2px solid #ddedde;width:30%">c</td>
    </tr>
    <tr>
        <td style="border:2px solid #ddedde;width:50%">a</td>
        <td style="border:2px solid #ddedde;width:20%">b</td>
        <td style="border:2px solid #ddedde;width:30%">c</td>
    </tr>
</table>

Adding custom radio buttons in android

Below code is example of custom radio button. follow below steps..

  1. Xml file.

     <FrameLayout
         android:layout_width="0dp"
         android:layout_height="match_parent"
         android:layout_weight="0.5">
    
         <TextView
             android:id="@+id/text_gender"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="left|center_vertical"
             android:gravity="center"
             android:text="@string/gender"
             android:textColor="#263238"
             android:textSize="15sp"
             android:textStyle="normal"
    
             />
    
         <TextView
             android:id="@+id/text_male"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="center"
             android:layout_marginLeft="10dp"
             android:gravity="center"
             android:text="@string/male"
             android:textColor="#263238"
             android:textSize="15sp"
             android:textStyle="normal"/>
    
         <RadioButton
             android:id="@+id/radio_Male"
             android:layout_width="28dp"
             android:layout_height="28dp"
             android:layout_gravity="right|center_vertical"
             android:layout_marginRight="4dp"
             android:button="@drawable/custom_radio_button"
             android:checked="true"
             android:text=""
             android:onClick="onButtonClicked"
             android:textSize="15sp"
             android:textStyle="normal"
    
             />
     </FrameLayout>
    
     <FrameLayout
         android:layout_width="0dp"
         android:layout_height="match_parent"
         android:layout_weight="0.6">
    
         <RadioButton
             android:id="@+id/radio_Female"
             android:layout_width="28dp"
             android:layout_height="28dp"
             android:layout_gravity="right|center_vertical"
             android:layout_marginLeft="10dp"
             android:layout_marginRight="0dp"
             android:button="@drawable/custom_female_button"
             android:text=""
             android:onClick="onButtonClicked"
             android:textSize="15sp"
             android:textStyle="normal"/>
    
         <TextView
             android:id="@+id/text_female"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="left|center_vertical"
             android:gravity="center"
             android:text="@string/female"
             android:textColor="#263238"
             android:textSize="15sp"
             android:textStyle="normal"/>
    
         <RadioButton
             android:id="@+id/radio_Other"
             android:layout_width="28dp"
             android:layout_height="28dp"
             android:layout_gravity="center_horizontal|bottom"
             android:layout_marginRight="10dp"
             android:button="@drawable/custom_other_button"
             android:text=""
             android:onClick="onButtonClicked"
             android:textSize="15sp"
             android:textStyle="normal"/>
    
         <TextView
             android:id="@+id/text_other"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="right|center_vertical"
             android:layout_marginRight="34dp"
             android:gravity="center"
             android:text="@string/other"
             android:textColor="#263238"
             android:textSize="15sp"
             android:textStyle="normal"/>
     </FrameLayout>
    

2.add the custom xml for the radio buttons

2.1.other drawable

custom_other_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true" android:drawable="@drawable/select_radio_other" />
    <item android:state_checked="false" android:drawable="@drawable/default_radio" />

</selector>

2.2.female drawable

custom_female_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true" android:drawable="@drawable/select_radio_female" />
    <item android:state_checked="false" android:drawable="@drawable/default_radio" />

</selector>

2.3. male drawable

custom_radio_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_checked="true" android:drawable="@drawable/select_radio_male" />
    <item android:state_checked="false" android:drawable="@drawable/default_radio" />
</selector>
  1. Output: this is the output screen

JOIN two SELECT statement results

Use UNION:

SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks

Or UNION ALL if you want duplicates:

SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION ALL
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks

How do you do block comments in YAML?

One way to block commenting in YAML is by using a text editor like Notepad++ to add a # (comment) tag to multiple lines at once.

In Notepad++ you can do that using the "Block Comment" right-click option for selected text.

Woo Images!

What is the difference between a Relational and Non-Relational Database?

Relational databases have a mathematical basis (set theory, relational theory), which are distilled into SQL == Structured Query Language.

NoSQL's many forms (e.g. document-based, graph-based, object-based, key-value store, etc.) may or may not be based on a single underpinning mathematical theory. As S. Lott has correctly pointed out, hierarchical data stores do indeed have a mathematical basis. The same might be said for graph databases.

I'm not aware of a universal query language for NoSQL databases.

HTML CSS Button Positioning

as I expected, yeah, it's because the whole DOM element is being pushed down. You have multiple options. You can put the buttons in separate divs, and float them so that they don't affect each other. the simpler solution is to just set the :active button to position:relative; and use top instead of margin or line-height. example fiddle: http://jsfiddle.net/5CZRP/

jQuery DataTables: control table width

"fnInitComplete": function() {
    $("#datatables4_wrapper").css("width","60%");
 }

This worked fine to adjust the whole table width. Thanks @Peter Drinnan!

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

If you can copy the whole exception it would be much more better, but once I faced with this Exception and this is because the function calling from your dll file which I guess is Aspose.dll hasn't been signed well. I think it would be the possible duplicate of this

FYI, in order to find out if your dll hasn't been signed well you should right-click on that and go to the signiture and it will tell you if it has been electronically signed well or not.

Open text file and program shortcut in a Windows batch file

"location of notepad file" > notepad Filename

C:\Users\Desktop\Anaconda> notepad myfile

works for me! :)

How to force a view refresh without having it trigger automatically from an observable?

In some circumstances it might be useful to simply remove the bindings and then re-apply:

ko.cleanNode(document.getElementById(element_id))
ko.applyBindings(viewModel, document.getElementById(element_id))

How to select date from datetime column?

Though all the answers on the page will return the desired result, they all have performance issues. Never perform calculations on fields in the WHERE clause (including a DATE() calculation) as that calculation must be performed on all rows in the table.

The BETWEEN ... AND construct is inclusive for both border conditions, requiring one to specify the 23:59:59 syntax on the end date which itself has other issues (microsecond transactions, which I believe MySQL did not support in 2009 when the question was asked).

The proper way to query a MySQL timestamp field for a particular day is to check for Greater-Than-Equals against the desired date, and Less-Than for the day after, with no hour specified.

WHERE datetime>='2009-10-20' AND datetime<'2009-10-21'

This is the fastest-performing, lowest-memory, least-resource intensive method, and additionally supports all MySQL features and corner-cases such as sub-second timestamp precision. Additionally, it is future proof.

Iterating over a numpy array

I see that no good desciption for using numpy.nditer() is here. So, I am gonna go with one. According to NumPy v1.21 dev0 manual, The iterator object nditer, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

I have to calculate mean_squared_error and I have already calculate y_predicted and I have y_actual from the boston dataset, available with sklearn.

def cal_mse(y_actual, y_predicted):
    """ this function will return mean squared error
       args:
           y_actual (ndarray): np array containing target variable
           y_predicted (ndarray): np array containing predictions from DecisionTreeRegressor
       returns:
           mse (integer)
    """
    sq_error = 0
    for i in np.nditer(np.arange(y_pred.shape[0])):
        sq_error += (y_actual[i] - y_predicted[i])**2
    mse = 1/y_actual.shape[0] * sq_error
    
    return mse

Hope this helps :). for further explaination visit

What is cardinality in Databases?

A source of confusion may be the use of the word in two different contexts - data modelling and database query optimization.

In data modelling terms, cardinality is how one table relates to another.

  • 1-1 (one row in table A relates to one row in tableB)
  • 1-Many (one row in table A relates to many rows in tableB)
  • Many-Many (Many rows in table A relate to many rows in tableB)

There are also optional participation conditions to the above (where a row in one table doesn't have to relate to the other table at all).

See Wikipedia on Cardinality (data modelling).


When talking about database query optimization, cardinality refers to the data in a column of a table, specifically how many unique values are in it. This statistic helps with planning queries and optimizing the execution plans.

See Wikipedia on Cardinality (SQL statements).

How to run a Command Prompt command with Visual Basic code?

Here is an example:

Process.Start("CMD", "/C Pause")


/C  Carries out the command specified by string and then terminates
/K  Carries out the command specified by string but remains

And here is a extended function: (Notice the comment-lines using CMD commands.)

#Region " Run Process Function "

' [ Run Process Function ]
'
' // By Elektro H@cker
'
' Examples :
'
' MsgBox(Run_Process("Process.exe")) 
' MsgBox(Run_Process("Process.exe", "Arguments"))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B", True))
' MsgBox(Run_Process("CMD.exe", "/C @Echo OFF & For /L %X in (0,1,50000) Do (Echo %X)", False, False))
' MsgBox(Run_Process("CMD.exe", "/C Dir /B /S %SYSTEMDRIVE%\*", , False, 500))
' If Run_Process("CMD.exe", "/C Dir /B", True).Contains("File.txt") Then MsgBox("File found")

Private Function Run_Process(ByVal Process_Name As String, _
                             Optional Process_Arguments As String = Nothing, _
                             Optional Read_Output As Boolean = False, _
                             Optional Process_Hide As Boolean = False, _
                             Optional Process_TimeOut As Integer = 999999999)

    ' Returns True if "Read_Output" argument is False and Process was finished OK
    ' Returns False if ExitCode is not "0"
    ' Returns Nothing if process can't be found or can't be started
    ' Returns "ErrorOutput" or "StandardOutput" (In that priority) if Read_Output argument is set to True.

    Try

        Dim My_Process As New Process()
        Dim My_Process_Info As New ProcessStartInfo()

        My_Process_Info.FileName = Process_Name ' Process filename
        My_Process_Info.Arguments = Process_Arguments ' Process arguments
        My_Process_Info.CreateNoWindow = Process_Hide ' Show or hide the process Window
        My_Process_Info.UseShellExecute = False ' Don't use system shell to execute the process
        My_Process_Info.RedirectStandardOutput = Read_Output '  Redirect (1) Output
        My_Process_Info.RedirectStandardError = Read_Output ' Redirect non (1) Output
        My_Process.EnableRaisingEvents = True ' Raise events
        My_Process.StartInfo = My_Process_Info
        My_Process.Start() ' Run the process NOW

        My_Process.WaitForExit(Process_TimeOut) ' Wait X ms to kill the process (Default value is 999999999 ms which is 277 Hours)

        Dim ERRORLEVEL = My_Process.ExitCode ' Stores the ExitCode of the process
        If Not ERRORLEVEL = 0 Then Return False ' Returns the Exitcode if is not 0

        If Read_Output = True Then
            Dim Process_ErrorOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Error Output (If any)
            Dim Process_StandardOutput As String = My_Process.StandardOutput.ReadToEnd() ' Stores the Standard Output (If any)
            ' Return output by priority
            If Process_ErrorOutput IsNot Nothing Then Return Process_ErrorOutput ' Returns the ErrorOutput (if any)
            If Process_StandardOutput IsNot Nothing Then Return Process_StandardOutput ' Returns the StandardOutput (if any)
        End If

    Catch ex As Exception
        'MsgBox(ex.Message)
        Return Nothing ' Returns nothing if the process can't be found or started.
    End Try

    Return True ' Returns True if Read_Output argument is set to False and the process finished without errors.

End Function

#End Region

XAMPP Object not found error

Object not found!

The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

You're having problem because the object really doesn't exist in your htdocs directory. You don't have to append xampp after localhost or 127.0.0.1 because xampp will treat it as an object or a folder under htdocs.

if you want to access your blog, make sure you have a blog folder under htdocs and put in your URL localhost/blog

How to activate a specific worksheet in Excel?

An alternative way to (not dynamically) link a text to activate a worksheet without macros is to make the selected string an actual link. You can do this by selecting the cell that contains the text and press CTRL+K then select the option/tab 'Place in this document' and select the tab you want to activate. If you would click the text (that is now a link) the configured sheet will become active/selected.

How to suppress Update Links warning?

I've found a temporary solution that will at least let me process this job. I wrote a short AutoIt script that waits for the "Update Links" window to appear, then clicks the "Don't Update" button. Code is as follows:

while 1
if winexists("Microsoft Excel","This workbook contains links to other data sources.") Then
   controlclick("Microsoft Excel","This workbook contains links to other data sources.",2)
EndIf
WEnd

So far this seems to be working. I'd really like to find a solution that's entirely VBA, however, so that I can make this a standalone application.

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

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

real 4.784
user 0.01s
sys  0.01s

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

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

How to get names of enum entries?

For me an easier, practical and direct way to understand what is going on, is that the following enumeration:

enum colors { red, green, blue };

Will be converted essentially to this:

var colors = { red: 0, green: 1, blue: 2,
               [0]: "red", [1]: "green", [2]: "blue" }

Because of this, the following will be true:

colors.red === 0
colors[colors.red] === "red"
colors["red"] === 0

This creates a easy way to get the name of an enumerated as follows:

var color: colors = colors.red;
console.log("The color selected is " + colors[color]);

It also creates a nice way to convert a string to an enumerated value.

var colorName: string = "green";
var color: colors = colors.red;
if (colorName in colors) color = colors[colorName];

The two situations above are far more common situation, because usually you are far more interested in the name of a specific value and serializing values in a generic way.

Compare and contrast REST and SOAP web services?

SOAP uses WSDL for communication btw consumer and provider, whereas REST just uses XML or JSON to send and receive data

WSDL defines contract between client and service and is static by its nature. In case of REST contract is somewhat complicated and is defined by HTTP, URI, Media Formats and Application Specific Coordination Protocol. It's highly dynamic unlike WSDL.

SOAP doesn't return human readable result, whilst REST result is readable with is just plain XML or JSON

This is not true. Plain XML or JSON are not RESTful at all. None of them define any controls(i.e. links and link relations, method information, encoding information etc...) which is against REST as far as messages must be self contained and coordinate interaction between agent/client and service.

With links + semantic link relations clients should be able to determine what is next interaction step and follow these links and continue communication with service.

It is not necessary that messages be human readable, it's possible to use cryptic format and build perfectly valid REST applications. It doesn't matter whether message is human readable or not.

Thus, plain XML(application/xml) or JSON(application/json) are not sufficient formats for building REST applications. It's always reasonable to use subset of these generic media types which have strong semantic meaning and offer enough control information(links etc...) to coordinate interactions between client and server.

REST is over only HTTP

Not true, HTTP is most widely used and when we talk about REST web services we just assume HTTP. HTTP defines interface with it's methods(GET, POST, PUT, DELETE, PATCH etc) and various headers which can be used uniformly for interacting with resources. This uniformity can be achieved with other protocols as well.

P.S. Very simple, yet very interesting explanation of REST: http://www.looah.com/source/view/2284

Darken background image on hover

Similar, but again a little bit different.

Make the image 100% opacity so it is clear. And then on img hover reduce it to the opacity you want. In this example, I have also added easing for a nice transition.

img {
    -webkit-filter: brightness(100%);
}

img:hover {
    -webkit-filter: brightness(70%);
    -webkit-transition: all 1s ease;
    -moz-transition: all 1s ease;
    -o-transition: all 1s ease;
    -ms-transition: all 1s ease;
    transition: all 1s ease;
}

That will do it, Hope that helps.

Thank you Robert Byers for your jsfiddle

PHP combine two associative arrays into one array

I use a wrapper around array_merge to deal with SeanWM's comment about null arrays; I also sometimes want to get rid of duplicates. I'm also generally wanting to merge one array into another, as opposed to creating a new array. This ends up as:

/**
 * Merge two arrays - but if one is blank or not an array, return the other.
 * @param $a array First array, into which the second array will be merged
 * @param $b array Second array, with the data to be merged
 * @param $unique boolean If true, remove duplicate values before returning
 */
function arrayMerge(&$a, $b, $unique = false) {
    if (empty($b)) {
        return;  // No changes to be made to $a
    }
    if (empty($a)) {
        $a = $b;
        return;
    }
    $a = array_merge($a, $b);
    if ($unique) {
        $a = array_unique($a);
    }
}

Get specific line from text file using just shell script

I didn't particularly like any of the answers.

Here is how I did it.

# Convert the file into an array of strings
lines=(`cat "foo.txt"`)

# Print out the lines via array index
echo "${lines[0]}"
echo "${lines[1]}"
echo "${lines[5]}"

How do I use Ruby for shell scripting?

By default, you already have access to Dir and File, which are pretty useful by themselves.

Dir['*.rb'] #basic globs
Dir['**/*.rb'] #** == any depth of directory, including current dir.
#=> array of relative names

File.expand_path('~/file.txt') #=> "/User/mat/file.txt"
File.dirname('dir/file.txt') #=> 'dir'
File.basename('dir/file.txt') #=> 'file.txt'
File.join('a', 'bunch', 'of', 'strings') #=> 'a/bunch/of/strings'

__FILE__ #=> the name of the current file

Also useful from the stdlib is FileUtils

require 'fileutils' #I know, no underscore is not ruby-like
include FileUtils
# Gives you access (without prepending by 'FileUtils.') to
cd(dir, options)
cd(dir, options) {|dir| .... }
pwd()
mkdir(dir, options)
mkdir(list, options)
mkdir_p(dir, options)
mkdir_p(list, options)
rmdir(dir, options)
rmdir(list, options)
ln(old, new, options)
ln(list, destdir, options)
ln_s(old, new, options)
ln_s(list, destdir, options)
ln_sf(src, dest, options)
cp(src, dest, options)
cp(list, dir, options)
cp_r(src, dest, options)
cp_r(list, dir, options)
mv(src, dest, options)
mv(list, dir, options)
rm(list, options)
rm_r(list, options)
rm_rf(list, options)
install(src, dest, mode = <src's>, options)
chmod(mode, list, options)
chmod_R(mode, list, options)
chown(user, group, list, options)
chown_R(user, group, list, options)
touch(list, options)

Which is pretty nice

One DbContext per web request... why?

There are two contradicting recommendations by microsoft and many people use DbContexts in a completely divergent manner.

  1. One recommendation is to "Dispose DbContexts as soon as posible" because having a DbContext Alive occupies valuable resources like db connections etc....
  2. The other states that One DbContext per request is highly reccomended

Those contradict to each other because if your Request is doing a lot of unrelated to the Db stuff , then your DbContext is kept for no reason. Thus it is waste to keep your DbContext alive while your request is just waiting for random stuff to get done...

So many people who follow rule 1 have their DbContexts inside their "Repository pattern" and create a new Instance per Database Query so X*DbContext per Request

They just get their data and dispose the context ASAP. This is considered by MANY people an acceptable practice. While this has the benefits of occupying your db resources for the minimum time it clearly sacrifices all the UnitOfWork and Caching candy EF has to offer.

Keeping alive a single multipurpose instance of DbContext maximizes the benefits of Caching but since DbContext is not thread safe and each Web request runs on it's own thread, a DbContext per Request is the longest you can keep it.

So EF's team recommendation about using 1 Db Context per request it's clearly based on the fact that in a Web Application a UnitOfWork most likely is going to be within one request and that request has one thread. So one DbContext per request is like the ideal benefit of UnitOfWork and Caching.

But in many cases this is not true. I consider Logging a separate UnitOfWork thus having a new DbContext for Post-Request Logging in async threads is completely acceptable

So Finally it turns down that a DbContext's lifetime is restricted to these two parameters. UnitOfWork and Thread

What data type to use for money in Java?

An integral type representing the smallest value possible. In other words your program should think in cents not in dollars/euros.

This should not stop you from having the gui translate it back to dollars/euros.

How to read a file line-by-line into a list?

If you want the \n included:

with open(fname) as f:
    content = f.readlines()

If you do not want \n included:

with open(fname) as f:
    content = f.read().splitlines()

Proper way to initialize C++ structs

In C++ classes/structs are identical (in terms of initialization).

A non POD struct may as well have a constructor so it can initialize members.
If your struct is a POD then you can use an initializer.

struct C
{
    int x; 
    int y;
};

C  c = {0}; // Zero initialize POD

Alternatively you can use the default constructor.

C  c = C();      // Zero initialize using default constructor
C  c{};          // Latest versions accept this syntax.
C* c = new C();  // Zero initialize a dynamically allocated object.

// Note the difference between the above and the initialize version of the constructor.
// Note: All above comments apply to POD structures.
C  c;            // members are random
C* c = new C;    // members are random (more officially undefined).

I believe valgrind is complaining because that is how C++ used to work. (I am not exactly sure when C++ was upgraded with the zero initialization default construction). Your best bet is to add a constructor that initializes the object (structs are allowed constructors).

As a side note:
A lot of beginners try to value init:

C c(); // Unfortunately this is not a variable declaration.
C c{}; // This syntax was added to overcome this confusion.

// The correct way to do this is:
C c = C();

A quick search for the "Most Vexing Parse" will provide a better explanation than I can.

Replace String in all files in Eclipse

Strange but it is a two step task:

  1. Search what you want
  2. In the search tab right click and select replace , or replace all:

A demo at:

http://www.avajava.com/tutorials/lessons/how-do-i-do-a-find-and-replace-in-multiple-files-in-eclipse.html

What is an instance variable in Java?

An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new), whereas a class variable is a member of the class itself.

Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.

What’s the difference between a class variable and an instance variable?

This test class illustrates the difference:

public class Test {
   
    public static String classVariable = "I am associated with the class";
    public String instanceVariable = "I am associated with the instance";
    
    public void setText(String string){
        this.instanceVariable = string;
    }
    
    public static void setClassText(String string){
        classVariable = string;
    }
    
    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        
        // Change test1's instance variable
        test1.setText("Changed");
        System.out.println(test1.instanceVariable); // Prints "Changed"
        // test2 is unaffected
        System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
        
        // Change class variable (associated with the class itself)
        Test.setClassText("Changed class text");
        System.out.println(Test.classVariable); // Prints "Changed class text"
        
        // Can access static fields through an instance, but there still is only one
        // (not best practice to access static variables through instance)
        System.out.println(test1.classVariable); // Prints "Changed class text"
        System.out.println(test2.classVariable); // Prints "Changed class text"
    }
}

jQuery to retrieve and set selected option value of html select element

$( "#myId option:selected" ).text(); will give you the text that you selected in the drop down element. either way you can change it to .val(); to get the value of it . check the below coding

<select id="myId">
    <option value="1">Mr</option>
    <option value="2">Mrs</option>
    <option value="3">Ms</option>`
    <option value="4">Dr</option>
    <option value="5">Prof</option>
</select>

Android: Go back to previous activity

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

This will get you to a previous activity keeping its stack and clearing all activities after it from the stack.

For example, if stack was A->B->C->D and you start B with this flag, stack will be A->B

What is the purpose of Node.js module.exports and how do you use it?

the module.exports property or the exports object allows a module to select what should be shared with the application

enter image description here

I have a video on module_export available here

c++ bool question

Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values

In MVC, how do I return a string result?

public ActionResult GetAjaxValue()
{
   return Content("string value");
}

How to write header row with csv.DictWriter?

Edit:
In 2.7 / 3.2 there is a new writeheader() method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader() method now available in 2.7 / 3.2:

from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
    dw.writeheader()
    # continue on to write data

Instantiating DictWriter requires a fieldnames argument.
From the documentation:

The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with statement was added in 2.6. If using 2.5: from __future__ import with_statement

with open(infile,'rb') as fin:
    dr = csv.DictReader(fin, delimiter='\t')

# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    headers = {} 
    for n in dw.fieldnames:
        headers[n] = n
    dw.writerow(headers)
    for row in dr:
        dw.writerow(row)

As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:

with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
    for row in dr:
        dw.writerow(row)

Gridview row editing - dynamic binding to a DropDownList

You can use SelectedValue:

<EditItemTemplate>
    <asp:DropDownList ID="ddlPBXTypeNS"
                      runat="server"
                      Width="200px"
                      DataSourceID="YDS"
                      DataTextField="CaptionValue"
                      DataValueField="OID"
                      SelectedValue='<%# Bind("YourForeignKey") %>' />
    <asp:YourDataSource ID="YDS" ...../>
</EditItemTemplate>

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Sample DDL

create table #Temp
(
    EventID int, 
    EventTitle Varchar(50), 
    EventStartDate DateTime, 
    EventEndDate DatetIme, 
    EventEnumDays int,
    EventStartTime Datetime,
    EventEndTime DateTime, 
    EventRecurring Bit, 
    EventType int
)

;WITH Calendar
AS (SELECT /*...*/)

Insert Into #Temp
Select EventID, EventStartDate, EventEndDate, PlannedDate as [EventDates], Cast(PlannedDate As datetime) AS DT, Cast(EventStartTime As time) AS ST,Cast(EventEndTime As time) AS ET, EventTitle
,EventType from Calendar
where (PlannedDate >= GETDATE()) AND ',' + EventEnumDays + ',' like '%,' + cast(datepart(dw, PlannedDate) as char(1)) + ',%'
    or EventEnumDays is null

Make sure that the table is deleted after use

If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End

Print to the same line and not a new line?

for Console you'll probably need

sys.stdout.flush()

to force update. I think using , in print will block stdout from flushing and somehow it won't update

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

After installing weblogic and forms server on a Linux machine we met some problems initializing sqlplus and tnsping. We altered the bash_profile in a way that the forms_home acts as the oracle home. It works fine, both commands (sqlplus and tnsping) are executable for user oracle

# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin

export JAVA_HOME=/mnt/software/java/jdk1.7.0_71
export ORACLE_HOME=/oracle/Middleware/Oracle_FRHome1
export PATH=$PATH:$JAVA_HOME/bin:$ORACLE_HOME/bin
export LD_LIBRARY_PATH=/oracle/Middleware/Oracle_FRHome1/lib
export FORMS_PATH=$FORMS_PATH:/oracle/Middleware/Oracle_FRHome1/forms:/oracle/Middleware/asinst_1/FormsComponent/forms:/appl/myapp:/home/oracle/myapp

How to detect a docker daemon port

By default, the docker daemon will use the unix socket unix:///var/run/docker.sock (you can check this is the case for you by doing a sudo netstat -tunlp and note that there is no docker daemon process listening on any ports). It's recommended to keep this setting for security reasons but it sounds like Riak requires the daemon to be running on a TCP socket.

To start the docker daemon with a TCP socket that anybody can connect to, use the -H option:

sudo docker -H 0.0.0.0:2375 -d &

Warning: This means machines that can talk to the daemon through that TCP socket can get root access to your host machine.

Related docs:

http://basho.com/posts/technical/running-riak-in-docker/

https://docs.docker.com/install/linux/linux-postinstall/#configure-where-the-docker-daemon-listens-for-connections

Why is it string.join(list) instead of list.join(string)?

The variables my_list and "-" are both objects. Specifically, they're instances of the classes list and str, respectively. The join function belongs to the class str. Therefore, the syntax "-".join(my_list) is used because the object "-" is taking my_list as an input.

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

Settings->Preferences->Auto-Completion and there check Enable auto-completion on each input. Press Ctrl + Space to get a autocomplete hint. For auto-complete in code type the first letter then press Ctrl + Enter. all the inputs you have given will be listed.

IE11 meta element Breaks SVG

I was having the same problem with 3 of 4 inline svgs I was using, and they only disappeared (in one case, partially) on IE11.

I had <meta http-equiv="x-ua-compatible" content="ie=edge"> on the page.

In the end, the problem was extra clipping paths on the svg file. I opened the files on Illustrator, removed the clipping path (normally at the bottom of the layers) and now they're all working.

Open Form2 from Form1, close Form1 from Form2

Your question is vague but you could use ShowDialog to display form 2. Then when you close form 2, pass a DialogResult object back to let the user know how the form was closed - if the user clicked the button, then close form 1 as well.

What's the difference between '$(this)' and 'this'?

$() is the jQuery constructor function.

this is a reference to the DOM element of invocation.

So basically, in $(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.

Passing a callback function to another class

You could change your code in this way:

public delegate void CallbackHandler(string str);

public class ServerRequest
{
    public void DoRequest(string request, CallbackHandler callback)
    {
        // do stuff....
        callback("asdf");
    }
}

How can I use an ES6 import in Node.js?

I don't know if this will work for your case, but I am running an Express.js server with this:

nodemon --inspect ./index.js --exec babel-node --presets es2015,stage-2

This gives me the ability to import and use spread operator even though I'm only using Node.js version 8.

You'll need to install babel-cli, babel-preset-es2015, and babel-preset-stage-2 to do what I'm doing.

mongod command not recognized when trying to connect to a mongodb server

You need to run mongod first in one cmd window then open another and type mongo. Make sure you updated your Windows Path environment variable too so that you don't have to navigate to the directory you have all of the mongo binaries in to start the application. To update the Path variable:

Go to Control Panel > System & Security > System > Advanced System Settings > Environment Variables > navigate to the Path variable hit Edit and add ;C:\mongodb to the Path (or whatever the directory name is where MongoDB is located (the semi-colon delimits each directory).

Apache Name Virtual Host with SSL

You may be able to replace the:

VirtualHost ipaddress:443

with

VirtualHost *:443

You probably need todo this on all of your virt hosts.

It will probably clear up that message. Let the ServerName directive worry about routing the message request.

Again, you may not be able to do this if you have multiple ip's aliases to the same machine.

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

AttributeError: 'tuple' object has no attribute

Variables names are only locally meaningful.

Once you hit

return s1,s2,s3,s4

at the end of the method, Python constructs a tuple with the values of s1, s2, s3 and s4 as its four members at index 0, 1, 2 and 3 - NOT a dictionary of variable names to values, NOT an object with variable names and their values, etc.

If you want the variable names to be meaningful after you hit return in the method, you must create an object or dictionary.

Java System.out.print formatting

Since you are using Java, printf is available from version 1.5

You may use it like this

System.out.printf("%03d ", x);

For Example:

System.out.printf("%03d ", 5);
System.out.printf("%03d ", 55);
System.out.printf("%03d ", 555);

Will Give You

005 055 555

as output

See: System.out.printf and Format String Syntax

Where does Android app package gets installed on phone

An application when installed on a device or on an emulator will install at:

/data/data/APP_PACKAGE_NAME

The APK itself is placed in the /data/app/ folder.

These paths, however, are in the System Partition and to access them, you will need to have root. This is for a device. On the emulator, you can see it in your logcat (DDMS) in the File Explorer tab

By the way, it only shows the package name that is defined in your Manifest.XML under the package="APP_PACKAGE_NAME" attribute. Any other packages you may have created in your project in Eclipse do not show up here.

How do I check the difference, in seconds, between two dates?

Another approach is to use timestamp values:

end_time.timestamp() - start_time.timestamp()

Remove android default action bar

I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:

<android:theme="@android:style/Theme.NoTitleBar">

Just add it to your application tag to apply it app-wide.

How can I select rows with most recent timestamp for each key value?

There is one common answer I haven't see here yet, which is the Window Function. It is an alternative to the correlated sub-query, if your DB supports it.

SELECT sensorID,timestamp,sensorField1,sensorField2 
FROM (
    SELECT sensorID,timestamp,sensorField1,sensorField2
        , ROW_NUMBER() OVER(
            PARTITION BY sensorID
            ORDER BY timestamp
        ) AS rn
    FROM sensorTable s1
WHERE rn = 1
ORDER BY sensorID, timestamp;

I acually use this more than correlated sub-queries. Feel free to bust me in the comments over effeciancy, I'm not too sure how it stacks up in that regard.

How to use both onclick and target="_blank"

The window.open method is prone to cause popup blockers to complain

A better approach is:

Put a form in the webpage with an id

<form action="theUrlToGoTo" method="post" target="yourTarget" id="yourFormName"> </form>

Then use:

function openYourRequiredPage() {
var theForm = document.getElementById("yourFormName");
theForm.submit();

}

and

onclick="Javascript: openYourRequiredPage()"

You can use

method="post"

or

method="get"

As you wish

A Simple, 2d cross-platform graphics library for c or c++?

One neat engine I came across is Angel-Engine. Info from the project site:

  • Cross-Platform functionality (Windows and Mac)
  • Actors (game objects with color, shape, responses, attributes, etc.)
  • Texturing with Transparency
  • "Animations" (texture swapping at defined intervals)
  • Rigid-Body Physics
    • A clever programmer can do soft-body physics with it
  • Sound
  • Text Rendering with multiple fonts
  • Particle Systems
  • Some basic AI (state machine and pathfinding)
  • Config File Processing
  • Logging
  • Input from a mouse, keyboard, or Xbox 360 controller
    • Binding inputs from a config file
  • Python Scripting
    • In-Game Console

Some users (including me) have succesfully (without any major problems) compiled it under linux.

how to get the base url in javascript

Base URL in JavaScript

You can access the current url quite easily in JavaScript with window.location

You have access to the segments of that URL via this locations object. For example:

// This article:
// https://stackoverflow.com/questions/21246818/how-to-get-the-base-url-in-javascript

var base_url = window.location.origin;
// "http://stackoverflow.com"

var host = window.location.host;
// stackoverflow.com

var pathArray = window.location.pathname.split( '/' );
// ["", "questions", "21246818", "how-to-get-the-base-url-in-javascript"]

In Chrome Dev Tools, you can simply enter window.location in your console and it will return all of the available properties.


Further reading is available on this Stack Overflow thread

NSNotificationCenter addObserver in Swift

Swift 3.0 in Xcode 8

Swift 3.0 has replaced many "stringly-typed" APIs with struct "wrapper types", as is the case with NotificationCenter. Notifications are now identified by a struct Notfication.Name rather than by String. See the Migrating to Swift 3 guide.

Previous usage:

// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"

// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)

// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)

New Swift 3.0 usage:

// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")

// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)

// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)

All of the system notification types are now defined as static constants on Notification.Name; i.e. .UIDeviceBatteryLevelDidChange, .UIApplicationDidFinishLaunching, .UITextFieldTextDidChange, etc.

You can extend Notification.Name with your own custom notifications in order to stay consistent with the system notifications:

// Definition:
extension Notification.Name {
    static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)

filter items in a python dictionary where keys contain a specific string

How about a dict comprehension:

filtered_dict = {k:v for k,v in d.iteritems() if filter_string in k}

One you see it, it should be self-explanatory, as it reads like English pretty well.

This syntax requires Python 2.7 or greater.

In Python 3, there is only dict.items(), not iteritems() so you would use:

filtered_dict = {k:v for (k,v) in d.items() if filter_string in k}

How do I make a request using HTTP basic authentication with PHP curl?

Yahoo has a tutorial on making calls to their REST services using PHP:

Make Yahoo! Web Service REST Calls with PHP

I have not used it myself, but Yahoo is Yahoo and should guarantee for at least some level of quality. They don't seem to cover PUT and DELETE requests, though.

Also, the User Contributed Notes to curl_exec() and others contain lots of good information.

How to loop through an array of objects in swift

Unwrap and downcast the objects to the right type, safely, with if let, before doing the iteration with a simple for in loop.

if let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] 
{
    for object in photos {
        let url = object.url
    }
}

There's also guard let else instead of if let if you prefer having the result available in scope:

guard let currentUser = currentUser, 
    let photos = currentUser.photos as? [ModelAttachment] else 
{
    // break or return
}
// now 'photos' is available outside the guard
for object in photos {
    let url = object.url
}

Are there any log file about Windows Services Status?

The most likely place to find this sort of information is in the event viewer (under Administrative tools in XP or run eventvwr) This is where most services log warnings errors etc.

Android - running a method periodically using postDelayed() call

You should set andrid:allowRetainTaskState="true" to Launch Activity in Manifest.xml. If this Activty is not Launch Activity. you should set android:launchMode="singleTask" at this activity

How to transfer some data to another Fragment?

This is how you use bundle:

Bundle b = new Bundle();
b.putInt("id", id);
Fragment frag= new Fragment();
frag.setArguments(b);

retrieve value from bundle:

 bundle = getArguments();
 if (bundle != null) {
    id = bundle.getInt("id");
 }

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

Also consider devd a small webserver written in go. Binaries for many platforms are available here.

devd -ol path/to/files/to/serve

It's small, fast, and provides some interesting optional features like live-reloading when your files change.

What is Python Whitespace and how does it work?

Every programming language has its own way of structuring the code.
whenever you write a block of code, it has to be organised in a way to be understood by everyone.

Usually used in conditional and classes and defining the definition.
It represents the parent, child and grandchild and further.

Example:

def example()
    print "name"
    print "my name"
example()

Here you can say example() is a parent and others are children.

Show div when radio button selected

 $('input[type="radio"]').change(function(){
      if($("input[name='group']:checked")){
      $(div).show();
    }
  });

How can I use "." as the delimiter with String.split() in java

If performance is an issue, you should consider using StringTokenizer instead of split. StringTokenizer is much much faster than split, even though it is a "legacy" class (but not deprecated).

Usage of @see in JavaDoc?

I use @see to annotate methods of an interface implementation class where the description of the method is already provided in the javadoc of the interface. When we do that I notice that Eclipse pulls up the interface's documentation even when I am looking up method on the implementation reference during code complete

Getting Raw XML From SOAPMessage in Java

this works

 final StringWriter sw = new StringWriter();

try {
    TransformerFactory.newInstance().newTransformer().transform(
        new DOMSource(soapResponse.getSOAPPart()),
        new StreamResult(sw));
} catch (TransformerException e) {
    throw new RuntimeException(e);
}
System.out.println(sw.toString());
return sw.toString();

Codeigniter LIKE with wildcard(%)

  $this->db->like('title', 'match', 'before'); 
 // Produces: WHERE title LIKE '%match' 

 $this->db->like('title', 'match', 'after'); 
// Produces: WHERE title LIKE 'match%' 

$this->db->like('title', 'match', 'both'); 
// Produces: WHERE title LIKE '%match%'

Confusing "duplicate identifier" Typescript error message

Problem was solved by simply:

  1. Deleting the node_modules folder
  2. Running npm install to get all packages with correct versions

In my case, the problem occurred after changing Git branches, where a new branch was using a different set of node modules. The old branch was using TypeScript v1.8, the new one v2.0

How can I edit a .jar file?

Here's what I did:

  • Extracted the files using WinRAR
  • Made my changes to the extracted files
  • Opened the original JAR file with WinRAR
  • Used the ADD button to replace the files that I modified

That's it. I have tested it with my Nokia and it's working for me.

How do we change the URL of a working GitLab install?

You did everything correctly!

You might also change the email configuration, depending on if the email server is also the same server. The email configuration is in gitlab.yml for the mails sent by GitLab and also the admin-email.

How can I remove an element from a list, with lodash?

In Addition to @thefourtheye answer, using predicate instead of traditional anonymous functions:

  _.remove(obj.subTopics, (currentObject) => {
        return currentObject.subTopicId === stToDelete;
    });

OR

obj.subTopics = _.filter(obj.subTopics, (currentObject) => {
    return currentObject.subTopicId !== stToDelete;
});

How can I pass data from Flask to JavaScript in a template?

Working answers are already given but I want to add a check that acts as a fail-safe in case the flask variable is not available. When you use:

var myVariable = {{ flaskvar | tojson }};

if there is an error that causes the variable to be non existent, resulting errors may produce unexpected results. To avoid this:

{% if flaskvar is defined and flaskvar %}
var myVariable = {{ flaskvar | tojson }};
{% endif %}

Dots in URL causes 404 with ASP.NET mvc and IIS

Also, (related) check the order of your handler mappings. We had a .ashx with a .svc (e.g. /foo.asmx/bar.svc/path) in the path after it. The .svc mapping was first so 404 for the .svc path which matched before the .asmx. Havn't thought too much but maybe url encodeing the path would take care of this.

No provider for Http StaticInjectorError

In order to use Http in your app you will need to add the HttpModule to your app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';
...
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ]

EDIT

As mentioned in the comment below, HttpModule is deprecated now, use import { HttpClientModule } from '@angular/common/http'; Make sure HttpClientModule in your imports:[] array

Undoing accidental git stash pop

Try using How to recover a dropped stash in Git? to find the stash you popped. I think there are always two commits for a stash, since it preserves the index and the working copy (so often the index commit will be empty). Then git show them to see the diff and use patch -R to unapply them.

What is the fastest factorial function in JavaScript?

One line solution for Iterative and Recursive options;

const rf = n => 1 === n ? 1 : rf( n - 1 ) * n;

const sf = n => {for (var i = n, c = 1; i > 1; i --) c *= i; return c;}

Repeat a string in JavaScript a number of times

Convenient if you repeat yourself a lot:

_x000D_
_x000D_
String.prototype.repeat = String.prototype.repeat || function(n){_x000D_
  n= n || 1;_x000D_
  return Array(n+1).join(this);_x000D_
}_x000D_
_x000D_
alert(  'Are we there yet?\nNo.\n'.repeat(10)  )
_x000D_
_x000D_
_x000D_

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

ASP.NET custom error page - Server.GetLastError() is null

A combination of what NailItDown and Victor said. The preferred/easiest way is to use your Global.Asax to store the error and then redirect to your custom error page.

Global.asax:

    void Application_Error(object sender, EventArgs e) 
{
    // Code that runs when an unhandled error occurs
    Exception ex = Server.GetLastError();
    Application["TheException"] = ex; //store the error for later
    Server.ClearError(); //clear the error so we can continue onwards
    Response.Redirect("~/myErrorPage.aspx"); //direct user to error page
}

In addition, you need to set up your web.config:

  <system.web>
    <customErrors mode="RemoteOnly" defaultRedirect="~/myErrorPage.aspx">
    </customErrors>
  </system.web>

And finally, do whatever you need to with the exception you've stored in your error page:

protected void Page_Load(object sender, EventArgs e)
{

    // ... do stuff ...
    //we caught an exception in our Global.asax, do stuff with it.
    Exception caughtException = (Exception)Application["TheException"];
    //... do stuff ...
}

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Try using SCP on Windows to transfer files, you can download SCP from Putty's website. Then try running:

pscp.exe filename.extension [email protected]:directory/subdirectory

There is a full length guide here.

port forwarding in windows

I've used this little utility whenever the need arises: http://www.analogx.com/contents/download/network/pmapper/freeware.htm

The last time this utility was updated was in 2009. I noticed on my Win10 machine, it hangs for a few seconds when opening new windows sometimes. Other then that UI glitch, it still does its job fine.

CSS: 100% width or height while keeping aspect ratio?

Nowadays one can use vw and vh units, which represent 1% of the viewport's width and height respectively.

https://css-tricks.com/fun-viewport-units/

So, for example:

img {
  max-width: 100vw;
  max-height: 100vh;
}

... will make the image as wide as tall as possible, maintaining aspect ratio, but without being wider or higher than 100% of the viewport.

How do I use Safe Area Layout programmatically?

Use constraints with visual format and you get respect for the safe area for free.

class ViewController: UIViewController {

    var greenView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        greenView.backgroundColor = .green
        view.addSubview(greenView)
    }
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        greenView.translatesAutoresizingMaskIntoConstraints = false
        let views : [String:Any] = ["greenView":greenView]
        view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[greenView]-|", options: [], metrics: nil, views: views))
        view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[greenView]-|", options: [], metrics: nil, views: views))
    }
}

result

Deploying website: 500 - Internal server error

Server Error 500 - Internal server error. There is a problem with the resource you are looking for, and it cannot be displayed. Goddady. Hosting - Web - Economy - Windows Plesk

In my case, I replace this code:

<configuration> 
  <system.webServer> 
    <httpErrors errorMode="Detailed" /> 
    <asp scriptErrorSentToBrowser="true"/> 
  </system.webServer> 
  <system.web> 
    <customErrors mode="Off"/>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web> 
</configuration>

Then change framework 3.5 to framework 4. It shows my detailed error. I delete code in:

<httpModules></httpModules>

It solved my problem.

How do I do a HTTP GET in Java?

If you dont want to use external libraries, you can use URL and URLConnection classes from standard Java API.

An example looks like this:

String urlString = "http://wherever.com/someAction?param1=value1&param2=value2....";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
// Do what you want with that stream

How to make div background color transparent in CSS

From https://developer.mozilla.org/en-US/docs/Web/CSS/background-color

To set background color:

/* Hexadecimal value with color and 100% transparency*/
background-color: #11ffee00;  /* Fully transparent */

/* Special keyword values */
background-color: transparent;

/* HSL value with color and 100% transparency*/
background-color: hsla(50, 33%, 25%, 1.00);  /* 100% transparent */

/* RGB value with color and 100% transparency*/
background-color: rgba(117, 190, 218, 1.0);  /* 100% transparent */

How to delete duplicate lines in a file without sorting it in Unix?

An alternative way using Vim(Vi compatible):

Delete duplicate, consecutive lines from a file:

vim -esu NONE +'g/\v^(.*)\n\1$/d' +wq

Delete duplicate, nonconsecutive and nonempty lines from a file:

vim -esu NONE +'g/\v^(.+)$\_.{-}^\1$/d' +wq

SQL Server 2008 Row Insert and Update timestamps

try

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    [CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [smalldatetime] NOT NULL

)

PS I think a smalldatetime is good enough. You may decide differently.

Can you not do this at the "moment of impact" ?

In Sql Server, this is common:

Update dbo.MyTable 
Set 

ColA = @SomeValue , 
UpdateDS = CURRENT_TIMESTAMP
Where...........

Sql Server has a "timestamp" datatype.

But it may not be what you think.

Here is a reference:

http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

Here is a little RowVersion (synonym for timestamp) example:

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)


INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Maybe a complete working example:

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS

BEGIN

Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
triggerInsertedTable.Name = myAlias.Name

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Matching on the "Name" value is probably not wise.

Try this more mainstream example with a SurrogateKey

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    SurrogateKey int not null Primary Key Identity (1001,1),
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS

BEGIN

   UPDATE dbo.Names
    SET UpdateTS = CURRENT_TIMESTAMP
    From  dbo.Names myAlias
    WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Only variable references should be returned by reference - Codeigniter

Edit filename: core/Common.php, line number: 257

Before

return $_config[0] =& $config; 

After

$_config[0] =& $config;
return $_config[0]; 

Update

Added by NikiC

In PHP assignment expressions always return the assigned value. So $_config[0] =& $config returns $config - but not the variable itself, but a copy of its value. And returning a reference to a temporary value wouldn't be particularly useful (changing it wouldn't do anything).

Update

This fix has been merged into CI 2.2.1 (https://github.com/bcit-ci/CodeIgniter/commit/69b02d0f0bc46e914bed1604cfbd9bf74286b2e3). It's better to upgrade rather than modifying core framework files.

How can I convert string date to NSDate?

try this:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /* find out and place date format from 
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
let date = dateFormatter.dateFromString(/* your_date_string */)

For further query, check NSDateFormatter and DateFormatter classes of Foundation framework for Objective-C and Swift, respectively.

Swift 3 and later (Swift 4 included)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
guard let date = dateFormatter.date(from: /* your_date_string */) else {
   fatalError("ERROR: Date conversion failed due to mismatched format.")
}

// use date constant here

XML Error: There are multiple root elements

If you're in charge (or have any control over the web service), get them to add a unique root element!

If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.

Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.

How can I remove jenkins completely from linux

For sentOs, it's works for me At first stop service by sudo service jenkins stop

Than remove by sudo yum remove jenkins

How to check internet access on Android? InetAddress never times out

Just create the following class which checks for an internet connection:

public class ConnectionStatus {

    private Context _context;

    public ConnectionStatus(Context context) {
        this._context = context;
    }

    public boolean isConnectionAvailable() {
        ConnectivityManager connectivity = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }
        return false;
    }
}

This class simply contains a method which returns the boolean value of the connection status. Therefore in simple terms, if the method finds a valid connection to the Internet, the return value is true, otherwise false if no valid connection is found.

The following method in the MainActivity then calls the result from the method previously described, and prompts the user to act accordingly:

public void addListenerOnWifiButton() {
        Button btnWifi = (Button)findViewById(R.id.btnWifi);

        iia = new ConnectionStatus(getApplicationContext());

        isConnected = iia.isConnectionAvailable();
        if (!isConnected) {
            btnWifi.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                    Toast.makeText(getBaseContext(), "Please connect to a hotspot",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
        else {
            btnWifi.setVisibility(4);
            warning.setText("This app may use your mobile data to update events and get their details.");
        }
    }

In the above code, if the result is false, (therefore there is no internet connection, the user is taken to the Android wi-fi panel, where he is prompted to connect to a wi-fi hotspot.

jQuery: Get the cursor position of text in input without browser specific code?

You can't do this without some browser specific code, since they implement text select ranged slightly differently. However, there are plugins that abstract this away. For exactly what you're after, there's the jQuery Caret (jCaret) plugin.

For your code to get the position you could do something like this:

$("#myTextInput").bind("keydown keypress mousemove", function() {
  alert("Current position: " + $(this).caret().start);
});

You can test it here.

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

I was facing the same issue. I noticed that in my index i had both the "on device ready" and the "document.ready" function, so removing one of them fixed my problem :)

Gridview get Checkbox.Checked value

You want an independent for loop for all the rows in grid view, then refer the below link

http://nikhilsreeni.wordpress.com/asp-net/checkbox/

Select all checkbox in Gridview

CheckBox cb = default(CheckBox);
for (int i = 0; i <= grdforumcomments.Rows.Count – 1; i++)
{
    cb = (CheckBox)grdforumcomments.Rows[i].Cells[0].FindControl(“cbSel”);

    cb.Checked = ((CheckBox)sender).Checked;
}

Select checked rows to a dataset; For gridview multiple edit

CheckBox cb = default(CheckBox);

foreach (GridViewRow row in grdforumcomments.Rows)
{
    cb = (CheckBox)row.FindControl("cbsel");
    if (cb.Checked)
    {
        drArticleCommentsUpdates = dtArticleCommentsUpdates.NewRow();
        drArticleCommentsUpdates["Id"] = dgItem.Cells[0].Text;
        drArticleCommentsUpdates["Date"] = System.DateTime.Now;dtArticleCommentsUpdates.Rows.Add(drArticleCommentsUpdates);
    }
}

Copy entire directory contents to another directory?

With Groovy, you can leverage Ant to do:

new AntBuilder().copy( todir:'/path/to/destination/folder' ) {
  fileset( dir:'/path/to/src/folder' )
}

AntBuilder is part of the distribution and the automatic imports list which means it is directly available for any groovy code.

PHP output showing little black diamonds with a question mark

I ran the "detect encoding" code after my collation change in phpmyadmin and now it comes up as Latin_1.

but here is something I came across looking a different data anomaly in my application and how I fixed it:

I just imported a table that has mixed encoding (with diamond question marks in some lines, and all were in the same column.) so here is my fix code. I used utf8_decode process that takes the undefined placeholder and assigns a plain question mark in the place of the "diamond question mark " then I used str_replace to replace the question mark with a space between quotes. here is the [code]

    include 'dbconnectfile.php';

  //// the variable $db comes from my db connect file
   /// inx is my auto increment column
   /// broke_column is the column I need to fix

      $qwy = "select inx,broke_column from Table ";
      $res = $db->query($qwy); 

      while ($data = $res->fetch_row()) {
      for ($m=0; $m<$res->field_count; $m++) {
           if ($m==0){ 
           $id=0;
           $id=$data[$m];
       echo $id;
           }else if ($m==1){ 
             $fix=0;
             $fix=$data[$m];


             $fix = utf8_decode($fix);
             $fixx =str_replace("?"," ",$fix);

        echo $fixx;

        ////I echoed the data to the screen because I like to see something as I execute it :)
            }
            }
         $insert= "UPDATE Table SET broke_column='".$fixx."'  where inx='".$id."'";
          $insresult= $db->query($insert);
      echo"<br>";
        }

        ?>        

What is trunk, branch and tag in Subversion?

The answer by David Schmitt sums things up very well, but I think it is important to note that, to SVN, the terms 'branch', 'tag', and 'trunk' don't mean anything. These terms are purely semantic and only affect the way we, as users of the system, treat those directories. One could easily name them 'main', 'test', and 'releases.'; As long as everyone using the system understands how to use each section properly, it really doesn't matter what they're called.

How to import Google Web Font in CSS file?

Download the font ttf/other format files, then simply add this CSS code example:

_x000D_
_x000D_
@font-face { font-family: roboto-regular; _x000D_
    src: url('../font/Roboto-Regular.ttf'); } _x000D_
h2{_x000D_
 font-family: roboto-regular;_x000D_
}
_x000D_
_x000D_
_x000D_

Get value from input (AngularJS)

If your markup is bound to a controller, directive or anything else with a $scope:

console.log($scope.movie);

Notice: Array to string conversion in

mysql_fetch_assoc returns an array so you can not echo an array, need to print_r() otherwise particular string $money['money'].

Differences between Emacs and Vim

There is a huge difference on a day-to-day level - Vim (or any vi variant) is inherently modal (you go into command modes where you cannot edit) and Emacs (along with most other editors) are not.

Sure, using menus and such you don't have to actually enter command mode in Vim - at first. But to use even a tiny fraction of the power of Vim you will. That is at the heart of the Vim/Emacs debate.

Personally, I also think Emacs is far more extensible. You can find Elisp packages for many things.

I am curious, though, why you are thinking to learn one of these over a more traditional IDE. What is it you want to learn one of these for?

External resource not being loaded by AngularJs

Whitelist the resource with $sceDelegateProvider

This is caused by a new security policy put in place in Angular 1.2. It makes XSS harder by preventing a hacker from dialling out (i.e. making a request to a foreign URL, potentially containing a payload).

To get around it properly you need to whitelist the domains you want to allow, like this:

angular.module('myApp',['ngSanitize']).config(function($sceDelegateProvider) {
  $sceDelegateProvider.resourceUrlWhitelist([
    // Allow same origin resource loads.
    'self',
    // Allow loading from our assets domain.  Notice the difference between * and **.
    'http://srv*.assets.example.com/**'
  ]);

  // The blacklist overrides the whitelist so the open redirect here is blocked.
  $sceDelegateProvider.resourceUrlBlacklist([
    'http://myapp.example.com/clickThru**'
  ]);
});

This example is lifted from the documentation which you can read here:

https://docs.angularjs.org/api/ng/provider/$sceDelegateProvider

Be sure to include ngSanitize in your app to make this work.

Disabling the feature

If you want to turn off this useful feature, and you're sure your data is secure, you can simply allow **, like so:

angular.module('app').config(function($sceDelegateProvider) {
  $sceDelegateProvider.resourceUrlWhitelist(['**']);
});

What is /var/www/html?

In the most shared hosts you can't set it.

On a VPS or dedicated server, you can set it, but everything has its price.

On shared hosts, in general you receive a Linux account, something such as /home/(your username)/, and the equivalent of /var/www/html turns to /home/(your username)/public_html/ (or something similar, such as /home/(your username)/www)

If you're accessing your account via FTP, you automatically has accessing the your */home/(your username)/ folder, just find the www or public_html and put your site in it.

If you're using absolute path in the code, bad news, you need to refactor it to use relative paths in the code, at least in a shared host.

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

To get current date/time in javascript:

var date = new Date();

If you need milliseconds for easy server-side interpretation use

var value = date.getTime();

For formatting dates into a user readable string see this

Then just write to hidden field:

document.getElementById("DATE").value = value;

Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress

I had same issue as mentioned " Your PHP installation appears to be missing the MySQL extension which is required by WordPress" in resellerclub hosting.

I went through this thread and came to know that php version should be greater than > 5.6 so that wordpress will automatically gets converted to mysqli

Then logged into my cpanel searched for php in cpanel to check for the version, luckly was able to find that my version of php was 5.2 and changed that to 5.6 by making sure mysqli is tick marked in the option window and saved it is working fine now.

Windows batch files: .bat vs .cmd?

RE: Apparently when command.com is invoked is a bit of a complex mystery;

Several months ago, during the course of a project, we had to figure out why some programs that we wanted to run under CMD.EXE were, in fact, running under COMMAND.COM. The "program" in question was a very old .BAT file, that still runs daily.

We discovered that the reason the batch file ran under COMMAND.COM is that it was being started from a .PIF file (also ancient). Since the special memory configuration settings available only through a PIF have become irrelevant, we replaced it with a conventional desktop shortcut.

The same batch file, launched from the shortcut, runs in CMD.EXE. When you think about it, this makes sense. The reason that it took us so long to figure it out was partially due to the fact that we had forgotten that its item in the startup group was a PIF, because it had been in production since 1998.

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

How to request Administrator access inside a batch file

There's also the FSUTIL query from this post which is also linked at ss64.com that has the following code:

@Echo Off
Setlocal
:: First check if we are running As Admin/Elevated
FSUTIL dirty query %SystemDrive% >nul
if %errorlevel% EQU 0 goto START

::Create and run a temporary VBScript to elevate this batch file
   Set _batchFile=%~f0
   Set _Args=%*
   :: double up any quotes
   Set _batchFile=""%_batchFile:"=%""
   Set _Args=%_Args:"=""%

   Echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\~ElevateMe.vbs"
   Echo UAC.ShellExecute "cmd", "/c ""%_batchFile% %_Args%""", "", "runas", 1 >> "%temp%\~ElevateMe.vbs"

   cscript "%temp%\~ElevateMe.vbs" 
   Exit /B

:START
:: set the current directory to the batch file location
cd /d %~dp0
:: Place the code which requires Admin/elevation below
Echo We are now running as admin [%1] [%2]
pause

As long as FSUTIL is around, it's a reliable alternative.

How to log request and response body with Retrofit-Android?

I hope this code will help you to logging .
you just need to add interceptor in your Build.Gradle then make RetrofitClient .

First Step

Add this line to your build.gradle

 implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1' 

Second Step

Make your Retrofit Client


   public class RetrofitClient {

    private Retrofit retrofit;
    private static OkHttpClient.Builder httpClient =
            new OkHttpClient.Builder();
    private static RetrofitClient instance = null;
    private static ApiServices service = null;
    private static HttpLoggingInterceptor logging =
            new HttpLoggingInterceptor();

    private RetrofitClient(final Context context) {
        httpClient.interceptors().add(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request.Builder builder = originalRequest.newBuilder().
                        method(originalRequest.method(), originalRequest.body());
                okhttp3.Response response = chain.proceed(builder.build());
                /*
                Do what you want
                 */
                return response;
            }
        });

        if (BuildConfig.DEBUG) {
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            // add logging as last interceptor
            httpClient.addInterceptor(logging);
        }

        retrofit = new Retrofit.Builder().client(httpClient.build()).
                baseUrl(Constants.BASE_URL).
                addConverterFactory(GsonConverterFactory.create()).build();
        service = retrofit.create(ApiServices.class);
    }


    public static RetrofitClient getInstance(Context context) {
        if (instance == null) {
            instance = new RetrofitClient(context);
        }
        return instance;
    }

    public ApiServices getApiService() {
        return service;
    }
}

Calling

RetrofitClient.getInstance(context).getApiService().yourRequestCall(); 

Display UIViewController as Popup in iPhone

Modal Popups in Interface Builder (Storyboards)

Step 1

On the ViewController you want as your modal popup, make the background color of the root UIView clear. Set Clear Color on root view Tip: Do not use the root UIView as your popup. Add a new UIView that is smaller to be your popup.

Step 2

Create a Segue to the ViewController that has your popup. Select "Present Modally". Segue

Two Methods To Create Popup From Here

Method One - Using the Segue

Select the Segue and change Presentation to "Over Current Context": Over Current Context

Method Two - Using the View Controller

Select the ViewController Scene that is your popup. In Attributes Inspector, under View Controller section, set Presentation to "Over Current Context": ViewController

Either method will work. That should do it!

Finished Product

I get exception when using Thread.sleep(x) or wait()

Have a look at this excellent brief post on how to do this properly.

Essentially: catch the InterruptedException. Remember that you must add this catch-block. The post explains this a bit further.

Java - get the current class name?

Here is a Android variant, but same principle can be used in plain Java too.

private static final String TAG = YourClass.class.getSimpleName();
private static final String TAG = YourClass.class.getName();

Javascript - Replace html using innerHTML

You are replacing the starting tag and then putting that back in innerHTML, so the code will be invalid. Make all the replacements before you put the code back in the element:

var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;

AngularJS custom filter function

Additionally, if you want to use the filter in your controller the same way you do it here:

<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}
</div>

You could do something like:

var filteredItems =  $scope.$eval('items | filter:filter:criteriaMatch(criteria)');

Writelines writes lines without newline, Just fills the file

As others have noted, writelines is a misnomer (it ridiculously does not add newlines to the end of each line).

To do that, explicitly add it to each line:

with open(dst_filename, 'w') as f:
    f.writelines(s + '\n' for s in lines)

Removing cordova plugins from the project

I do it with this python one-liner:

python -c "import subprocess as sp;[sp.call('cordova plugin rm ' + p.split()[0], shell=True) for p in sp.check_output('cordova plugin', shell=True).split('\n') if p]"

Obviously it doesn't handle any sort of error conditions, but it gets the job done.

How to prevent "The play() request was interrupted by a call to pause()" error?

I have used a trick to counter this issue. Define a global variable var audio;

and in the function check

if(audio === undefined)
{
   audio = new Audio(url);
}

and in the stop function

audio.pause();
audio = undefined;

so the next call of audio.play, audio will be ready from '0' currentTime

I used

audio.pause();
audio.currentTime =0.0; 

but it didn't work. Thanks.