Programs & Examples On #Apm

APM generally refers to Application Performance Management. The best in class tools provide real-time access to detailed information about the performance of a system and its components (including transaction tracing, database and external system response times, etc.)

Please add a @Pipe/@Directive/@Component annotation. Error

I had a component declared without the styleUrls property, like this:

@Component({
    selector: 'app-server',
    templateUrl: './server.component.html'
})

instead of:

@Component({
    selector: 'app-server',
    templateUrl: './server.component.html',
    styleUrls: ['./server.component.css']
})

Adding in the styleUrls property solved the issue.

Hibernate Error executing DDL via JDBC Statement

you have to be careful because reseved words are not only for table names, also you have to check column names, my mistake was that one of my columns was named "user". If you are using PostgreSQL the correct dialect is: org.hibernate.dialect.PostgreSQLDialect

cheers.

Angular 2 : No NgModule metadata found

I had this issue when i cloned from a git repository and I had it resolved when I created a new project and re-inserted the src folder from the old project.

The src folder is the only folder needed when deploying your angular application but you must reconfigure the dev environment, using this solution.

Error: Unexpected value 'undefined' imported by the module

For me, I just did a CTRL+C and YES .
And I restart by

ionic serve 

This works for me.

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

your manifest application name should contain application class name. Like

<application
        android:name="your package name.MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:theme="@style/AppTheme"> 

UIAlertView first deprecated IOS 9

From iOS8 Apple provide new UIAlertController class which you can use instead of UIAlertView which is now deprecated, it is also stated in deprecation message:

UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead

So you should use something like this

UIAlertController * alert = [UIAlertController
                alertControllerWithTitle:@"Title"
                                 message:@"Message"
                          preferredStyle:UIAlertControllerStyleAlert];



UIAlertAction* yesButton = [UIAlertAction
                    actionWithTitle:@"Yes, please"
                              style:UIAlertActionStyleDefault
                            handler:^(UIAlertAction * action) {
                                //Handle your yes please button action here
                            }];

UIAlertAction* noButton = [UIAlertAction
                        actionWithTitle:@"No, thanks"
                                  style:UIAlertActionStyleDefault
                                handler:^(UIAlertAction * action) {
                                   //Handle no, thanks button                
                                }];

[alert addAction:yesButton];
[alert addAction:noButton];

[self presentViewController:alert animated:YES completion:nil];

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

You can get this error if you have invalid 9-patch files. If there is anything apart from black and transparent in the border pixels you will get this error. The easiest way of fixing this is to open it up in Android Studio and modify the borders. Just adding and removing one pixel is enough.

It's worth noting that you won't see the bad pixels in AS, as the editor sets anything not black to transparent, but you will need to modify the file for it to save these changes.

Saving binary data as file using JavaScript from a browser

Use FileSaver.js. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it:
     https://github.com/eligrey/FileSaver.js

Minified version is really small at < 2.5KB, gzipped < 1.2KB.

Usage:

/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);

You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
     https://github.com/eligrey/Blob.js

Consider StreamSaver.js if you have files larger than blob's size limitations.

Complete example:

_x000D_
_x000D_
/* Two options_x000D_
 * 1. Get FileSaver.js from here_x000D_
 *     https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
 *     <script src="FileSaver.min.js" />_x000D_
 *_x000D_
 * Or_x000D_
 *_x000D_
 * 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
 *    then a simple implementation of saveAs function can be:_x000D_
 */_x000D_
function saveAs(blob, fileName) {_x000D_
    var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
    var anchorElem = document.createElement("a");_x000D_
    anchorElem.style = "display: none";_x000D_
    anchorElem.href = url;_x000D_
    anchorElem.download = fileName;_x000D_
_x000D_
    document.body.appendChild(anchorElem);_x000D_
    anchorElem.click();_x000D_
_x000D_
    document.body.removeChild(anchorElem);_x000D_
_x000D_
    // On Edge, revokeObjectURL should be called only after_x000D_
    // a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
    setTimeout(function() {_x000D_
        window.URL.revokeObjectURL(url);_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
    // convert base64 string to byte array_x000D_
    var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
    var byteNumbers = new Array(byteCharacters.length);_x000D_
    for (var i = 0; i < byteCharacters.length; i++) {_x000D_
        byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
    }_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
    _x000D_
    // now that we have the byte array, construct the blob from it_x000D_
    var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
    var fileName1 = "cool.gif";_x000D_
    saveAs(blob1, fileName1);_x000D_
_x000D_
    // saving text file_x000D_
    var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
    var fileName2 = "cool.txt";_x000D_
    saveAs(blob2, fileName2);_x000D_
})();
_x000D_
_x000D_
_x000D_


Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js for supporting IE 11).
You can also save from a canvas element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.

Demos: https://eligrey.com/demos/FileSaver.js/

Blog post by author of FileSaver.js: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side

Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers

Note 2: Failed to execute 'atob' on 'Window'

Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
                See http://caniuse.com/#search=blob

Note 4: IE < 10 support (I've not tested this part):
                https://github.com/eligrey/FileSaver.js#ie--10
                https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476

Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html

Note 5: Creating a BLOB from a Base64 string in JavaScript

Note 6: FileSaver.js examples: https://github.com/eligrey/FileSaver.js#examples

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

Add just these two lines before the datetime property in your model

[DataType(DataType.Date)] 
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

and result will be :Date Picker in MVC Application

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

I had the same error statement following a "Failed to access resource" error message:

Command

#cat callflow-java-logger-1.log.0

Output

Dec 09, 2015 8:09:03 AM org.apache.catalina.loader.WebappLoader startInternal
SEVERE: LifecycleException 
java.io.IOException: Failed to access resource /WEB-INF/lib/ojdbc14.jar

In my case the solution was changing the connector permissions

-rw------- 1 owner creator size date ojdbc14.jar

This file in question wasn't initially located at /WEB-INF/lib, which was probably due to how BIRT works. It can be tricky if you are dealing with a higher number of files.

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

I ran into this problem, which resolved itself after I stopped using a proxy. Maybe CloudFront is blacklisting some IPs.

Python: import module from another directory at the same level in project hierarchy

From Python 2.5 onwards, you can use

from ..Modules import LDAPManager

The leading period takes you "up" a level in your heirarchy.

See the Python docs on intra-package references for imports.

How to convert image into byte array and byte array to base64 String in android?

Try this:

// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();
}

// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg), 
                       Base64.NO_WRAP);

SSLHandshakeException: No subject alternative names present

Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.

But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.

static {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {
            public boolean verify(String hostname, SSLSession session)
            {
                // ip address of the service URL(like.23.28.244.244)
                if (hostname.equals("23.28.244.244"))
                    return true;
                return false;
            }
        });
}

If you happen to be using Java 8, there is a much slicker way of achieving the same result:

static {
    HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

Configuring RollingFileAppender in log4j

I'm suspicious of the ActiveFileName property. According to the log4j javadoc, there isn't such a property on the TimeBasedRollingPolicy class. (No setActiveFileName or getActiveFileName methods.)

I don't know what specifying an unknown property would do, but it is possible that it will cause the containing object to be abandoned, and that could lead to the warnings that you saw.

Try leaving it out and seeing what happens.

Client to send SOAP request and receive response

The best practice is to reference the WSDL and use it like a web service reference. It's easier and works better, but if you don't have the WSDL, the XSD definitions are a good piece of code.

Getting Raw XML From SOAPMessage in Java

Using Transformer Factory:-

public static String printSoapMessage(final SOAPMessage soapMessage) throws TransformerFactoryConfigurationError,
            TransformerConfigurationException, SOAPException, TransformerException
    {
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();

        // Format it
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        final Source soapContent = soapMessage.getSOAPPart().getContent();

        final ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
        final StreamResult result = new StreamResult(streamOut);
        transformer.transform(soapContent, result);

        return streamOut.toString();
    }

How do I make the text box bigger in HTML/CSS?

there are many options that would change the height of an input box. padding, font-size, height would all do this. different combinations of these produce taller input boxes with different styles. I suggest just changing the font-size (and font-family for looks) and add some padding to make it even taller and also more appealing. I will give you an example of all three style though:

#signin input {
font-size:20px;
}

OR

#signin input {
padding:10px;
}

OR

#signin input {
height:24px;
}

This is the combination of the three that I recommend:

#signin input {
font-size:20px;font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; font-weight: 300;
padding:10px;
}

Angular2 *ngIf check object array length in template

This article helped me alot figuring out why it wasn't working for me either. It give me a lesson to think of the webpage loading and how angular 2 interacts as a timeline and not just the point in time i'm thinking of. I didn't see anyone else mention this point, so I will...

The reason the *ngIf is needed because it will try to check the length of that variable before the rest of the OnInit stuff happens, and throw the "length undefined" error. So thats why you add the ? because it won't exist yet, but it will soon.

Filter values only if not null using lambda in Java8

Leveraging the power of java.util.Optional#map():

List<Car> requiredCars = cars.stream()
  .filter (car -> 
    Optional.ofNullable(car)
      .map(Car::getName)
      .map(name -> name.startsWith("M"))
      .orElse(false) // what to do if either car or getName() yields null? false will filter out the element
    )
  .collect(Collectors.toList())
;

Batch command to move files to a new directory

Something like this might help:

SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=

The important part is the first line. It takes the output of the internal DATE value and parses it into an environmental variable named Today, in the format CCYYMMDD, as in '20110407`.

The %Date:~10,4% says to extract a *substring of the Date environmental variable 'Thu 04/07/2011' (built in - type echo %Date% at a command prompt) starting at position 10 for 4 characters (2011). It then concatenates another substring of Date: starting at position 4 for 2 chars (04), and then concats two additional characters starting at position 7 (07).

*The substring value starting points are 0-based.

You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.

How to add images to README.md on GitHub?

Add image in your repository from upload file option then in README file

![Alt text]("enter repository image URL here") 

How to insert data to MySQL having auto incremented primary key?

I used something like this to type only values in my SQL request. There are too much columns in my case, and im lazy.

insert into my_table select max(id)+1, valueA, valueB, valueC.... from my_table; 

ECMAScript 6 arrow function that returns an object

You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:

p => ({ foo: 'bar' });

You don't need to wrap any other expression into parentheses:

p => 10;
p => 'foo';
p => true;
p => [1,2,3];
p => null;
p => /^foo$/;

and so on.

Reference: MDN - Returning object literals

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

It seems that when this error appears it is an indication that the selenium-java plugin for maven is out-of-date.

Changing the version in the pom.xml should fix the problem

How to identify unused CSS definitions from multiple CSS files in a project

I have just found this site – http://unused-css.com/

Looks good but I would need to thoroughly check its outputted 'clean' css before uploading it to any of my sites.

Also as with all these tools I would need to check it didn't strip id's and classes with no style but are used as JavaScript selectors.

The below content is taken from http://unused-css.com/ so credit to them for recommending other solutions:

Latish Sehgal has written a windows application to find and remove unused CSS classes. I haven't tested it but from the description, you have to provide the path of your html files and one CSS file. The program will then list the unused CSS selectors. From the screenshot, it looks like there is no way to export this list or download a new clean CSS file. It also looks like the service is limited to one CSS file. If you have multiple files you want to clean, you have to clean them one by one.

Dust-Me Selectors is a Firefox extension (for v1.5 or later) that finds unused CSS selectors. It extracts all the selectors from all the stylesheets on the page you're viewing, then analyzes that page to see which of those selectors are not used. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they're encountered. This tool is supposed to be able to spider a whole website but I unfortunately could make it work. Also, I don't believe you can configure and download the CSS file with the styles removed.

Topstyle is a windows application including a bunch of tools to edit CSS. I haven't tested it much but it looks like it has the ability to removed unused CSS selectors. This software costs 80 USD.

Liquidcity CSS cleaner is a php script that uses regular expressions to check the styles of one page. It will tell you the classes that aren't available in the HTML code. I haven't tested this solution.

Deadweight is a CSS coverage tool. Given a set of stylesheets and a set of URLs, it determines which selectors are actually used and lists which can be "safely" deleted. This tool is a ruby module and will only work with rails website. The unused selectors have to be manually removed from the CSS file.

Helium CSS is a javascript tool for discovering unused CSS across many pages on a web site. You first have to install the javascript file to the page you want to test. Then, you have to call a helium function to start the cleaning.

UnusedCSS.com is web application with an easy to use interface. Type the url of a site and you will get a list of CSS selectors. For each selector, a number indicates how many times a selector is used. This service has a few limitations. The @import statement is not supported. You can't configure and download the new clean CSS file.

CSSESS is a bookmarklet that helps you find unused CSS selectors on any site. This tool is pretty easy to use but it won't let you configure and download clean CSS files. It will only list unused CSS files.

Decimal to Hexadecimal Converter in Java

Check out the code below for decimal to hexadecimal conversion,

import java.util.Scanner;

public class DecimalToHexadecimal
{
   public static void main(String[] args)
   {
      int temp, decimalNumber;
      String hexaDecimal = "";
      char hexa[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter decimal number : ");
      decimalNumber = sc.nextInt();

      while(decimalNumber > 0)
      {
         temp = decimalNumber % 16;
         hexaDecimal = hexa[temp] + hexaDecimal;
         decimalNumber = decimalNumber / 16;
      }

      System.out.print("The hexadecimal value of " + decimalNumber + " is : " + hexaDecimal);      
      sc.close();
   }
}

You can learn more on different ways to convert decimal to hexadecimal in the following link >> java convert decimal to hexadecimal.

How to declare a type as nullable in TypeScript?

i had this same question a while back.. all types in ts are nullable, because void is a subtype of all types (unlike, for example, scala).

see if this flowchart helps - https://github.com/bcherny/language-types-comparison#typescript

Close popup window

Your web_window variable must have gone out of scope when you tried to close the window. Add this line into your _openpageview function to test:

setTimeout(function(){web_window.close();},1000);

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

I would just do:

private static Timer timer;
 private static void Main()
 {
   timer = new Timer(_ => OnCallBack(), null, 1000 * 10,Timeout.Infinite); //in 10 seconds
   Console.ReadLine();
 }

  private static void OnCallBack()
  {
    timer.Dispose();
    Thread.Sleep(3000); //doing some long operation
    timer = new Timer(_ => OnCallBack(), null, 1000 * 10,Timeout.Infinite); //in 10 seconds
  }

And ignore the period parameter, since you're attempting to control the periodicy yourself.


Your original code is running as fast as possible, since you keep specifying 0 for the dueTime parameter. From Timer.Change:

If dueTime is zero (0), the callback method is invoked immediately.

Counting the occurrences / frequency of array elements

My solution with ramda:

const testArray = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4]

const counfFrequency = R.compose(
  R.map(R.length),
  R.groupBy(R.identity),
)

counfFrequency(testArray)

Link to REPL.

How to get index using LINQ?

Simply do :

int index = List.FindIndex(your condition);

E.g.

int index = cars.FindIndex(c => c.ID == 150);

Create Table from JSON Data with angularjs and ng-repeat

To render any json in tabular format:

<table>
    <thead>
      <tr>
        <th ng-repeat="(key, value) in vm.records[0]">{{key}}</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="(key, value) in vm.records">
        <td ng-repeat="(key, value) in value">
          {{value}}
        </td>
      </tr>
    </tbody>
</table>

See complete code in detail with other features

How to check which locks are held on a table

I use a Dynamic Management View (DMV) to capture locks as well as the object_id or partition_id of the item that is locked.

(MUST switch to the Database you want to observe to get object_id)

SELECT 
     TL.resource_type,
     TL.resource_database_id,
     TL.resource_associated_entity_id,
     TL.request_mode,
     TL.request_session_id,
     WT.blocking_session_id,
     O.name AS [object name],
     O.type_desc AS [object descr],
     P.partition_id AS [partition id],
     P.rows AS [partition/page rows],
     AU.type_desc AS [index descr],
     AU.container_id AS [index/page container_id]
FROM sys.dm_tran_locks AS TL
INNER JOIN sys.dm_os_waiting_tasks AS WT 
 ON TL.lock_owner_address = WT.resource_address
LEFT OUTER JOIN sys.objects AS O 
 ON O.object_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.partitions AS P 
 ON P.hobt_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.allocation_units AS AU 
 ON AU.allocation_unit_id = TL.resource_associated_entity_id;

How to get a thread and heap dump of a Java process on Windows that's not running in a console

In addition to using the mentioned jconsole/visualvm, you can use jstack -l <vm-id> on another command line window, and capture that output.

The <vm-id> can be found using the task manager (it is the process id on windows and unix), or using jps.

Both jstack and jps are include in the Sun JDK version 6 and higher.

Using npm behind corporate proxy .pac

If you are behind a corporate network with proxy, i just used a ntlm proxy tool and used the port and proxy provided by ntlm, for instnce i used this configuration:

strict-ssl=false
proxy=http://localhost:3125

I hope this helps.

Android - how to make a scrollable constraintlayout?

in scrollview make height and width 0 add Top_toBottomOfand Bottom_toTopOf constraints that's it.

Postgres integer arrays as parameters?

See: http://www.postgresql.org/docs/9.1/static/arrays.html

If your non-native driver still does not allow you to pass arrays, then you can:

  • pass a string representation of an array (which your stored procedure can then parse into an array -- see string_to_array)

    CREATE FUNCTION my_method(TEXT) RETURNS VOID AS $$ 
    DECLARE
           ids INT[];
    BEGIN
           ids = string_to_array($1,',');
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method(:1)
    

    with :1 = '1,2,3,4'

  • rely on Postgres itself to cast from a string to an array

    CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$ 
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method('{1,2,3,4}')
    
  • choose not to use bind variables and issue an explicit command string with all parameters spelled out instead (make sure to validate or escape all parameters coming from outside to avoid SQL injection attacks.)

    CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$ 
           ...
    END $$ LANGUAGE plpgsql;
    

    then

    SELECT my_method(ARRAY [1,2,3,4])
    

Changing the "tick frequency" on x or y axis in matplotlib?

I like this solution (from the Matplotlib Plotting Cookbook):

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]

tick_spacing = 1

fig, ax = plt.subplots(1,1)
ax.plot(x,y)
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.show()

This solution give you explicit control of the tick spacing via the number given to ticker.MultipleLocater(), allows automatic limit determination, and is easy to read later.

How to replicate vector in c?

https://github.com/jakubgorny47/baku-code/tree/master/c_vector

Here's my implementation. It's basicaly a struct containing pointer to the data, size (in elements), overall allocated space and a size of the type that's being stored in vector to allow use of void pointer.

How do I make a <div> move up and down when I'm scrolling the page?

You might want to check out Remy Sharp's recent article on fixed floating elements at jQuery for Designers, which has a nice video and writeup on how to apply this effect in client script

Open URL in Java to get the content

public class UrlContent{
    public static void main(String[] args) {

        URL url;

        try {
            // get URL content

            String a="http://localhost:8080/TestWeb/index.jsp";
            url = new URL(a);
            URLConnection conn = url.openConnection();

            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(
                               new InputStreamReader(conn.getInputStream()));

            String inputLine;
            while ((inputLine = br.readLine()) != null) {
                    System.out.println(inputLine);
            }
            br.close();

            System.out.println("Done");

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

offsetting an html anchor to adjust for fixed header

I'm facing this problem in a TYPO3 website, where all "Content Elements" are wrapped with something like:

<div id="c1234" class="contentElement">...</div>

and i changed the rendering so it renders like this:

<div id="c1234" class="anchor"></div>
<div class="contentElement">...</div>

And this CSS:

.anchor{
    position: relative;
    top: -50px;
}

The fixed topbar being 40px high, now the anchors work again and start 10px under the topbar.

Only drawback of this technique is you can no longer use :target.

How to test whether a service is running from the command line

if you don't mind to combine the net command with grep you can use the following script.

@echo off
net start | grep -x "Service"
if %ERRORLEVEL% == 2 goto trouble
if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo unknown status
goto end
:trouble
echo trouble
goto end
:started
echo started
goto end
:stopped
echo stopped
goto end
:end

What Makes a Method Thread-safe? What are the rules?

If a method only accesses local variables, it's thread safe. Is that it?

Absolultely not. You can write a program with only a single local variable accessed from a single thread that is nevertheless not threadsafe:

https://stackoverflow.com/a/8883117/88656

Does that apply for static methods as well?

Absolutely not.

One answer, provided by @Cybis, was: "Local variables cannot be shared among threads because each thread gets its own stack."

Absolutely not. The distinguishing characteristic of a local variable is that it is only visible from within the local scope, not that it is allocated on the temporary pool. It is perfectly legal and possible to access the same local variable from two different threads. You can do so by using anonymous methods, lambdas, iterator blocks or async methods.

Is that the case for static methods as well?

Absolutely not.

If a method is passed a reference object, does that break thread safety?

Maybe.

I've done some research, and there is a lot out there about certain cases, but I was hoping to be able to define, by using just a few rules, guidelines to follow to make sure a method is thread safe.

You are going to have to learn to live with disappointment. This is a very difficult subject.

So, I guess my ultimate question is: "Is there a short list of rules that define a thread-safe method?

Nope. As you saw from my example earlier an empty method can be non-thread-safe. You might as well ask "is there a short list of rules that ensures a method is correct". No, there is not. Thread safety is nothing more than an extremely complicated kind of correctness.

Moreover, the fact that you are asking the question indicates your fundamental misunderstanding about thread safety. Thread safety is a global, not a local property of a program. The reason why it is so hard to get right is because you must have a complete knowledge of the threading behaviour of the entire program in order to ensure its safety.

Again, look at my example: every method is trivial. It is the way that the methods interact with each other at a "global" level that makes the program deadlock. You can't look at every method and check it off as "safe" and then expect that the whole program is safe, any more than you can conclude that because your house is made of 100% non-hollow bricks that the house is also non-hollow. The hollowness of a house is a global property of the whole thing, not an aggregate of the properties of its parts.

Does Python have a ternary conditional operator?

You might often find

cond and on_true or on_false

but this lead to problem when on_true == 0

>>> x = 0
>>> print x == 0 and 0 or 1 
1
>>> x = 1
>>> print x == 0 and 0 or 1 
1

where you would expect for a normal ternary operator this result

>>> x = 0
>>> print 0 if x == 0 else 1 
0
>>> x = 1
>>> print 0 if x == 0 else 1 
1

If Cell Starts with Text String... Formula

I'm not sure lookup is the right formula for this because of multiple arguments. Maybe hlookup or vlookup but these require you to have tables for values. A simple nested series of if does the trick for a small sample size

Try =IF(A1="a","pickup",IF(A1="b","collect",IF(A1="c","prepaid","")))

Now incorporate your left argument

=IF(LEFT(A1,1)="a","pickup",IF(LEFT(A1,1)="b","collect",IF(LEFT(A1,1)="c","prepaid","")))

Also note your usage of left, your argument doesn't specify the number of characters, but a set.


7/8/15 - Microsoft KB articles for the above mentioned functions. I don't think there's anything wrong with techonthenet, but I rather link to official sources.

How can I check if a View exists in a Database?

To expand on Kevin's answer.

    private bool CustomViewExists(string viewName)
    {
        using (SalesPad.Data.DataConnection dc = yourconnection)
        {
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(String.Format(@"IF EXISTS(select * FROM sys.views where name = '{0}')
                Select 1
            else
                Select 0", viewName));
            cmd.CommandType = CommandType.Text;
            return Convert.ToBoolean(dc.ExecuteScalar(cmd));
        }
    }

jquery background-color change on focus and blur

Even easier, just CSS can resolve the problem:

input[type="text"], input[type="password"], textarea, select { 
    width: 200px;
    border: 1px solid;
    border-color: #C0C0C0 #E4E4E4 #E4E4E4 #C0C0C0;
    background: #FFF;
    padding: 8px 5px;
    font: 16px Arial, Tahoma, Helvetica, sans-serif;
    -moz-box-shadow: 0 0 5px #C0C0C0;
    -moz-border-radius: 5px;
    -webkit-box-shadow: 0 0 5px #C0C0C0;
    -webkit-border-radius: 5px;
    box-shadow: 0 0 5px #C0C0C0;
    border-radius: 5px;
}
input[type="text"]:focus, input[type="password"]:focus, textarea:focus, select:focus { 
    border-color: #B6D5F7 #B6D5F7 #B6D5F7 #B6D5F7;
    outline: none;
    -moz-box-shadow: 0 0 10px #B6D5F7;
    -webkit-box-shadow: 0 0 10px #B6D5F7;
    box-shadow: 0 0 10px #B6D5F7;
}

How to display loading message when an iFrame is loading?

I have done the following css approach:

<div class="holds-the-iframe"><iframe here></iframe></div>

.holds-the-iframe {
  background:url(../images/loader.gif) center center no-repeat;
}

Forward declaration of a typedef in C++

To "fwd declare a typedef" you need to fwd declare a class or a struct and then you can typedef declared type. Multiple identical typedefs are acceptable by compiler.

long form:

class MyClass;
typedef MyClass myclass_t;

short form:

typedef class MyClass myclass_t;

How to write a file with C in Linux?

You have to do write in the same loop as read.

How to filter for multiple criteria in Excel?

The regular filter options in Excel don't allow for more than 2 criteria settings. To do 2+ criteria settings, you need to use the Advanced Filter option. Below are the steps I did to try this out.

http://www.bettersolutions.com/excel/EDZ483/QT419412321.htm

Set up the criteria. I put this above the values I want to filter. You could do that or put on a different worksheet. Note that putting the criteria in rows will make it an 'OR' filter and putting them in columns will make it an 'AND' filter.

  1. E1 : Letters
  2. E2 : =m
  3. E3 : =h
  4. E4 : =j

I put the data starting on row 5:

  1. A5 : Letters
  2. A6 :
  3. A7 :
  4. ...

Select the first data row (A6) and click the Advanced Filter option. The List Range should be pre-populated. Select the Criteria range as E1:E4 and click OK.

That should be it. Note that I use the '=' operator. You will want to use something a bit different to test for file extensions.

How to set array length in c# dynamically

If you don't want to use a List, ArrayList, or other dynamically-sized collection and then convert to an array (that's the method I'd recommend, by the way), then you'll have to allocate the array to its maximum possible size, keep track of how many items you put in it, and then create a new array with just those items in it:

private Update BuildMetaData(MetaData[] nvPairs)
{
    Update update = new Update();
    InputProperty[] ip = new InputProperty[20];  // how to make this "dynamic"
    int i;
    for (i = 0; i < nvPairs.Length; i++)
    {
        if (nvPairs[i] == null) break;
        ip[i] = new InputProperty(); 
        ip[i].Name = "udf:" + nvPairs[i].Name;
        ip[i].Val = nvPairs[i].Value;
    }
    if (i < nvPairs.Length)
    {
        // Create new, smaller, array to hold the items we processed.
        update.Items = new InputProperty[i];
        Array.Copy(ip, update.Items, i);
    }
    else
    {
        update.Items = ip;
    }
    return update;
}

An alternate method would be to always assign update.Items = ip; and then resize if necessary:

update.Items = ip;
if (i < nvPairs.Length)
{
    Array.Resize(update.Items, i);
}

It's less code, but will likely end up doing the same amount of work (i.e. creating a new array and copying the old items).

What is the simplest C# function to parse a JSON string into an object?

DataContractJsonSerializer serializer = 
    new DataContractJsonSerializer(typeof(YourObjectType));

YourObjectType yourObject = (YourObjectType)serializer.ReadObject(jsonStream);

You could also use the JavaScriptSerializer, but DataContractJsonSerializer is supposedly better able to handle complex types.

Oddly enough JavaScriptSerializer was once deprecated (in 3.5) and then resurrected because of ASP.NET MVC (in 3.5 SP1). That would definitely be enough to shake my confidence and lead me to use DataContractJsonSerializer since it is hard baked for WCF.

Android: Rotate image in imageview by an angle

You can simply use rotation atribute of ImageView

Below is the attribute from ImageView with details from Android source

<!-- rotation of the view, in degrees. -->
<attr name="rotation" format="float" />

Check if any ancestor has a class using jQuery

if ($elem.parents('.left').length) {

}

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

Python 2.6 and 3 specifically say to avoid using PIPE for stdout and stderr.

The correct way is

import subprocess

# must create a file object to store the output. Here we are getting
# the ssid we are connected to
outfile = open('/tmp/ssid', 'w');
status = subprocess.Popen(["iwgetid"], bufsize=0, stdout=outfile)
outfile.close()

# now operate on the file

What is the point of the diamond operator (<>) in Java 7?

All said in the other responses are valid but the use cases are not completely valid IMHO. If one checks out Guava and especially the collections related stuff, the same has been done with static methods. E.g. Lists.newArrayList() which allows you to write

List<String> names = Lists.newArrayList();

or with static import

import static com.google.common.collect.Lists.*;
...
List<String> names = newArrayList();
List<String> names = newArrayList("one", "two", "three");

Guava has other very powerful features like this and I actually can't think of much uses for the <>.

It would have been more useful if they went for making the diamond operator behavior the default, that is, the type is inferenced from the left side of the expression or if the type of the left side was inferenced from the right side. The latter is what happens in Scala.

Are PostgreSQL column names case-sensitive?

To quote the documentation:

Key words and unquoted identifiers are case insensitive. Therefore:

UPDATE MY_TABLE SET A = 5;

can equivalently be written as:

uPDaTE my_TabLE SeT a = 5;

You could also write it using quoted identifiers:

UPDATE "my_table" SET "a" = 5;

Quoting an identifier makes it case-sensitive, whereas unquoted names are always folded to lower case (unlike the SQL standard where unquoted names are folded to upper case). For example, the identifiers FOO, foo, and "foo" are considered the same by PostgreSQL, but "Foo" and "FOO" are different from these three and each other.

If you want to write portable applications you are advised to always quote a particular name or never quote it.

How to split the screen with two equal LinearLayouts?

Just putting it out there:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FF0000"
    android:weightSum="4"
    android:padding="5dp"> <!-- to show what the parent is -->
    <LinearLayout
        android:background="#0000FF"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="2" />
    <LinearLayout
        android:background="#00FF00"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1" />
</LinearLayout>

Drawing an image from a data URL to a canvas

in javascript , using jquery for canvas id selection :

 var Canvas2 = $("#canvas2")[0];
        var Context2 = Canvas2.getContext("2d");
        var image = new Image();
        image.src = "images/eye.jpg";
        Context2.drawImage(image, 0, 0);

html5:

<canvas id="canvas2"></canvas>

iPhone: Setting Navigation Bar Title

By default the navigation controller displays the title of the 'topitem'

so in your viewdidload method of your appdelegate you can. I tested it and it works

navController.navigationBar.topItem.title = @"Test";

How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac

As previously answered (and retracted). To get the base directory, as in the location of the running assembly, don't use Directory.GetCurrentDirectory(), rather get it from IHostingEnvironment.ContentRootPath.

private IHostingEnvironment _hostingEnvironment;
    private string projectRootFolder;
    public Program(IHostingEnvironment env)
    {
        _hostingEnvironment = env;
        projectRootFolder = env.ContentRootPath.Substring(0,
            env.ContentRootPath.LastIndexOf(@"\ProjectRoot\", StringComparison.Ordinal) + @"\ProjectRoot\".Length);
    }

However I made an additional error: I had set the ContentRoot Directory to Directory.GetCurrentDirectory() at startup undermining the default value which I had so desired! Here I commented out the offending line:

 public static void Main(string[] args)
    {
        var host = new WebHostBuilder().UseKestrel()
           // .UseContentRoot(Directory.GetCurrentDirectory()) //<== The mistake
            .UseIISIntegration()
            .UseStartup<Program>()
            .Build();
        host.Run();
    }

Now it runs correctly - I can now navigate to sub folders of my projects root with:

var pathToData = Path.GetFullPath(Path.Combine(projectRootFolder, "data"));

I realised my mistake by reading BaseDirectory vs. Current Directory and @CodeNotFound founds answer (which was retracted because it didn't work because of the above mistake) which basically can be found here: Getting WebRoot Path and Content Root Path in Asp.net Core

jQuery UI Accordion Expand/Collapse All

A lot of these seem to be overcomplicated. I achieved what I wanted with just the following:

$(".ui-accordion-content").show();

JSFiddle

Setting max-height for table cell contents

What I found !!!, In tables CSS td{height:60px;} works same as CSS td{min-height:60px;}

I know that situation when cells height looks bad . This javascript solution don't need overflow hidden.

For Limiting max-height of all cells or rows in table with Javascript:

This script is good for horizontal overflow tables.

This script increase the table width 300px each time (maximum 4000px) until rows shrinks to max-height(160px) , and you can also edit numbers as your need.

var i = 0, row, table = document.getElementsByTagName('table')[0], j = table.offsetWidth;
while (row = table.rows[i++]) {
    while (row.offsetHeight > 160 && j < 4000) {
        j += 300;
        table.style.width = j + 'px';
    }
}

Source: HTML Table Solution Max Height Limit For Rows Or Cells By Increasing Table Width, Javascript

Index Error: list index out of range (Python)

Generally it means that you are providing an index for which a list element does not exist.

E.g, if your list was [1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.

How to submit an HTML form on loading the page?

Do this :

$(document).ready(function(){
     $("#frm1").submit();
});

What is useState() in React?

useState is a hook that lets you add state to a functional component. It accepts an argument which is the initial value of the state property and returns the current value of state property and a method which is capable of updating that state property.
Following is a simple example:

import React, {useState} from react    

function HookCounter {    
  const [count, stateCount]= useState(0)    
    return(    
      <div>     
        <button onClick{( ) => setCount(count+1)}> count{count}</button>    
      </div>    
    )   
 }

useState accepts the initial value of the state variable which is zero in this case and returns a pair of values. The current value of the state has been called count and a method that can update the state variable has been called as setCount.

How can I upgrade NumPy?

I tried doing sudo pip uninstall numpy instead, because the rm didn't work at first.

Hopefully that helps.

Uninstalling then to install it again.

If you can decode JWT, how are they secure?

JWTs can be either signed, encrypted or both. If a token is signed, but not encrypted, everyone can read its contents, but when you don't know the private key, you can't change it. Otherwise, the receiver will notice that the signature won't match anymore.

Answer to your comment: I'm not sure if I understand your comment the right way. Just to be sure: do you know and understand digital signatures? I'll just briefly explain one variant (HMAC, which is symmetrical, but there are many others).

Let's assume Alice wants to send a JWT to Bob. They both know some shared secret. Mallory doesn't know that secret, but wants to interfere and change the JWT. To prevent that, Alice calculates Hash(payload + secret) and appends this as signature.

When receiving the message, Bob can also calculate Hash(payload + secret) to check whether the signature matches. If however, Mallory changes something in the content, she isn't able to calculate the matching signature (which would be Hash(newContent + secret)). She doesn't know the secret and has no way of finding it out. This means if she changes something, the signature won't match anymore, and Bob will simply not accept the JWT anymore.

Let's suppose, I send another person the message {"id":1} and sign it with Hash(content + secret). (+ is just concatenation here). I use the SHA256 Hash function, and the signature I get is: 330e7b0775561c6e95797d4dd306a150046e239986f0a1373230fda0235bda8c. Now it's your turn: play the role of Mallory and try to sign the message {"id":2}. You can't because you don't know which secret I used. If I suppose that the recipient knows the secret, he CAN calculate the signature of any message and check if it's correct.

Pass user defined environment variable to tomcat

Environment variables can be set, by creating a setenv.bat (windows) or setenv.sh (unix) file in the bin folder of your tomcat installation directory. However, environment variables will not be accessabile from within your code.

System properties are set by -D arguments of the java process. You can define java starting arguments in the environment variable JAVA_OPTS.

My suggestions is the combination of these two mechanisms. In your apache-tomcat-0.0.0\bin\setenv.bat write:

set JAVA_OPTS=-DAPP_MASTER_PASSWORD=password1

and in your Java code write:

System.getProperty("APP_MASTER_PASSWORD")

Where is the visual studio HTML Designer?

Another way of setting the default to the HTML web forms editor is:

  1. At the top menu in Visual Studio go to File > New > File
  2. Select HTML Page
  3. In the lower right corner of the New File dialog on the Open button there is a down arrow
  4. Click it and you should see an option Open With
  5. Select HTML (Web Forms) Editor
  6. Click Set as Default
  7. Press OK

Screenshot showing how to get to the "Open With" dialog box when creating a new file.

How to add a ListView to a Column in Flutter?

You can check console output. It prints error:

The following assertion was thrown during performResize(): Horizontal viewport was given unbounded height. Viewports expand in the cross axis to fill their container and constrain their children to match their extent in the cross axis. In this case, a horizontal viewport was given an unlimited amount of vertical space in which to expand.

You need to add height constraint to your horizontal list. E.g. wrap in Container with height:

Container(
  height: 44.0,
  child: ListView(
    scrollDirection: Axis.horizontal,
    children: <Widget>[
      RaisedButton(
        onPressed: null,
        child: Text("Facebook"),
      ),
      Padding(padding: EdgeInsets.all(5.00)),
      RaisedButton(
        onPressed: null,
        child: Text("Google"),
      )
    ],
  ),
)

"And" and "Or" troubles within an IF statement

I like assylias' answer, however I would refactor it as follows:

Sub test()

Dim origNum As String
Dim creditOrDebit As String

origNum = "30062600006"
creditOrDebit = "D"

If creditOrDebit = "D" Then
  If origNum = "006260006" Then
    MsgBox "OK"
  ElseIf origNum = "30062600006" Then
    MsgBox "OK"
  End If
End If

End Sub

This might save you some CPU cycles since if creditOrDebit is <> "D" there is no point in checking the value of origNum.

Update:

I used the following procedure to test my theory that my procedure is faster:

Public Declare Function timeGetTime Lib "winmm.dll" () As Long

Sub DoTests2()

  Dim startTime1 As Long
  Dim endTime1 As Long
  Dim startTime2 As Long
  Dim endTime2 As Long
  Dim i As Long
  Dim msg As String

  Const numberOfLoops As Long = 10000
  Const origNum As String = "006260006"
  Const creditOrDebit As String = "D"

  startTime1 = timeGetTime
  For i = 1 To numberOfLoops
    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        ' do something here
        Debug.Print "OK"
      ElseIf origNum = "30062600006" Then
        ' do something here
        Debug.Print "OK"
      End If
    End If
  Next i
  endTime1 = timeGetTime

  startTime2 = timeGetTime
  For i = 1 To numberOfLoops
    If (origNum = "006260006" Or origNum = "30062600006") And _
      creditOrDebit = "D" Then
      ' do something here
      Debug.Print "OK"
    End If
  Next i
  endTime2 = timeGetTime

  msg = "number of iterations: " & numberOfLoops & vbNewLine
  msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
       " ms" & vbNewLine
  msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
       " ms"

  MsgBox msg

End Sub

I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)

After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit is <>"D", my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.

And that is why I refactored it - to short-circuit the logic so that origNum doesn't need to be evaluated when creditOrDebit <> "D".

At this point, the rest depends on the OP's spreadsheet. If creditOrDebit is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit has a wide range of possible values, and D is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.

How to pass parameter to function using in addEventListener?

In the first line of your JS code:

select.addEventListener('change', getSelection(this), false);

you're invoking getSelection by placing (this) behind the function reference. That is most likely not what you want, because you're now passing the return value of that call to addEventListener, instead of a reference to the actual function itself.


In a function invoked by addEventListener the value for this will automatically be set to the object the listener is attached to, productLineSelect in this case.

If that is what you want, you can just pass the function reference and this will in this example be select in invocations from addEventListener:

select.addEventListener('change', getSelection, false);

If that is not what you want, you'd best bind your value for this to the function you're passing to addEventListener:

var thisArg = { custom: 'object' };
select.addEventListener('change', getSelection.bind(thisArg), false);

The .bind part is also a call, but this call just returns the same function we're calling bind on, with the value for this inside that function scope fixed to thisArg, effectively overriding the dynamic nature of this-binding.


To get to your actual question: "How to pass parameters to function in addEventListener?"

You would have to use an additional function definition:

var globalVar = 'global';

productLineSelect.addEventListener('change', function(event) {
    var localVar = 'local';
    getSelection(event, this, globalVar, localVar);
}, false);

Now we pass the event object, a reference to the value of this inside the callback of addEventListener, a variable defined and initialised inside that callback, and a variable from outside the entire addEventListener call to your own getSelection function.


We also might again have an object of our choice to be this inside the outer callback:

var thisArg = { custom: 'object' };
var globalVar = 'global';

productLineSelect.addEventListener('change', function(event) {
    var localVar = 'local';
    getSelection(event, this, globalVar, localVar);
}.bind(thisArg), false);

Programmatically Check an Item in Checkboxlist where text is equal to what I want

All Credit to @Jim Scott -- just added one touch. (ASP.NET 4.5 & C#)

Refractoring this a little more... if you pass the CheckBoxList as an object to the method, you can reuse it for any CheckBoxList. Also you can use either the Text or the Value.

private void SelectCheckBoxList(string valueToSelect, CheckBoxList lst)
{
    ListItem listItem = lst.Items.FindByValue(valueToSelect);
    //ListItem listItem = lst.Items.FindByText(valueToSelect);
    if (listItem != null) listItem.Selected = true;
}

//How to call it -- in this case from a SQLDataReader and "chkRP" is my CheckBoxList`

SelectCheckBoxList(dr["kRPId"].ToString(), chkRP);`

How to add "active" class to wp_nav_menu() current menu item (simple way)

In header.php insert this code to show menu:

<?php
    wp_nav_menu(
        array(
            'theme_location' => 'menu-one',
            'walker' => new Custom_Walker_Nav_Menu_Top
        )
    );
?>

In functions.php use this:

class Custom_Walker_Nav_Menu_top extends Walker_Nav_Menu
{
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        $is_current_item = '';
        if(array_search('current-menu-item', $item->classes) != 0)
        {
            $is_current_item = ' class="active"';
        }
        echo '<li'.$is_current_item.'><a href="'.$item->url.'">'.$item->title;
    }

    function end_el( &$output, $item, $depth = 0, $args = array() ) {
        echo '</a></li>';
    }
}

Why am I getting a FileNotFoundError?

If the user does not pass the full path to the file (on Unix type systems this means a path that starts with a slash), the path is interpreted relatively to the current working directory. The current working directory usually is the directory in which you started the program. In your case, the file test.rtf must be in the same directory in which you execute the program.

You are obviously performing programming tasks in Python under Mac OS. There, I recommend to work in the terminal (on the command line), i.e. start the terminal, cd to the directory where your input file is located and start the Python script there using the command

$ python script.py

In order to make this work, the directory containing the python executable must be in the PATH, a so-called environment variable that contains directories that are automatically used for searching executables when you enter a command. You should make use of this, because it simplifies daily work greatly. That way, you can simply cd to the directory containing your Python script file and run it.

In any case, if your Python script file and your data input file are not in the same directory, you always have to specify either a relative path between them or you have to use an absolute path for one of them.

Strip HTML from Text JavaScript

It is also possible to use the fantastic htmlparser2 pure JS HTML parser. Here is a working demo:

var htmlparser = require('htmlparser2');

var body = '<p><div>This is </div>a <span>simple </span> <img src="test"></img>example.</p>';

var result = [];

var parser = new htmlparser.Parser({
    ontext: function(text){
        result.push(text);
    }
}, {decodeEntities: true});

parser.write(body);
parser.end();

result.join('');

The output will be This is a simple example.

See it in action here: https://tonicdev.com/jfahrenkrug/extract-text-from-html

This works in both node and the browser if you pack you web application using a tool like webpack.

Set field value with reflection

It's worth reading Oracle Java Tutorial - Getting and Setting Field Values

Field#set(Object object, Object value) sets the field represented by this Field object on the specified object argument to the specified new value.

It should be like this

f.set(objectOfTheClass, new ConcurrentHashMap<>());

You can't set any value in null Object If tried then it will result in NullPointerException


Note: Setting a field's value via reflection has a certain amount of performance overhead because various operations must occur such as validating access permissions. From the runtime's point of view, the effects are the same, and the operation is as atomic as if the value was changed in the class code directly.

How to properly stop the Thread in Java?

In the IndexProcessor class you need a way of setting a flag which informs the thread that it will need to terminate, similar to the variable run that you have used just in the class scope.

When you wish to stop the thread, you set this flag and call join() on the thread and wait for it to finish.

Make sure that the flag is thread safe by using a volatile variable or by using getter and setter methods which are synchronised with the variable being used as the flag.

public class IndexProcessor implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
    private volatile boolean running = true;

    public void terminate() {
        running = false;
    }

    @Override
    public void run() {
        while (running) {
            try {
                LOGGER.debug("Sleeping...");
                Thread.sleep((long) 15000);

                LOGGER.debug("Processing");
            } catch (InterruptedException e) {
                LOGGER.error("Exception", e);
                running = false;
            }
        }

    }
}

Then in SearchEngineContextListener:

public class SearchEngineContextListener implements ServletContextListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);

    private Thread thread = null;
    private IndexProcessor runnable = null;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        runnable = new IndexProcessor();
        thread = new Thread(runnable);
        LOGGER.debug("Starting thread: " + thread);
        thread.start();
        LOGGER.debug("Background process successfully started.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        LOGGER.debug("Stopping thread: " + thread);
        if (thread != null) {
            runnable.terminate();
            thread.join();
            LOGGER.debug("Thread successfully stopped.");
        }
    }
}

Console.WriteLine and generic List

List<int> list = new List<int> { 1, 3, 5 };
list.ForEach(x => Console.WriteLine(x));

Edit: Dammit! took too long to open visual studio to test it.

How do I do pagination in ASP.NET MVC?

I wanted to cover a simple way of doing this with the front end too:

Controller:

public ActionResult Index(int page = 0)
{
    const int PageSize = 3; // you can always do something more elegant to set this

    var count = this.dataSource.Count();

    var data = this.dataSource.Skip(page * PageSize).Take(PageSize).ToList();

    this.ViewBag.MaxPage = (count / PageSize) - (count % PageSize == 0 ? 1 : 0);

    this.ViewBag.Page = page;

    return this.View(data);
}

View:

@* rest of file with view *@

@if (ViewBag.Page > 0)
{
    <a href="@Url.Action("Index", new { page = ViewBag.Page - 1 })" 
       class="btn btn-default">
        &laquo; Prev
    </a>
}
@if (ViewBag.Page < ViewBag.MaxPage)
{
    <a href="@Url.Action("Index", new { page = ViewBag.Page + 1 })" 
       class="btn btn-default">
        Next &raquo;
    </a>
}

What is the difference between encode/decode?

The decode method of unicode strings really doesn't have any applications at all (unless you have some non-text data in a unicode string for some reason -- see below). It is mainly there for historical reasons, i think. In Python 3 it is completely gone.

unicode().decode() will perform an implicit encoding of s using the default (ascii) codec. Verify this like so:

>>> s = u'ö'
>>> s.decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

>>> s.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)

The error messages are exactly the same.

For str().encode() it's the other way around -- it attempts an implicit decoding of s with the default encoding:

>>> s = 'ö'
>>> s.decode('utf-8')
u'\xf6'
>>> s.encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)

Used like this, str().encode() is also superfluous.

But there is another application of the latter method that is useful: there are encodings that have nothing to do with character sets, and thus can be applied to 8-bit strings in a meaningful way:

>>> s.encode('zip')
'x\x9c;\xbc\r\x00\x02>\x01z'

You are right, though: the ambiguous usage of "encoding" for both these applications is... awkard. Again, with separate byte and string types in Python 3, this is no longer an issue.

Searching a string in eclipse workspace

Press Ctrl+shift+L and type your string

[] and {} vs list() and dict(), which is better?

In my opinion [] and {} are the most pythonic and readable ways to create empty lists/dicts.

Be wary of set()'s though, for example:

this_set = {5}
some_other_set = {}

Can be confusing. The first creates a set with one element, the second creates an empty dict and not a set.

When does socket.recv(recv_size) return?

Yes, your conclusion is correct. socket.recv is a blocking call.

socket.recv(1024) will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv won't block.

socket.recv will also end with an empty string if the connection is closed or there is an error.

If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking.

I had issues with socket.setblocking in the past, but feel free to try it if you want.

How to list the files inside a JAR file?

Just a different way of listing/reading files from a jar URL and it does it recursively for nested jars

https://gist.github.com/trung/2cd90faab7f75b3bcbaa

URL urlResource = Thead.currentThread().getContextClassLoader().getResource("foo");
JarReader.read(urlResource, new InputStreamCallback() {
    @Override
    public void onFile(String name, InputStream is) throws IOException {
        // got file name and content stream 
    }
});

Dump all tables in CSV format using 'mysqldump'

You also can do it using Data Export tool in dbForge Studio for MySQL.

It will allow you to select some or all tables and export them into CSV format.

Storing a Key Value Array into a compact JSON string

If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"} is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.

For example:

var data = ["slide0001.html", "Looking Ahead"];

var C_KEY = 0;
var C_VALUE = 1;

var value = data[C_VALUE];

So, now, your data can be:

[
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
]

If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:

{ meta: { keys: [ "key", "value" ] },
  data: [
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
  ]
}

... which would then be handled by the parser.

Laravel Eloquent LEFT JOIN WHERE NULL

This can be resolved by specifying the specific column names desired from the specific table like so:

$c = Customer::leftJoin('orders', function($join) {
      $join->on('customers.id', '=', 'orders.customer_id');
    })
    ->whereNull('orders.customer_id')
    ->first([
        'customers.id',
        'customers.first_name',
        'customers.last_name',
        'customers.email',
        'customers.phone',
        'customers.address1',
        'customers.address2',
        'customers.city',
        'customers.state',
        'customers.county',
        'customers.district',
        'customers.postal_code',
        'customers.country'
    ]);

How to center a button within a div?

You could just make:

_x000D_
_x000D_
<div style="text-align: center; border: 1px solid">_x000D_
  <input type="button" value="button">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or you could do it like this instead:

_x000D_
_x000D_
<div style="border: 1px solid">_x000D_
  <input type="button" value="button" style="display: block; margin: 0 auto;">_x000D_
</div>
_x000D_
_x000D_
_x000D_

The first one will center align everything inside the div. The other one will center align just the button.

Can I use a min-height for table, tr or td?

It's not a nice solution but try it like this:

<table>
    <tr>
        <td>
            <div>Lorem</div>
        </td>
    </tr>
    <tr>
        <td>
            <div>Ipsum</div>
        </td>
    </tr>
</table>

and set the divs to the min-height:

div {
    min-height: 300px;
}

Hope this is what you want ...

Using success/error/finally/catch with Promises in AngularJS

I do it like Bradley Braithwaite suggests in his blog:

app
    .factory('searchService', ['$q', '$http', function($q, $http) {
        var service = {};

        service.search = function search(query) {
            // We make use of Angular's $q library to create the deferred instance
            var deferred = $q.defer();

            $http
                .get('http://localhost/v1?=q' + query)
                .success(function(data) {
                    // The promise is resolved once the HTTP call is successful.
                    deferred.resolve(data);
                })
                .error(function(reason) {
                    // The promise is rejected if there is an error with the HTTP call.
                    deferred.reject(reason);
                });

            // The promise is returned to the caller
            return deferred.promise;
        };

        return service;
    }])
    .controller('SearchController', ['$scope', 'searchService', function($scope, searchService) {
        // The search service returns a promise API
        searchService
            .search($scope.query)
            .then(function(data) {
                // This is set when the promise is resolved.
                $scope.results = data;
            })
            .catch(function(reason) {
                // This is set in the event of an error.
                $scope.error = 'There has been an error: ' + reason;
            });
    }])

Key Points:

  • The resolve function links to the .then function in our controller i.e. all is well, so we can keep our promise and resolve it.

  • The reject function links to the .catch function in our controller i.e. something went wrong, so we can’t keep our promise and need to reject it.

It is quite stable and safe and if you have other conditions to reject the promise you can always filter your data in the success function and call deferred.reject(anotherReason) with the reason of the rejection.

As Ryan Vice suggested in the comments, this may not be seen as useful unless you fiddle a bit with the response, so to speak.

Because success and error are deprecated since 1.4 maybe it is better to use the regular promise methods then and catch and transform the response within those methods and return the promise of that transformed response.

I am showing the same example with both approaches and a third in-between approach:

success and error approach (success and error return a promise of an HTTP response, so we need the help of $q to return a promise of data):

function search(query) {
  // We make use of Angular's $q library to create the deferred instance
  var deferred = $q.defer();

  $http.get('http://localhost/v1?=q' + query)
  .success(function(data,status) {
    // The promise is resolved once the HTTP call is successful.
    deferred.resolve(data);              
  })

  .error(function(reason,status) {
    // The promise is rejected if there is an error with the HTTP call.
    if(reason.error){
      deferred.reject({text:reason.error, status:status});
    }else{
      //if we don't get any answers the proxy/api will probably be down
      deferred.reject({text:'whatever', status:500});
    }
  });

  // The promise is returned to the caller
  return deferred.promise;
};

then and catch approach (this is a bit more difficult to test, because of the throw):

function search(query) {

  var promise=$http.get('http://localhost/v1?=q' + query)

  .then(function (response) {
    // The promise is resolved once the HTTP call is successful.
    return response.data;
  },function(reason) {
    // The promise is rejected if there is an error with the HTTP call.
    if(reason.statusText){
      throw reason;
    }else{
      //if we don't get any answers the proxy/api will probably be down
      throw {statusText:'Call error', status:500};
    }

  });

  return promise;
}

There is a halfway solution though (this way you can avoid the throw and anyway you'll probably need to use $q to mock the promise behavior in your tests):

function search(query) {
  // We make use of Angular's $q library to create the deferred instance
  var deferred = $q.defer();

  $http.get('http://localhost/v1?=q' + query)

  .then(function (response) {
    // The promise is resolved once the HTTP call is successful.
    deferred.resolve(response.data);
  },function(reason) {
    // The promise is rejected if there is an error with the HTTP call.
    if(reason.statusText){
      deferred.reject(reason);
    }else{
      //if we don't get any answers the proxy/api will probably be down
      deferred.reject({statusText:'Call error', status:500});
    }

  });

  // The promise is returned to the caller
  return deferred.promise;
}

Any kind of comments or corrections are welcome.

Remove all special characters from a string

Update

The solution below has a "SEO friendlier" version:

function hyphenize($string) {
    $dict = array(
        "I'm"      => "I am",
        "thier"    => "their",
        // Add your own replacements here
    );
    return strtolower(
        preg_replace(
          array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
          array( '-', '' ),
          // the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
          cleanString(
              str_replace( // preg_replace can be used to support more complicated replacements
                  array_keys($dict),
                  array_values($dict),
                  urldecode($string)
              )
          )
        )
    );
}

function cleanString($text) {
    $utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
        '/[“”«»„]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );
    return preg_replace(array_keys($utf8), array_values($utf8), $text);
}

The rationale for the above functions (which I find way inefficient - the one below is better) is that a service that shall not be named apparently ran spelling checks and keyword recognition on the URLs.

After losing a long time on a customer's paranoias, I found out they were not imagining things after all -- their SEO experts [I am definitely not one] reported that, say, converting "Viaggi Economy Perù" to viaggi-economy-peru "behaved better" than viaggi-economy-per (the previous "cleaning" removed UTF8 characters; Bogotà became bogot, Medellìn became medelln and so on).

There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that "Perù" became "Peru" instead of "Per". "Per" did not match and sort of took it in the neck.

In order to both keep UTF8 characters and replace some misspellings, the faster function below became the more accurate (?) function above. $dict needs to be hand tailored, of course.

Previous answer

A simple approach:

// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped

$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);

// Replace sequences of spaces with hyphen
$str = preg_replace('/  */', '-', $str);

// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)

// You may also want to try this alternative:
$str = preg_replace('/\\s+/', '-', $str);

// where \s+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything

Note that you might have to first urldecode() the URL, since %20 and + both are actually spaces - I mean, if you have "Never%20gonna%20give%20you%20up" you want it to become Never-gonna-give-you-up, not Never20gonna20give20you20up . You might not need it, but I thought I'd mention the possibility.

So the finished function along with test cases:

function hyphenize($string) {
    return 
    ## strtolower(
          preg_replace(
            array('#[\\s-]+#', '#[^A-Za-z0-9. -]+#'),
            array('-', ''),
        ##     cleanString(
              urldecode($string)
        ##     )
        )
    ## )
    ;
}

print implode("\n", array_map(
    function($s) {
            return $s . ' becomes ' . hyphenize($s);
    },
    array(
    'Never%20gonna%20give%20you%20up',
    "I'm not the man I was",
    "'Légeresse', dit sa majesté",
    )));


Never%20gonna%20give%20you%20up    becomes  never-gonna-give-you-up
I'm not the man I was              becomes  im-not-the-man-I-was
'Légeresse', dit sa majesté        becomes  legeresse-dit-sa-majeste

To handle UTF-8 I used a cleanString implementation found online (link broken since, but a stripped down copy with all the not-too-esoteric UTF8 characters is at the beginning of the answer; it's also easy to add more characters to it if you need) that converts UTF8 characters to normal characters, thus preserving the word "look" as much as possible. It could be simplified and wrapped inside the function here for performance.

The function above also implements converting to lowercase - but that's a taste. The code to do so has been commented out.

Git fetch remote branch

You use 'git pull' to keep your branches separate. I will use the actual repository and branch names to help since 'lbranch' and 'rbranch' are tough to decipher.

Let's use:

  • myteam.unfuddle.com = the remote Git server
  • tlc = Unfuddle project account where the repository exists
  • daves_branch = remote branch name

    You, or any colleague, can run this to pull only your branch, no matter how many branches there are:

    git init
    git pull [email protected]:myteam/tlc daves_branch:refs/remotes/origin/daves_branch
    
  • Bulk Insert into Oracle database: Which is better: FOR Cursor loop or a simple Select?

    You can use:

    Bulk collect along with FOR ALL that is called Bulk binding.

    Because PL/SQL forall operator speeds 30x faster for simple table inserts.

    BULK_COLLECT and Oracle FORALL together these two features are known as Bulk Binding. Bulk Binds are a PL/SQL technique where, instead of multiple individual SELECT, INSERT, UPDATE or DELETE statements are executed to retrieve from, or store data in, at table, all of the operations are carried out at once, in bulk. This avoids the context-switching you get when the PL/SQL engine has to pass over to the SQL engine, then back to the PL/SQL engine, and so on, when you individually access rows one at a time. To do bulk binds with INSERT, UPDATE, and DELETE statements, you enclose the SQL statement within a PL/SQL FORALL statement. To do bulk binds with SELECT statements, you include the BULK COLLECT clause in the SELECT statement instead of using INTO.

    It improves performance.

    How to sum all values in a column in Jaspersoft iReport Designer?

    iReports Custom Fields for columns (sum, average, etc)

    1. Right-Click on Variables and click Create Variable

    2. Click on the new variable

      a. Notice the properties on the right

    3. Rename the variable accordingly

    4. Change the Value Class Name to the correct Data Type

      a. You can search by clicking the 3 dots

    5. Select the correct type of calculation

    6. Change the Expression

      a. Click the little icon

      b. Select the column you are looking to do the calculation for

      c. Click finish

    7. Set Initial Value Expression to 0

    8. Set the increment type to none

    9. Leave Incrementer Factory Class Name blank
    10. Set the Reset Type (usually report)

    11. Drag a new Text Field to stage (Usually in Last Page Footer, or Column Footer)

    12. Double Click the new Text Field
    13. Clear the expression “Text Field”
    14. Select the new variable

    15. Click finish

    16. Put the new text in a desirable position ?

    How best to read a File into List<string>

    string inLine = reader.ReadToEnd();
    myList = inLine.Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();
    

    I also use the Environment.NewLine.toCharArray as well, but found that didn't work on a couple files that did end in \r\n. Try either one and I hope it works well for you.

    Getting multiple values with scanf()

    Could do this, but then the user has to separate the numbers by a space:

    #include "stdio.h"
    
    int main()
    {
        int minx, x, y, z;
    
        printf("Enter four ints: ");
        scanf( "%i %i %i %i", &minx, &x, &y, &z);
    
        printf("You wrote: %i %i %i %i", minx, x, y, z);
    }
    

    How do I monitor the computer's CPU, memory, and disk usage in Java?

    A lot of this is already available via JMX. With Java 5, JMX is built-in and they include a JMX console viewer with the JDK.

    You can use JMX to monitor manually, or invoke JMX commands from Java if you need this information in your own run-time.

    How to load an external webpage into a div of a html page

    Using simple html,

     <div> 
        <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
        </object>
     </div>
    

    Or jquery,

    <script>
            $("#mydiv")
                .html('<object data="http://your-website-domain"/>');
    </script>
    

    JSFIDDLE DEMO

    How to pass variable number of arguments to a PHP function

    Since PHP 5.6, a variable argument list can be specified with the ... operator.

    function do_something($first, ...$all_the_others)
    {
        var_dump($first);
        var_dump($all_the_others);
    }
    
    do_something('this goes in first', 2, 3, 4, 5);
    
    #> string(18) "this goes in first"
    #>
    #> array(4) {
    #>   [0]=>
    #>   int(2)
    #>   [1]=>
    #>   int(3)
    #>   [2]=>
    #>   int(4)
    #>   [3]=>
    #>   int(5)
    #> }
    

    As you can see, the ... operator collects the variable list of arguments in an array.

    If you need to pass the variable arguments to another function, the ... can still help you.

    function do_something($first, ...$all_the_others)
    {
        do_something_else($first, ...$all_the_others);
        // Which is translated to:
        // do_something_else('this goes in first', 2, 3, 4, 5);
    }
    

    Since PHP 7, the variable list of arguments can be forced to be all of the same type too.

    function do_something($first, int ...$all_the_others) { /**/ }
    

    how to write value into cell with vba code without auto type conversion?

    Cells(1,1).Value2 = "'123,456"
    

    note the single apostrophe before the number - this will signal to excel that whatever follows has to be interpreted as text.

    S3 - Access-Control-Allow-Origin Header

    I was having similar problems loading 3D models from S3 into a javascript 3D viewer (3D HOP), but strangely enough only with certain file types (.nxs).

    What fixed it for me was changing AllowedHeader from the default Authorization to * in the CORS config:

    <?xml version="1.0" encoding="UTF-8"?>
    <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    </CORSConfiguration>
    

    Start thread with member function

    #include <thread>
    #include <iostream>
    
    class bar {
    public:
      void foo() {
        std::cout << "hello from member function" << std::endl;
      }
    };
    
    int main()
    {
      std::thread t(&bar::foo, bar());
      t.join();
    }
    

    EDIT: Accounting your edit, you have to do it like this:

      std::thread spawn() {
        return std::thread(&blub::test, this);
      }
    

    UPDATE: I want to explain some more points, some of them have also been discussed in the comments.

    The syntax described above is defined in terms of the INVOKE definition (§20.8.2.1):

    Define INVOKE (f, t1, t2, ..., tN) as follows:

    • (t1.*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is an object of type T or a reference to an object of type T or a reference to an object of a type derived from T;
    • ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a class T and t1 is not one of the types described in the previous item;
    • t1.*f when N == 1 and f is a pointer to member data of a class T and t 1 is an object of type T or a
      reference to an object of type T or a reference to an object of a
      type derived from T;
    • (*t1).*f when N == 1 and f is a pointer to member data of a class T and t 1 is not one of the types described in the previous item;
    • f(t1, t2, ..., tN) in all other cases.

    Another general fact which I want to point out is that by default the thread constructor will copy all arguments passed to it. The reason for this is that the arguments may need to outlive the calling thread, copying the arguments guarantees that. Instead, if you want to really pass a reference, you can use a std::reference_wrapper created by std::ref.

    std::thread (foo, std::ref(arg1));
    

    By doing this, you are promising that you will take care of guaranteeing that the arguments will still exist when the thread operates on them.


    Note that all the things mentioned above can also be applied to std::async and std::bind.

    Call two functions from same onclick

    Binding events from html is NOT recommended. This is recommended way:

    document.getElementById('btn').addEventListener('click', function(){
        pay();
        cls();
    });
    

    Custom Cell Row Height setting in storyboard is not responding

    One other thing you can do is to go to your Document Outline, select the table view that your prototype cell is nested. Then on the Size Inspector, change your table view Row Height to your desired value and uncheck the Automatic box.

    Example to use shared_ptr?

    I will add that one of the important things about shared_ptr's is to only ever construct them with the following syntax:

    shared_ptr<Type>(new Type(...));
    

    This way, the "real" pointer to Type is anonymous to your scope, and held only by the shared pointer. Thus it will be impossible for you to accidentally use this "real" pointer. In other words, never do this:

    Type* t_ptr = new Type(...);
    shared_ptr<Type> t_sptr ptrT(t_ptr);
    //t_ptr is still hanging around!  Don't use it!
    

    Although this will work, you now have a Type* pointer (t_ptr) in your function which lives outside the shared pointer. It's dangerous to use t_ptr anywhere, because you never know when the shared pointer which holds it may destruct it, and you'll segfault.

    Same goes for pointers returned to you by other classes. If a class you didn't write hands you a pointer, it's generally not safe to just put it in a shared_ptr. Not unless you're sure that the class is no longer using that object. Because if you do put it in a shared_ptr, and it falls out of scope, the object will get freed when the class may still need it.

    Copy a file list as text from Windows Explorer

    If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").

    It makes a nice clean list of file names.

    Reading Properties file in Java

    Your file should be available as com/example/foo/myProps.properties in classpath. Then load it as:

    props.load(this.getClass().getResourceAsStream("myProps.properties"));
    

    Combine Points with lines with ggplot2

    The following example using the iris dataset works fine:

    dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
          id.vars = "Species")
    ggplot(aes(x = 1:nrow(iris), y = value, color = variable), data = dat) +  
          geom_point() + geom_line()
    

    enter image description here

    Does Enter key trigger a click event?

    @Component({
      selector: 'key-up3',
      template: `
        <input #box (keyup.enter)="doSomething($event)">
        <p>{{values}}</p>
      `
    })
    export class KeyUpComponent_v3 {
      doSomething(e) {
        alert(e);
      }
    }
    

    This works for me!

    ALTER table - adding AUTOINCREMENT in MySQL

    ALTER TABLE tblcatalog
        CHANGE COLUMN id id INT(11) NOT NULL AUTO_INCREMENT FIRST;
    

    What are the differences between "git commit" and "git push"?

    commit: adding changes to the local repository

    push: to transfer the last commit(s) to a remote server

    How to list all properties of a PowerShell object

    The most succinct way to do this is:

    Get-WmiObject -Class win32_computersystem -Property *
    

    React-Redux: Actions must be plain objects. Use custom middleware for async actions

    You have to dispatch after the async request ends.

    This would work:

    export function bindComments(postId) {
        return function(dispatch) {
            return API.fetchComments(postId).then(comments => {
                // dispatch
                dispatch({
                    type: BIND_COMMENTS,
                    comments,
                    postId
                });
            });
        };
    }
    

    Android view pager with page indicator

    UPDATE: 22/03/2017

    main fragment layout:

           <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
    
                <android.support.v4.view.ViewPager
                    android:id="@+id/viewpager"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
    
                <RadioGroup
                    android:id="@+id/page_group"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal|bottom"
                    android:layout_marginBottom="@dimen/margin_help_container"
                    android:orientation="horizontal">
    
                    <RadioButton
                        android:id="@+id/page1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:checked="true" />
    
                    <RadioButton
                        android:id="@+id/page2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
    
                    <RadioButton
                        android:id="@+id/page3"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" />
                </RadioGroup>
            </FrameLayout>
    

    set up view and event on your fragment like this:

            mViewPaper = (ViewPager) view.findViewById(R.id.viewpager);
            mViewPaper.setAdapter(adapder);
    
            mPageGroup = (RadioGroup) view.findViewById(R.id.page_group);
            mPageGroup.setOnCheckedChangeListener(this);
    
            mViewPaper.addOnPageChangeListener(this);
    
           *************************************************
           *************************************************
    
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }
    
        @Override
        public void onPageSelected(int position) {
            // when current page change -> update radio button state
            int radioButtonId = mPageGroup.getChildAt(position).getId();
            mPageGroup.check(radioButtonId);
        }
    
        @Override
        public void onPageScrollStateChanged(int state) {
        }
    
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
            // when checked radio button -> update current page
            RadioButton checkedRadioButton = (RadioButton)radioGroup.findViewById(checkedId);
            // get index of checked radio button
            int index = radioGroup.indexOfChild(checkedRadioButton);
    
            // update current page
            mViewPaper.setCurrentItem(index), true);
        }
    

    custom checkbox state: Custom checkbox image android

    Viewpager tutorial: http://architects.dzone.com/articles/android-tutorial-using

    enter image description here

    Go to first line in a file in vim?

    Go to first line

    • :1

    • or Ctrl + Home

    Go to last line

    • :%

    • or Ctrl + End


    Go to another line (f.i. 27)

    • :27

    [Works On VIM 7.4 (2016) and 8.0 (2018)]

    Java - No enclosing instance of type Foo is accessible

    Declare the INNER class Thing as a static and it will work with no issues.

    I remember I have the same issue with the inner class Dog when I declared it as class Dog { only. I got the same issue as you did. There were two solutions:

    1- To declare the inner class Dog as static. Or

    2- To move the inner class Dog to a new class by itself.

    Here is the Example:

    public class ReturnDemo {

    public static void main(String[] args) {
        
        int z = ReturnDemo.calculate(10, 12);
        System.out.println("z = " + z);
        
        ReturnDemo.Dog dog = new Dog("Bosh", " Doggy");
        System.out.println( dog.getDog());
    }
    
    
    public static int calculate (int x, int y) {
        return x + y;
    }
    
    public void print( ) {
        System.out.println("void method");
        return;
    }
    
    public String getString() {
        return "Retrun String type value";
    }
    
    
    static class Dog {
        
    private String breed;
    private String name;
    
    public Dog(String breed, String name) {
        super();
        this.breed = breed;
        this.name = name;
    }
    
    public Dog getDog() {
        // return Dog type;
        return this;
        
    }
    
    public String toString() {
        return "breed" + breed.concat("name: " + name);
    }
    }
    

    }

    Start a fragment via Intent within a Fragment

    You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.

    So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filters.

    Count number of lines in a git repository

    I was playing around with cmder (http://gooseberrycreative.com/cmder/) and I wanted to count the lines of html,css,java and javascript. While some of the answers above worked, or pattern in grep didn't - I found here (https://unix.stackexchange.com/questions/37313/how-do-i-grep-for-multiple-patterns) that I had to escape it

    So this is what I use now:

    git ls-files | grep "\(.html\|.css\|.js\|.java\)$" | xargs wc -l

    How to plot a function curve in R

    You mean like this?

    > eq = function(x){x*x}
    > plot(eq(1:1000), type='l')
    

    Plot of eq over range 1:1000

    (Or whatever range of values is relevant to your function)

    IIS error, Unable to start debugging on the webserver

    I've seen alot of different solutions for this. iisreset did the trick for me.

    Just open an elevated command prompt and type:

    iisreset

    How to get the current location in Google Maps Android API v2?

    I just found this code snippet simple and functional, try :

    public class MainActivity extends ActionBarActivity implements
        ConnectionCallbacks, OnConnectionFailedListener {
    ...
    @Override
    public void onConnected(Bundle connectionHint) {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
            mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
        }
    }}
    

    here's the link of the tutorial : Getting the Last Known Location

    How do you read from stdin?

    Try this:

    import sys
    
    print sys.stdin.read().upper()
    

    and check it with:

    $ echo "Hello World" | python myFile.py
    

    Reading numbers from a text file into an array in C

    There are two problems in your code:

    • the return value of scanf must be checked
    • the %d conversion does not take overflows into account (blindly applying *10 + newdigit for each consecutive numeric character)

    The first value you got (-104204697) is equals to 5623125698541159 modulo 2^32; it is thus the result of an overflow (if int where 64 bits wide, no overflow would happen). The next values are uninitialized (garbage from the stack) and thus unpredictable.

    The code you need could be (similar to the answer of BLUEPIXY above, with the illustration how to check the return value of scanf, the number of items successfully matched):

    #include <stdio.h>
    
    int main(int argc, char *argv[]) {
        int i, j;
        short unsigned digitArray[16];
        i = 0;
        while (
            i != sizeof(digitArray) / sizeof(digitArray[0])
         && 1 == scanf("%1hu", digitArray + i)
        ) {
            i++;
        }
        for (j = 0; j != i; j++) {
            printf("%hu\n", digitArray[j]);
        }
        return 0;
    }
    

    Spark read file from S3 using sc.textFile ("s3n://...)

    Confirmed that this is related to the Spark build against Hadoop 2.60. Just installed Spark 1.4.0 "Pre built for Hadoop 2.4 and later" (instead of Hadoop 2.6). And the code now works OK.

    sc.textFile("s3n://bucketname/Filename") now raises another error:

    java.lang.IllegalArgumentException: AWS Access Key ID and Secret Access Key must be specified as the username or password (respectively) of a s3n URL, or by setting the fs.s3n.awsAccessKeyId or fs.s3n.awsSecretAccessKey properties (respectively).
    

    The code below uses the S3 URL format to show that Spark can read S3 file. Using dev machine (no Hadoop libs).

    scala> val lyrics = sc.textFile("s3n://MyAccessKeyID:MySecretKey@zpub01/SafeAndSound_Lyrics.txt")
    lyrics: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[3] at textFile at <console>:21
    
    scala> lyrics.count
    res1: Long = 9
    

    Even Better: the code above with AWS credentials inline in the S3N URI will break if the AWS Secret Key has a forward "/". Configuring AWS Credentials in SparkContext will fix it. Code works whether the S3 file is public or private.

    sc.hadoopConfiguration.set("fs.s3n.awsAccessKeyId", "BLABLA")
    sc.hadoopConfiguration.set("fs.s3n.awsSecretAccessKey", "....") // can contain "/"
    val myRDD = sc.textFile("s3n://myBucket/MyFilePattern")
    myRDD.count
    

    Bootstrap modal link

    Please remove . from your target it should be a id

    <a href="#bannerformmodal" data-toggle="modal" data-target="#bannerformmodal">Load me</a>
    

    Also you have to give your modal id like below

    <div class="modal fade bannerformmodal" tabindex="-1" role="dialog" aria-labelledby="bannerformmodal" aria-hidden="true" id="bannerformmodal">
    

    Here is the solution in a fiddle.

    In Python, how do I create a string of n characters in one line of code?

    If you can use repeated letters, you can use the * operator:

    >>> 'a'*5
    
    'aaaaa'
    

    How to select rows from a DataFrame based on column values

    Faster results can be achieved using numpy.where.

    For example, with unubtu's setup -

    In [76]: df.iloc[np.where(df.A.values=='foo')]
    Out[76]: 
         A      B  C   D
    0  foo    one  0   0
    2  foo    two  2   4
    4  foo    two  4   8
    6  foo    one  6  12
    7  foo  three  7  14
    

    Timing comparisons:

    In [68]: %timeit df.iloc[np.where(df.A.values=='foo')]  # fastest
    1000 loops, best of 3: 380 µs per loop
    
    In [69]: %timeit df.loc[df['A'] == 'foo']
    1000 loops, best of 3: 745 µs per loop
    
    In [71]: %timeit df.loc[df['A'].isin(['foo'])]
    1000 loops, best of 3: 562 µs per loop
    
    In [72]: %timeit df[df.A=='foo']
    1000 loops, best of 3: 796 µs per loop
    
    In [74]: %timeit df.query('(A=="foo")')  # slowest
    1000 loops, best of 3: 1.71 ms per loop
    

    c# - approach for saving user settings in a WPF application?

    You can store your settings info as Strings of XML in the Settings.Default. Create some classes to store your configuration data and make sure they are [Serializable]. Then, with the following helpers, you can serialize instances of these objects--or List<T> (or arrays T[], etc.) of them--to String. Store each of these various strings in its own respective Settings.Default slot in your WPF application's Settings.

    To recover the objects the next time the app starts, read the Settings string of interest and Deserialize to the expected type T (which this time must be explcitly specified as a type argument to Deserialize<T>).

    public static String Serialize<T>(T t)
    {
        using (StringWriter sw = new StringWriter())
        using (XmlWriter xw = XmlWriter.Create(sw))
        {
            new XmlSerializer(typeof(T)).Serialize(xw, t);
            return sw.GetStringBuilder().ToString();
        }
    }
    
    public static T Deserialize<T>(String s_xml)
    {
        using (XmlReader xw = XmlReader.Create(new StringReader(s_xml)))
            return (T)new XmlSerializer(typeof(T)).Deserialize(xw);
    }
    

    How to pass multiple parameters from ajax to mvc controller?

    Try this:

    var req={StrContactDetails:'data',IsPrimary:'True'}
    
    $.ajax({
                       type: 'POST',
                       data: req,
                       url: '@url.Action("SaveEmergencyContact","Dhp")',
                       contentType: "application/json; charset=utf-8",
                       dataType: "json",
                       data: JSON.stringify(req),
                       success: function (data) {
                           alert("Success");
                       },
                       error: function (ob, errStr) {
                           alert("An error occured.Please try after sometime.");
                       }
                   });
    

    http://api.jquery.com/jquery.ajax/

    Jquery/Ajax call with timer

    If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

    setTimeout ( expression, timeout );
    setInterval ( expression, interval );
    

    Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

    So in your case it would work something like this:

    setInterval(function() {
        //call $.ajax here
    }, 5000); //5 seconds
    

    As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


    If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

    setInterval() returns an integer which is the ID of the interval.

    var id = setInterval(function() {
        //call $.ajax here
    }, 30000); // 30 seconds
    

    If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

    Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

    Number of regex matches

    For those moments when you really want to avoid building lists:

    import re
    import operator
    from functools import reduce
    count = reduce(operator.add, (1 for _ in re.finditer(my_pattern, my_string))) 
    

    Sometimes you might need to operate on huge strings. This might help.

    Arrays.asList() of an array

    Use java.utils.Arrays:

    public int getTheNumber(int[] factors) {
        int[] f = (int[])factors.clone();
        Arrays.sort(f);
        return f[0]*f[(f.length-1];
    }
    

    Or if you want to be efficient avoid all the object allocation just actually do the work:

    public static int getTheNumber(int[] array) {
        if (array.length == 0)
            throw new IllegalArgumentException();
        int min = array[0];
        int max = array[0];
        for (int i = 1; i< array.length;++i) {
            int v = array[i];
            if (v < min) {
                min = v;
            } else if (v > max) {
                max = v;
            }
        }
        return min * max;
    }
    

    Javascript setInterval not working

    A lot of other answers are focusing on a pattern that does work, but their explanations aren't really very thorough as to why your current code doesn't work.

    Your code, for reference:

    function funcName() {
        alert("test");
    }
    
    var func = funcName();
    var run = setInterval("func",10000)
    

    Let's break this up into chunks. Your function funcName is fine. Note that when you call funcName (in other words, you run it) you will be alerting "test". But notice that funcName() -- the parentheses mean to "call" or "run" the function -- doesn't actually return a value. When a function doesn't have a return value, it defaults to a value known as undefined.

    When you call a function, you append its argument list to the end in parentheses. When you don't have any arguments to pass the function, you just add empty parentheses, like funcName(). But when you want to refer to the function itself, and not call it, you don't need the parentheses because the parentheses indicate to run it.

    So, when you say:

    var func = funcName();
    

    You are actually declaring a variable func that has a value of funcName(). But notice the parentheses. funcName() is actually the return value of funcName. As I said above, since funcName doesn't actually return any value, it defaults to undefined. So, in other words, your variable func actually will have the value undefined.

    Then you have this line:

    var run = setInterval("func",10000)
    

    The function setInterval takes two arguments. The first is the function to be ran every so often, and the second is the number of milliseconds between each time the function is ran.

    However, the first argument really should be a function, not a string. If it is a string, then the JavaScript engine will use eval on that string instead. So, in other words, your setInterval is running the following JavaScript code:

    func
    // 10 seconds later....
    func
    // and so on
    

    However, func is just a variable (with the value undefined, but that's sort of irrelevant). So every ten seconds, the JS engine evaluates the variable func and returns undefined. But this doesn't really do anything. I mean, it technically is being evaluated every 10 seconds, but you're not going to see any effects from that.

    The solution is to give setInterval a function to run instead of a string. So, in this case:

    var run = setInterval(funcName, 10000);
    

    Notice that I didn't give it func. This is because func is not a function in your code; it's the value undefined, because you assigned it funcName(). Like I said above, funcName() will call the function funcName and return the return value of the function. Since funcName doesn't return anything, this defaults to undefined. I know I've said that several times now, but it really is a very important concept: when you see funcName(), you should think "the return value of funcName". When you want to refer to a function itself, like a separate entity, you should leave off the parentheses so you don't call it: funcName.

    So, another solution for your code would be:

    var func = funcName;
    var run = setInterval(func, 10000);
    

    However, that's a bit redundant: why use func instead of funcName?

    Or you can stay as true as possible to the original code by modifying two bits:

    var func = funcName;
    var run = setInterval("func()", 10000);
    

    In this case, the JS engine will evaluate func() every ten seconds. In other words, it will alert "test" every ten seconds. However, as the famous phrase goes, eval is evil, so you should try to avoid it whenever possible.

    Another twist on this code is to use an anonymous function. In other words, a function that doesn't have a name -- you just drop it in the code because you don't care what it's called.

    setInterval(function () {
        alert("test");
    }, 10000);
    

    In this case, since I don't care what the function is called, I just leave a generic, unnamed (anonymous) function there.

    Get local IP address in Node.js

    An improvement on the top answer for the following reasons:

    • Code should be as self-explanatory as possible.

    • Enumerating over an array using for...in... should be avoided.

    • for...in... enumeration should be validated to ensure the object's being enumerated over contains the property you're looking for. As JavaScript is loosely typed and the for...in... can be handed any arbitrary object to handle; it's safer to validate the property we're looking for is available.

       var os = require('os'),
           interfaces = os.networkInterfaces(),
           address,
           addresses = [],
           i,
           l,
           interfaceId,
           interfaceArray;
      
       for (interfaceId in interfaces) {
           if (interfaces.hasOwnProperty(interfaceId)) {
               interfaceArray = interfaces[interfaceId];
               l = interfaceArray.length;
      
               for (i = 0; i < l; i += 1) {
      
                   address = interfaceArray[i];
      
                   if (address.family === 'IPv4' && !address.internal) {
                       addresses.push(address.address);
                   }
               }
           }
       }
      
       console.log(addresses);
      

    Configuring user and password with Git Bash

    I wrote the answer inside this link;

    Still, I am sharing it here as well.

    Change username and email global

    git config --global user.name "<username>"
    git config --global user.email "<email>"
    

    Change username and email for current repo

    git config  user.name "<username>" --replace-all
    git config  user.email "<email>" --replace-all
    

    Inserting Data into Hive Table

    There's no direct way to insert 1 record at a time from the terminal, however, here's an easy straight forward workaround which I usually use when I want to test something:

    Assuming that t is a table with at least 1 record. It doesn't matter what is the type or number of columns.

    INSERT INTO TABLE foo
    SELECT '12', 'xyz'
    FROM t
    LIMIT 1;
    

    What is the largest TCP/IP network port number allowable for IPv4?

    According to RFC 793, the port is a 16 bit unsigned int.

    This means the range is 0 - 65535.

    However, within that range, ports 0 - 1023 are generally reserved for specific purposes. I say generally because, apart from port 0, there is usually no enforcement of the 0-1023 reservation. TCP/UDP implementations usually don't enforce reservations apart from 0. You can, if you want to, run up a web server's TLS port on port 80, or 25, or 65535 instead of the standard 443. Likewise, even tho it is the standard that SMTP servers listen on port 25, you can run it on 80, 443, or others.

    Most implementations reserve 0 for a specific purpose - random port assignment. So in most implementations, saying "listen on port 0" actually means "I don't care what port I use, just give me some random unassigned port to listen on".

    So any limitation on using a port in the 0-65535 range, including 0, ephemeral reservation range etc, is implementation (i.e. OS/driver) specific, however all, including 0, are valid ports in the RFC 793.

    How to add images in select list?

    I got the same issue. My solution was a foreach of radio buttons, with the image at the right of it. Since you can only choose a single option at radio, it works (like) a select.

    Worket well for me. Hope it can help someone else.

    How to place a file on classpath in Eclipse?

    One option is to place your properties file in the src/ directory of your project. This will copy it to the "classes" (along with your .class files) at build time. I often do this for web projects.

    how to output every line in a file python

    Did you try

    for line in open("masters", "r").readlines(): print line
    

    ?

    readline() 
    

    only reads "a line", on the other hand

    readlines()
    

    reads whole lines and gives you a list of all lines.

    Optional Parameters in Go?

    You can pass arbitrary named parameters with a map. You will have to assert types with "aType = map[key].(*foo.type)" if the parameters have non-uniform types.

    type varArgs map[string]interface{}
    
    func myFunc(args varArgs) {
    
        arg1 := "default"
        if val, ok := args["arg1"]; ok {
            arg1 = val.(string)
        }
    
        arg2 := 123
        if val, ok := args["arg2"]; ok {
            arg2 = val.(int)
        }
    
        fmt.Println(arg1, arg2)
    }
    
    func Test_test() {
        myFunc(varArgs{"arg1": "value", "arg2": 1234})
    }
    

    Out-File -append in Powershell does not produce a new line and breaks string into characters

    Out-File defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii to change this behavior. In your case

    Out-File -Encoding Ascii -append textfile.txt. 
    

    Add-Content uses Ascii and also appends by default.

    "This is a test" | Add-Content textfile.txt.
    

    As for the lack of newline: You did not send a newline so it will not write one to file.

    How do I tokenize a string sentence in NLTK?

    As @PavelAnossov answered, the canonical answer, use the word_tokenize function in nltk:

    from nltk import word_tokenize
    sent = "This is my text, this is a nice way to input text."
    word_tokenize(sent)
    

    If your sentence is truly simple enough:

    Using the string.punctuation set, remove punctuation then split using the whitespace delimiter:

    import string
    x = "This is my text, this is a nice way to input text."
    y = "".join([i for i in x if not in string.punctuation]).split(" ")
    print y
    

    Updating a JSON object using Javascript

    JSON is the JavaScript Object Notation. There is no such thing as a JSON object. JSON is just a way of representing a JavaScript object in text.

    So what you're after is a way of updating a in in-memory JavaScript object. qiao's answer shows how to do that simply enough.

    Better way to convert file sizes in Python

    UNITS = {1000: ['KB', 'MB', 'GB'],
                1024: ['KiB', 'MiB', 'GiB']}
    
    def approximate_size(size, flag_1024_or_1000=True):
        mult = 1024 if flag_1024_or_1000 else 1000
        for unit in UNITS[mult]:
            size = size / mult
            if size < mult:
                return '{0:.3f} {1}'.format(size, unit)
    
    approximate_size(2123, False)
    

    Convert seconds value to hours minutes seconds?

    I use this:

     public String SEG2HOR( long lnValue) {     //OK
            String lcStr = "00:00:00";
            String lcSign = (lnValue>=0 ? " " : "-");
            lnValue = lnValue * (lnValue>=0 ? 1 : -1); 
    
            if (lnValue>0) {                
                long lnHor  = (lnValue/3600);
                long lnHor1 = (lnValue % 3600);
                long lnMin  = (lnHor1/60);
                long lnSec  = (lnHor1 % 60);            
    
                            lcStr = lcSign + ( lnHor < 10 ? "0": "") + String.valueOf(lnHor) +":"+
                                  ( lnMin < 10 ? "0": "") + String.valueOf(lnMin) +":"+
                                  ( lnSec < 10 ? "0": "") + String.valueOf(lnSec) ;
            }
    
            return lcStr;           
        }
    

    Homebrew refusing to link OpenSSL

    The solution might be updating some tools.

    Here's my scenario from 2020 with Ruby and Python:

    I needed to install Python 3 on Mac and things escalated. In the end, updating homebrew, node and python lead to the problem with openssl. I did not have openssl 1.0 anymore, so I couldn't "brew switch" to it.
    So what was still trying to use that old 1.0 version?

    It tuned out it was Ruby 2.5.5.
    So I just installed Ruby 2.5.8 and removed the old one.

    Other things you can try if this is not enough: Use rbenv and pyenv. Clean up gems and formulas. Update homebrew, node, yarn. Upgrade bundler. Make sure your .bash_profile (or equivalent) is set up according to each tool's instructions. Reopen the terminal.

    AngularJS $resource RESTful example

    $resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.

    It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.

    EDIT: I don't think I explained this well enough originally, but $resource does some funky stuff with returns. Todo.get() and Todo.query() both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save() before the get() callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then() or the callback method.

    Standard use

    var Todo = $resource('/api/1/todo/:id');
    
    //create a todo
    var todo1 = new Todo();
    todo1.foo = 'bar';
    todo1.something = 123;
    todo1.$save();
    
    //get and update a todo
    var todo2 = Todo.get({id: 123});
    todo2.foo += '!';
    todo2.$save();
    
    //which is basically the same as...
    Todo.get({id: 123}, function(todo) {
       todo.foo += '!';
       todo.$save();
    });
    
    //get a list of todos
    Todo.query(function(todos) {
      //do something with todos
      angular.forEach(todos, function(todo) {
         todo.foo += ' something';
         todo.$save();
      });
    });
    
    //delete a todo
    Todo.$delete({id: 123});
    

    Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):

    var something = src.GetTodo({id: 123});
    something.foo = 'hi there';
    something.UpdateTodo();
    

    I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource, you should probably just be using $http on it's own.

    Update: Angular 1.2 and Promises

    As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.

    To leverage promises with $resource, you need to use the $promise property on the returned value.

    Example using promises

    var Todo = $resource('/api/1/todo/:id');
    
    Todo.get({id: 123}).$promise.then(function(todo) {
       // success
       $scope.todos = todos;
    }, function(errResponse) {
       // fail
    });
    
    Todo.query().$promise.then(function(todos) {
       // success
       $scope.todos = todos;
    }, function(errResponse) {
       // fail
    });
    

    Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:

    These are equivalent

    var todo = Todo.get({id: 123}, function() {
       $scope.todo = todo;
    });
    
    Todo.get({id: 123}, function(todo) {
       $scope.todo = todo;
    });
    
    Todo.get({id: 123}).$promise.then(function(todo) {
       $scope.todo = todo;
    });
    
    var todo = Todo.get({id: 123});
    todo.$promise.then(function() {
       $scope.todo = todo;
    });
    

    How do I get Maven to use the correct repositories?

    By default, Maven will always look in the official Maven repository, which is http://repo1.maven.org.

    When Maven tries to build a project, it will look in your local repository (by default ~/.m2/repository but you can configure it by changing the <localRepository> value in your ~/.m2/settings.xml) to find any dependency, plugin or report defined in your pom.xml. If the adequate artifact is not found in your local repository, it will look in all external repositories configured, starting with the default one, http://repo1.maven.org.

    You can configure Maven to avoid this default repository by setting a mirror in your settings.xml file:

    <mirrors>
        <mirror>
            <id>repoMirror</id>
            <name>Our mirror for Maven repository</name>
            <url>http://the/server/</url>
            <mirrorOf>*</mirrorOf>
        </mirror>
    </mirrors>
    

    This way, instead of contacting http://repo1.maven.org, Maven will contact your entreprise repository (http://the/server in this example).

    If you want to add another repository, you can define a new one in your settings.xml file:

    <profiles>
        <profile>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <repositories>
                <repository>
                    <id>foo.bar</id>
                    <releases>
                        <enabled>true</enabled>
                    </releases>
                    <snapshots>
                        <enabled>true</enabled>
                    </snapshots>
                    <url>http://new/repository/server</url>
                </repository>
            </repositories>
    

    You can see the complete settings.xml model here.

    Concerning the clean process, you can ask Maven to run it offline. In this case, Maven will not try to reach any external repositories:

    mvn -o clean 
    

    byte array to pdf

    Usually this happens if something is wrong with the byte array.

    File.WriteAllBytes("filename.PDF", Byte[]);
    

    This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.

    Asynchronous implementation of this is also available.

    public static System.Threading.Tasks.Task WriteAllBytesAsync 
    (string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);
    

    react-router - pass props to handler component

    for the react-router 2.5.2,the solution is so easy:

        //someConponent
    ...
    render:function(){
      return (
        <h1>This is the parent component who pass the prop to this.props.children</h1>
        {this.props.children && React.cloneElement(this.props.children,{myProp:'value'})}
      )
    }
    ...
    

    Pygame Drawing a Rectangle

    Have you tried this:

    PyGame Drawing Basics

    Taken from the site:

    pygame.draw.rect(screen, color, (x,y,width,height), thickness) draws a rectangle (x,y,width,height) is a Python tuple x,y are the coordinates of the upper left hand corner width, height are the width and height of the rectangle thickness is the thickness of the line. If it is zero, the rectangle is filled

    Superscript in markdown (Github flavored)?

    Comments about previous answers

    The universal solution is using the HTML tag <sup>, as suggested in the main answer.
    However, the idea behind Markdown is precisely to avoid the use of such tags:
    The document should look nice as plain text, not only when rendered.

    Another answer proposes using Unicode characters, which makes the document look nice as a plain text document but could reduce compatibility.

    Finally, I would like to remember the simplest solution for some documents: the character ^.
    Some Markdown implementation (e.g. MacDown in macOS) interprets the caret as an instruction for superscript.

    Ex.
    Sin^2 + Cos^2 = 1
    Clearly, Stack Overflow does not interpret the caret as a superscript instruction. However, the text is comprehensible, and this is what really matters when using Markdown.

    Install tkinter for Python

    If, like me, you don't have root privileges on your network because of your wonderful friends in I.S., and you are working in a local install you may have some problems with the above approaches.

    I spent ages on Google - but in the end, it's easy.

    Download the tcl and tk from http://www.tcl.tk/software/tcltk/download.html and install them locally too.

    To install locally on Linux (I did it to my home directory), extract the .tar.gz files for tcl and tk. Then open up the readme files inside the ./unix directory. I ran

    cd ~/tcl8.5.11/unix
    ./configure --prefix=/home/cnel711 --exec-prefix=/home/cnel711
    make
    make install
    
    cd ~/tk8.5.11/unix
    ./configure --prefix=/home/cnel711 --exec-prefix=/home/cnel711 --with-tcl=/home/cnel711/tcl8.5.11/unix
    make
    make install
    

    It may seem a pain, but the files are tiny and installation is very fast.

    Then re-run python setup.py build and python setup.py install in your python installation directory - and it should work. It worked for me - and I can now import Tkinter etc to my heart's content - yipidy-yay. An entire afternoon spent on this - hope this note saves others from the pain.

    Swift Set to Array

    In the simplest case, with Swift 3, you can use Array's init(_:) initializer to get an Array from a Set. init(_:) has the following declaration:

    init<S>(_ s: S) where S : Sequence, Element == S.Iterator.Element
    

    Creates an array containing the elements of a sequence.

    Usage:

    let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy")    
    let stringArray = Array(stringSet)
    
    print(stringArray)
    // may print ["toy", "car", "bike", "boat"]
    

    However, if you also want to perform some operations on each element of your Set while transforming it into an Array, you can use map, flatMap, sort, filter and other functional methods provided by Collection protocol:

    let stringSet = Set(["car", "boat", "bike", "toy"])
    let stringArray = stringSet.sorted()
    
    print(stringArray)
    // will print ["bike", "boat", "car", "toy"]
    
    let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy") 
    let stringArray = stringSet.filter { $0.characters.first != "b" }
    
    print(stringArray)
    // may print ["car", "toy"]
    
    let intSet = Set([1, 3, 5, 2]) 
    let stringArray = intSet.flatMap { String($0) }
    
    print(stringArray)
    // may print ["5", "2", "3", "1"]
    
    let intSet = Set([1, 3, 5, 2])
    // alternative to `let intArray = Array(intSet)`
    let intArray = intSet.map { $0 }
    
    print(intArray)
    // may print [5, 2, 3, 1]
    

    Utils to read resource text file to String (Java)

    At least as of Apache commons-io 2.5, the IOUtils.toString() method supports an URI argument and returns contents of files located inside jars on the classpath:

    IOUtils.toString(SomeClass.class.getResource(...).toURI(), ...)
    

    Using an index to get an item, Python

    Same as any other language, just pass index number of element that you want to retrieve.

    #!/usr/bin/env python
    x = [2,3,4,5,6,7]
    print(x[5])
    

    Javascript / Chrome - How to copy an object from the webkit inspector as code

    Follow the following steps:

    1. Output the object with console.log from your code, like so: console.log(myObject)
    2. Right click on the object and click "Store as Global Object". Chrome would print the name of the variable at this point. Let's assume it's called "temp1".
    3. In the console, type: JSON.stringify(temp1).
    4. At this point you will see the entire JSON object as a string that you can copy/paste.
    5. You can use online tools like http://www.jsoneditoronline.org/ to prettify your string at this point.

    YouTube URL in Video Tag

    Video tag supports only video formats (like mp4 etc). Youtube does not expose its raw video files - it only exposes the unique id of the video. Since that id does not correspond to the actual file, video tag cannot be used.

    If you do get hold of the actual source file using one of the youtube download sites or soft wares, you will be able to use the video tag. But even then, the url of the actual source will cease to work after a set time. So your video also will work only till then.

    Java2D: Increase the line width

    You should use setStroke to set a stroke of the Graphics2D object.

    The example at http://www.java2s.com gives you some code examples.

    The following code produces the image below:

    import java.awt.*;
    import java.awt.geom.Line2D;
    import javax.swing.*;
    
    public class FrameTest {
        public static void main(String[] args) {
            JFrame jf = new JFrame("Demo");
            Container cp = jf.getContentPane();
            cp.add(new JComponent() {
                public void paintComponent(Graphics g) {
                    Graphics2D g2 = (Graphics2D) g;
                    g2.setStroke(new BasicStroke(10));
                    g2.draw(new Line2D.Float(30, 20, 80, 90));
                }
            });
            jf.setSize(300, 200);
            jf.setVisible(true);
        }
    }
    

    enter image description here

    (Note that the setStroke method is not available in the Graphics object. You have to cast it to a Graphics2D object.)


    This post has been rewritten as an article here.

    How do I convert this list of dictionaries to a csv file?

    import csv
    
    with open('file_name.csv', 'w') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(('colum1', 'colum2', 'colum3'))
        for key, value in dictionary.items():
            writer.writerow([key, value[0], value[1]])
    

    This would be the simplest way to write data to .csv file

    Getting the value of an attribute in XML

    This is more of an xpath question, but like this, assuming the context is the parent element:

    <xsl:value-of select="name/@attribute1" />
    

    PHP - Session destroy after closing browser

    The best way is to close the session is: if there is no response for that session after particular interval of time. then close. Please see this post and I hope it will resolve the issue. "How to change the session timeout in PHP?"

    How to uninstall downloaded Xcode simulator?

    NOTE: This will only remove a device configuration from the Xcode devices list. To remove the simulator files from your hard drive see the previous answer.

    For Xcode 7 just use Window \ Devices menu in Xcode:

    Devices menu

    Then select emulator to delete in the list on the left side and right click on it. Here is Delete option: enter image description here

    That's all.

    Display MessageBox in ASP

    If you want to do it from code behind, try this:

    System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Message');", true);
    

    Change Project Namespace in Visual Studio

    "Default Namespace textbox in project properties is disabled" Same with me (VS 2010). I edited the project file ("xxx.csproj") and tweaked the item. That changed the default namespace.

    How to iterate over array of objects in Handlebars?

    You can pass this to each block. See here: http://jsfiddle.net/yR7TZ/1/

    {{#each this}}
        <div class="row"></div>
    {{/each}}
    

    Use of def, val, and var in scala

    To provide another perspective, "def" in Scala means something that will be evaluated each time when it's used, while val is something that is evaluated immediately and only once. Here, the expression def person = new Person("Kumar",12) entails that whenever we use "person" we will get a new Person("Kumar",12) call. Therefore it's natural that the two "person.age" are non-related.

    This is the way I understand Scala(probably in a more "functional" manner). I'm not sure if

    def defines a method
    val defines a fixed value (which cannot be modified)
    var defines a variable (which can be modified)
    

    is really what Scala intends to mean though. I don't really like to think that way at least...

    How to create a floating action button (FAB) in android, using AppCompat v21?

    Add padding and elevation:

     android:elevation="10dp"
     android:padding="10dp"
    

    Export multiple classes in ES6 modules

    For exporting the instances of the classes you can use this syntax:

    // export index.js
    const Foo = require('./my/module/foo');
    const Bar = require('./my/module/bar');
    
    module.exports = {
        Foo : new Foo(),
        Bar : new Bar()
    };
    
    // import and run method
    const {Foo,Bar} = require('module_name');
    Foo.test();
    

    matplotlib: colorbars and its text labels

    To add to tacaswell's answer, the colorbar() function has an optional cax input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.

    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    fig, ax = plt.subplots()
    heatmap = ax.imshow(data)
    divider = make_axes_locatable(ax)
    cax = divider.append_axes('bottom', size='10%', pad=0.6)
    cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')
    
    cax.set_xlabel('data label')  # cax == cb.ax
    

    angularjs - using {{}} binding inside ng-src but ng-src doesn't load

    Changing the ng-src value is actually very simple. Like this:

    <html ng-app>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
    </head>
    <body>
    <img ng-src="{{img_url}}">
    <button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
    </body>
    </html>
    

    Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

    Convert String To date in PHP

    Use the strtotime function:

    Example:

     $date = "25 december 2009";
     $my_date = date('m/d/y', strtotime($date));
     echo $my_date;
    

    How to name variables on the fly?

    FAQ says:

    If you have

    varname <- c("a", "b", "d")
    

    you can do

    get(varname[1]) + 2
    

    for

    a + 2
    

    or

    assign(varname[1], 2 + 2)
    

    for

    a <- 2 + 2
    

    So it looks like you use GET when you want to evaluate a formula that uses a variable (such as a concatenate), and ASSIGN when you want to assign a value to a pre-declared variable.

    Syntax for assign: assign(x, value)

    x: a variable name, given as a character string. No coercion is done, and the first element of a character vector of length greater than one will be used, with a warning.

    value: value to be assigned to x.

    If condition inside of map() React

    If you're a minimalist like me. Say you only want to render a record with a list containing entries.

    <div>
      {data.map((record) => (
        record.list.length > 0
          ? (<YourRenderComponent record={record} key={record.id} />)
          : null
      ))}
    </div>
    

    How do I exit the Vim editor?

    Before you enter a command, hit the Esc key. After you enter it, hit the Return to confirm.

    Esc finishes the current command and switches Vim to normal mode. Now if you press :, the : will appear at the bottom of the screen. This confirms that you're actually typing a command and not editing the file.

    Most commands have abbreviations, with optional part enclosed in brackets: c[ommand].

    Commands marked with '*' are Vim-only (not implemented in Vi).

    Safe-quit (fails if there are unsaved changes):

    • :q[uit] Quit the current window. Quit Vim if this is the last window. This fails when changes have been made in current buffer.
    • :qa[ll]* Quit all windows and Vim, unless there are some buffers which have been changed.

    Prompt-quit (prompts if there are unsaved changes)

    • :conf[irm] q[uit]* Quit, but give prompt when there are some buffers which have been changed.
    • :conf[irm] xa[ll]* Write all changed buffers and exit Vim. Bring up a prompt when some buffers cannot be written.

    Write (save) changes and quit:

    • :wq Write the current file (even if it was not changed) and quit. Writing fails when the file is read-only or the buffer does not have a name. :wqa[ll]* for all windows.
    • :wq! The same, but writes even read-only files. :wqa[ll]!* for all windows.
    • :x[it], ZZ(with details). Write the file only if it was changed and quit, :xa[ll]* for all windows.

    Discard changes and quit:

    • :q[uit]! ZQ* Quit without writing, also when visible buffers have changes. Does not exit when there are changed hidden buffers.
    • :qa[ll]!*, :quita[ll][!]* Quit Vim, all changes to the buffers (including hidden) are lost.

    Press Return to confirm the command.

    This answer doesn't reference all Vim write and quit commands and arguments. Indeed, they are referenced in the Vim documentation.

    Vim has extensive built-in help, type Esc:helpReturn to open it.

    This answer was inspired by the other one, originally authored by @dirvine and edited by other SO users. I've included more information from Vim reference, SO comments and some other sources. Differences for Vi and Vim are reflected too.

    jQuery $.cookie is not a function

    Solve jQuery $.cookie is not a function this Problem jquery cdn update in solve this problem

     <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
     <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
    

    @HostBinding and @HostListener: what do they do and what are they for?

    // begginers
    @Component({
      selector: 'custom-comp',
      template: ` <div class="my-class" (click)="onClick()">CLICK ME</div> `,
    })
    export class CustomComp {
      onClick = () => console.log('click event');
    }
    
    // pros
    @Component({
      selector: 'custom-comp',
      template: ` CLICK ME `,
    })
    export class CustomComp {
      @HostBinding('class') class = 'my-class';
      @HostListener('click') onClick = () => console.log('click event');
    }
    
    // experts
    @Component({
      selector: 'custom-comp',
      template: ` CLICK ME `,
      host: {
        class: 'my-class',
        '(click)': 'onClick()',
      },
    })
    export class CustomComp {}
    
    ------------------------------------------------
    The 1st way will result in:
    <custom-comp>
       <div class="my-class" (click)="onClick()">
          CLICK ME
       <div>
    </custom-comp>
    
    The last 2 ways will result in:
    <custom-comp class="my-class" (click)="onClick()">
       CLICK ME
    </custom-comp>
    

    Remove a fixed prefix/suffix from a string in Bash

    $ string="hello-world"
    $ prefix="hell"
    $ suffix="ld"
    
    $ #remove "hell" from "hello-world" if "hell" is found at the beginning.
    $ prefix_removed_string=${string/#$prefix}
    
    $ #remove "ld" from "o-world" if "ld" is found at the end.
    $ suffix_removed_String=${prefix_removed_string/%$suffix}
    $ echo $suffix_removed_String
    o-wor
    

    Notes:

    #$prefix : adding # makes sure that substring "hell" is removed only if it is found in beginning. %$suffix : adding % makes sure that substring "ld" is removed only if it is found in end.

    Without these, the substrings "hell" and "ld" will get removed everywhere, even it is found in the middle.

    Facebook user url by id

    The marked answer seems outdated and it won't work.

    Facebook now only gives unique ID related to app which isn't equal to userId and profileUrl and username will come out to be empty.

    Doing me?fields=id,name,links is also depreciated after Graph Version 2.4

    The only option now is to request for user_links permission from your developer console.

    enter image description here

    and the pass it in scope when doing facebook login

    scope: ['user_link'] }
    

    or by doing an api call

    Download and save PDF file with Python requests module

    Please note I'm a beginner. If My solution is wrong, please feel free to correct and/or let me know. I may learn something new too.

    My solution:

    Change the downloadPath accordingly to where you want your file to be saved. Feel free to use the absolute path too for your usage.

    Save the below as downloadFile.py.

    Usage: python downloadFile.py url-of-the-file-to-download new-file-name.extension

    Remember to add an extension!

    Example usage: python downloadFile.py http://www.google.co.uk google.html

    import requests
    import sys
    import os
    
    def downloadFile(url, fileName):
        with open(fileName, "wb") as file:
            response = requests.get(url)
            file.write(response.content)
    
    
    scriptPath = sys.path[0]
    downloadPath = os.path.join(scriptPath, '../Downloads/')
    url = sys.argv[1]
    fileName = sys.argv[2]      
    print('path of the script: ' + scriptPath)
    print('downloading file to: ' + downloadPath)
    downloadFile(url, downloadPath + fileName)
    print('file downloaded...')
    print('exiting program...')
    

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

    Html.Hidden and Html.HiddenFor used to generate name-value pairs which waited by action method in controller. Sample Usage(*):

    @using (Html.BeginForm("RemoveFromCart", "Cart")) {
                        @Html.Hidden("ProductId", line.Product.ProductID)
                        @Html.HiddenFor(x => x.ReturnUrl)
                        <input class="btn btn-sm btn-warning"
                               type="submit" value="Remove" />
                    }
    

    If your action method wait for "ProductId" you have to generate this name in form via using (Html.Hidden or Html.HiddenFor) For the case it is not possible to generate this name with strongly typed model you simple write this name with a string thats "ProductId".

    public ViewResult RemoveFromCart(int productId, string returnUrl){...}
    

    If I had written Html.HiddenFor(x => line.Product.ProductID), the helper would render a hidden field with the name "line.Product.ProductID". The name of the field would not match the names of the parameters for the "RemoveFromCart" action method which waiting the name of "ProductId". This would prevent the default model binders from working, so the MVC Framework would not be able to call the method.

    *Adam Freeman (Apress - Pro ASP.Net MVC 5)

    How to fade changing background image

    If your trying to fade the backgound image but leave the foreground text/images you could use css to separate the background image into a new div and position it over the div containing the text/images then fade the background div.

    Return None if Dictionary key is not available

    If you can do it with False, then, there's also the hasattr built-in funtion:

    e=dict()
    hasattr(e, 'message'):
    >>> False
    

    Best approach to converting Boolean object to string in java

    Depends on what you mean by "efficient". Performance-wise both versions are the same as its the same bytecode.

    $ ./javap.exe -c java.lang.String | grep -A 10 "valueOf(boolean)"
      public static java.lang.String valueOf(boolean);
        Code:
           0: iload_0
           1: ifeq          9
           4: ldc           #14                 // String true
           6: goto          11
           9: ldc           #10                 // String false
          11: areturn
    
    
    $ ./javap.exe -c java.lang.Boolean | grep -A 10 "toString(boolean)"
      public static java.lang.String toString(boolean);
        Code:
           0: iload_0
           1: ifeq          9
           4: ldc           #3                  // String true
           6: goto          11
           9: ldc           #2                  // String false
          11: areturn
    

    Git error: src refspec master does not match any error: failed to push some refs

    One classic root cause for this message is:

    • when the repo has been initialized (git init lis4368/assignments),
    • but no commit has ever been made

    Ie, if you don't have added and committed at least once, there won't be a local master branch to push to.

    Try first to create a commit:

    • either by adding (git add .) then git commit -m "first commit"
      (assuming you have the right files in place to add to the index)
    • or by create a first empty commit: git commit --allow-empty -m "Initial empty commit"

    And then try git push -u origin master again.

    See "Why do I need to explicitly push a new branch?" for more.

    How to delete the first row of a dataframe in R?

    You can use negative indexing to remove rows, e.g.:

    dat <- dat[-1, ]
    

    Here is an example:

    > dat <- data.frame(A = 1:3, B = 1:3)
    > dat[-1, ]
      A B
    2 2 2
    3 3 3
    > dat2 <- dat[-1, ]
    > dat2
      A B
    2 2 2
    3 3 3
    

    That said, you may have more problems than just removing the labels that ended up on row 1. It is more then likely that R has interpreted the data as text and thence converted to factors. Check what str(foo), where foo is your data object, says about the data types.

    It sounds like you just need header = TRUE in your call to read in the data (assuming you read it in via read.table() or one of it's wrappers.)

    Touch move getting stuck Ignored attempt to cancel a touchmove

    Please remove e.preventDefault(), because event.cancelable of touchmove is false. So you can't call this method.

    Java NIO FileChannel versus FileOutputstream performance / usefulness

    I tested the performance of FileInputStream vs. FileChannel for decoding base64 encoded files. In my experients I tested rather large file and traditional io was alway a bit faster than nio.

    FileChannel might have had an advantage in prior versions of the jvm because of synchonization overhead in several io related classes, but modern jvm are pretty good at removing unneeded locks.

    Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

    It seems to be a nasty problem of Gradle. We just upgraded from 2.14 to 3.3 and our build server couldn't build any more (a local build in Android Studio worked).

    Error with too long path shows for example:

    C:\Windows\System32\config\systemprofile.gradle\caches\3.3\scripts-remapped\build_bonsjy48fqq8sotonpgrvhswt\36ejadunoxgw3iugkh95lqw\projedd7e29570ae79482d0308d82f4e346b\classes\build_bonsjy48fqq8sotonpgrvhswt$_run_closure1$_closure8$_closure13$_closure14$_closure15.class

    We had to create a local user account for the service that ran as system service for years... Now it saves under C:\Users... which is much shorter as the system profile path.

    How can I change the Java Runtime Version on Windows (7)?

    All you need to do is set the PATH environment variable in Windows to point to where your java6 bin directory is instead of the java7 directory.

    Right click My Computer > Advanced System Settings > Advanced > Environmental Variables

    If there is a JAVA_HOME environment variable set this to point to the correct directory as well.

    How to refresh a page with jQuery by passing a parameter to URL

    I'm using Jquery Load to handels this, works great for me. check out my code from my project. I need to refresh with arguments to put Javascript variable into php

    if (isset($_GET['language'])){
        $language = $_GET['language'];
    }else{
        echo '<script>';    
        echo '  var userLang = navigator.language || navigator.userLanguage;';
        echo '  if(userLang.search("zh") != -1) {';
        echo '      var language = "chn";';
        echo '  }else{';
        echo '      var language = "eng";';
        echo '  }';
        echo '$("html").load("index.php","language=" + language);';
        echo '</script>';
        die;
    }
    

    Running AMP (apache mysql php) on Android

    Have you tried using Linux Installer to get a full Debian build on the phone? It's billed as being able to run a full LAMP environment in about 300M and has gotten some good reviews.

    The following artifacts could not be resolved: javax.jms:jms:jar:1.1

    You import one dependency, and this dependency is dependent on com.sun.jmx:jmxri:jar:1.2.1 and others, but com.sun.jmx:jmxri:jar:1.2.1 cannot be found in central repository,

    so you'd better try to import another version.

    Here suppose your dependency may be log4j, and you can try to import log4j:log4j:jar:1.2.13.

    Undefined behavior and sequence points

    This is a follow up to my previous answer and contains C++11 related material..


    Pre-requisites : An elementary knowledge of Relations (Mathematics).


    Is it true that there are no Sequence Points in C++11?

    Yes! This is very true.

    Sequence Points have been replaced by Sequenced Before and Sequenced After (and Unsequenced and Indeterminately Sequenced) relations in C++11.


    What exactly is this 'Sequenced before' thing?

    Sequenced Before(§1.9/13) is a relation which is:

    between evaluations executed by a single thread and induces a strict partial order1

    Formally it means given any two evaluations(See below) A and B, if A is sequenced before B, then the execution of A shall precede the execution of B. If A is not sequenced before B and B is not sequenced before A, then A and B are unsequenced 2.

    Evaluations A and B are indeterminately sequenced when either A is sequenced before B or B is sequenced before A, but it is unspecified which3.

    [NOTES]
    1 : A strict partial order is a binary relation "<" over a set P which is asymmetric, and transitive, i.e., for all a, b, and c in P, we have that:
    ........(i). if a < b then ¬ (b < a) (asymmetry);
    ........(ii). if a < b and b < c then a < c (transitivity).
    2 : The execution of unsequenced evaluations can overlap.
    3 : Indeterminately sequenced evaluations cannot overlap, but either could be executed first.


    What is the meaning of the word 'evaluation' in context of C++11?

    In C++11, evaluation of an expression (or a sub-expression) in general includes:

    • value computations (including determining the identity of an object for glvalue evaluation and fetching a value previously assigned to an object for prvalue evaluation) and

    • initiation of side effects.

    Now (§1.9/14) says:

    Every value computation and side effect associated with a full-expression is sequenced before every value computation and side effect associated with the next full-expression to be evaluated.

    • Trivial example:

      int x; x = 10; ++x;

      Value computation and side effect associated with ++x is sequenced after the value computation and side effect of x = 10;


    So there must be some relation between Undefined Behaviour and the above-mentioned things, right?

    Yes! Right.

    In (§1.9/15) it has been mentioned that

    Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced4.

    For example :

    int main()
    {
         int num = 19 ;
         num = (num << 3) + (num >> 3);
    } 
    
    1. Evaluation of operands of + operator are unsequenced relative to each other.
    2. Evaluation of operands of << and >> operators are unsequenced relative to each other.

    4: In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations.

    (§1.9/15) The value computations of the operands of an operator are sequenced before the value computation of the result of the operator.

    That means in x + y the value computation of x and y are sequenced before the value computation of (x + y).

    More importantly

    (§1.9/15) If a side effect on a scalar object is unsequenced relative to either

    (a) another side effect on the same scalar object

    or

    (b) a value computation using the value of the same scalar object.

    the behaviour is undefined.

    Examples:

    int i = 5, v[10] = { };
    void  f(int,  int);
    
    1. i = i++ * ++i; // Undefined Behaviour
    2. i = ++i + i++; // Undefined Behaviour
    3. i = ++i + ++i; // Undefined Behaviour
    4. i = v[i++]; // Undefined Behaviour
    5. i = v[++i]: // Well-defined Behavior
    6. i = i++ + 1; // Undefined Behaviour
    7. i = ++i + 1; // Well-defined Behaviour
    8. ++++i; // Well-defined Behaviour
    9. f(i = -1, i = -1); // Undefined Behaviour (see below)

    When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function. [Note: Value computations and side effects associated with different argument expressions are unsequenced. — end note]

    Expressions (5), (7) and (8) do not invoke undefined behaviour. Check out the following answers for a more detailed explanation.


    Final Note :

    If you find any flaw in the post please leave a comment. Power-users (With rep >20000) please do not hesitate to edit the post for correcting typos and other mistakes.

    How to get client's IP address using JavaScript?

    <script type="application/javascript">
      function getip(json)
      {
         alert(json.ip); 
      }
    

     <script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>
    

    Run above script Clik here

    form_for with nested resources

    Be sure to have both objects created in controller: @post and @comment for the post, eg:

    @post = Post.find params[:post_id]
    @comment = Comment.new(:post=>@post)
    

    Then in view:

    <%= form_for([@post, @comment]) do |f| %>
    

    Be sure to explicitly define the array in the form_for, not just comma separated like you have above.

    $watch'ing for data changes in an Angular directive

    My version for a directive that uses jqplot to plot the data once it becomes available:

        app.directive('lineChart', function() {
            $.jqplot.config.enablePlugins = true;
    
            return function(scope, element, attrs) {
                scope.$watch(attrs.lineChart, function(newValue, oldValue) {
                    if (newValue) {
                        // alert(scope.$eval(attrs.lineChart));
                        var plot = $.jqplot(element[0].id, scope.$eval(attrs.lineChart), scope.$eval(attrs.options));
                    }
                });
            }
    });
    

    SQL Server insert if not exists best practice

    Additionally, if you have multiple columns to insert and want to check if they exists or not use the following code

    Insert Into [Competitors] (cName, cCity, cState)
    Select cName, cCity, cState from 
    (
        select new.* from 
        (
            select distinct cName, cCity, cState 
            from [Competitors] s, [City] c, [State] s
        ) new
        left join 
        (   
            select distinct cName, cCity, cState 
            from [Competitors] s
        ) existing
        on new.cName = existing.cName and new.City = existing.City and new.State = existing.State
        where existing.Name is null  or existing.City is null or existing.State is null
    )
    

    HTML table with fixed headers and a fixed column?

    Working example of link posted by pranav:

    http://jsbin.com/nolanole/1/edit?html,js,output

    FYI: Tested in IE 6, 7, & 8 (compatibility mode on or off), FF 3 & 3.5, Chrome 2. Not screen-reader-friendly (headers aren't part of content table).

    EDIT 5/5/14: moved example to jsBin. This is old, but amazingly still works in current Chrome, IE, and Firefox (though IE and Firefox might require some adjustments to row heights).

    What does DIM stand for in Visual Basic and BASIC?

    Variable declaration. Initially, it was short for "dimension", which is not a term that is used in programming (outside of this specific keyword) to any significant degree.

    http://in.answers.yahoo.com/question/index?qid=20090310095555AANmiAZ

    json Uncaught SyntaxError: Unexpected token :

    You've told jQuery to expect a JSONP response, which is why jQuery has added the callback=jQuery16406345664265099913_1319854793396&_=1319854793399 part to the URL (you can see this in your dump of the request).

    What you're returning is JSON, not JSONP. Your response looks like

    {"red" : "#f00"}
    

    and jQuery is expecting something like this:

    jQuery16406345664265099913_1319854793396({"red" : "#f00"})
    

    If you actually need to use JSONP to get around the same origin policy, then the server serving colors.json needs to be able to actually return a JSONP response.

    If the same origin policy isn't an issue for your application, then you just need to fix the dataType in your jQuery.ajax call to be json instead of jsonp.

    Best way to initialize (empty) array in PHP

    Try this:

        $arr = (array) null;
        var_dump($arr);
    
        // will print
        // array(0) { }
    

    How to add hyperlink in JLabel?

    You can use this under an

    actionListener ->  Runtime.getRuntime().exec("cmd.exe /c start chrome www.google.com")`
    

    or if you want to use Internet Explorer or Firefox replace chrome with iexplore or firefox

    Activate a virtualenv with a Python script

    If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the Python interpreter that lives inside virtualenv's /bin/ directory:

    import subprocess
    
    # Path to a Python interpreter that runs any Python script
    # under the virtualenv /path/to/virtualenv/
    python_bin = "/path/to/virtualenv/bin/python"
    
    # Path to the script that must run under the virtualenv
    script_file = "must/run/under/virtualenv/script.py"
    
    subprocess.Popen([python_bin, script_file])
    

    However, if you want to activate the virtualenv under the current Python interpreter instead of a subprocess, you can use the activate_this.py script:

    # Doing execfile() on this file will alter the current interpreter's
    # environment so you can import libraries in the virtualenv
    activate_this_file = "/path/to/virtualenv/bin/activate_this.py"
    
    execfile(activate_this_file, dict(__file__=activate_this_file))
    

    JQuery Find #ID, RemoveClass and AddClass

    jQuery('#testID2').find('.test2').replaceWith('.test3');
    

    Semantically, you are selecting the element with the ID testID2, then you are looking for any descendent elements with the class test2 (does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3) that also do not exist.

    You need to do this:

    jQuery('#testID2').addClass('test3').removeClass('test2');
    

    This selects the element with the ID testID2, then adds the class test3 to it. Last, it removes the class test2 from that element.

    How to get the last day of the month?

    Here is a solution based python lambdas:

    next_month = lambda y, m, d: (y, m + 1, 1) if m + 1 < 13 else ( y+1 , 1, 1)
    month_end  = lambda dte: date( *next_month( *dte.timetuple()[:3] ) ) - timedelta(days=1)
    

    The next_month lambda finds the tuple representation of the first day of the next month, and rolls over to the next year. The month_end lambda transforms a date (dte) to a tuple, applies next_month and creates a new date. Then the "month's end" is just the next month's first day minus timedelta(days=1).

    Scanner vs. StringTokenizer vs. String.Split

    Let's start by eliminating StringTokenizer. It is getting old and doesn't even support regular expressions. Its documentation states:

    StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

    So let's throw it out right away. That leaves split() and Scanner. What's the difference between them?

    For one thing, split() simply returns an array, which makes it easy to use a foreach loop:

    for (String token : input.split("\\s+") { ... }
    

    Scanner is built more like a stream:

    while (myScanner.hasNext()) {
        String token = myScanner.next();
        ...
    }
    

    or

    while (myScanner.hasNextDouble()) {
        double token = myScanner.nextDouble();
        ...
    }
    

    (It has a rather large API, so don't think that it's always restricted to such simple things.)

    This stream-style interface can be useful for parsing simple text files or console input, when you don't have (or can't get) all the input before starting to parse.

    Personally, the only time I can remember using Scanner is for school projects, when I had to get user input from the command line. It makes that sort of operation easy. But if I have a String that I want to split up, it's almost a no-brainer to go with split().

    How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

    Just need to add: new SimpleDateFormat("bla bla bla", Locale.US)

    public static void main(String[] args) throws ParseException {
        java.util.Date fecha = new java.util.Date("Mon Dec 15 00:00:00 CST 2014");
        DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
        Date date;
        date = (Date)formatter.parse(fecha.toString());
        System.out.println(date);        
    
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        String formatedDate = cal.get(Calendar.DATE) + "/" + 
                (cal.get(Calendar.MONTH) + 1) + 
                "/" +         cal.get(Calendar.YEAR);
        System.out.println("formatedDate : " + formatedDate);
    }
    

    Initialise numpy array of unknown length

    You can do this:

    a = np.array([])
    for x in y:
        a = np.append(a, x)