Programs & Examples On #Listeners

An object that reacts to an event that it is 'listening' for.

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

I found some issue about that kind of error

  1. Database username or password not match in the mysql or other other database. Please set application.properties like this

  

# =============================== # = DATA SOURCE # =============================== # Set here configurations for the database connection # Connection url for the database please let me know "[email protected]" spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc # Username and secret spring.datasource.username = root spring.datasource.password = # Keep the connection alive if idle for a long time (needed in production) spring.datasource.testWhileIdle = true spring.datasource.validationQuery = SELECT 1 # =============================== # = JPA / HIBERNATE # =============================== # Use spring.jpa.properties.* for Hibernate native properties (the prefix is # stripped before adding them to the entity manager). # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update): with "update" the database # schema will be automatically updated accordingly to java entities found in # the project spring.jpa.hibernate.ddl-auto = update # Allows Hibernate to generate SQL optimized for a particular DBMS spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Issue no 2.

Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine

Why is setState in reactjs Async instead of Sync?

1) setState actions are asynchronous and are batched for performance gains. This is explained in the documentation of setState.

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.


2) Why would they make setState async as JS is a single threaded language and this setState is not a WebAPI or server call?

This is because setState alters the state and causes rerendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive.

Thus the setState calls are asynchronous as well as batched for better UI experience and performance.

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

I have got this error (in MacBook) though I used correct command to create image,

docker build -t testimg .

Later I found that path is the problem. Just navigate to the correct path that contains docker file. Just double check your current working directory .Nothing to panic!

Dynamically add event listener

I aso find this extremely confusing. as @EricMartinez points out Renderer2 listen() returns the function to remove the listener:

ƒ () { return element.removeEventListener(eventName, /** @type {?} */ (handler), false); }

If i´m adding a listener

this.listenToClick = this.renderer.listen('document', 'click', (evt) => {
    alert('Clicking the document');
})

I´d expect my function to execute what i intended, not the total opposite which is remove the listener.

// I´d expect an alert('Clicking the document'); 
this.listenToClick();
// what you actually get is removing the listener, so nothing...

In the given scenario, It´d actually make to more sense to name it like:

// Add listeners
let unlistenGlobal = this.renderer.listen('document', 'click', (evt) => {
    console.log('Clicking the document', evt);
})

let removeSimple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
    console.log('Clicking the button', evt);
});

There must be a good reason for this but in my opinion it´s very misleading and not intuitive.

Invariant Violation: Objects are not valid as a React child

In my case the error was happening because I returned elements array in curly braces instead of just returning the array itself.

Code with error

   render() {
        var rows = this.props.products.map(product => <tr key={product.id}><td>{product.name}</td><td>{product.price}</td></tr>
        );
        return {rows};
    }

Correct code

render() {
    var rows = this.props.products.map(product => <tr key={product.id}><td>{product.name}</td><td>{product.price}</td></tr>
    );
    return rows;
}

Get div's offsetTop positions in React

You may be encouraged to use the Element.getBoundingClientRect() method to get the top offset of your element. This method provides the full offset values (left, top, right, bottom, width, height) of your element in the viewport.

Check the John Resig's post describing how helpful this method is.

WARNING: Exception encountered during context initialization - cancelling refresh attempt

I was having the problem as a beginner..........

There was issue in the path of the xml file I have saved.

ECMAScript 6 class destructor

Is there such a thing as destructors for ECMAScript 6?

No. EcmaScript 6 does not specify any garbage collection semantics at all[1], so there is nothing like a "destruction" either.

If I register some of my object's methods as event listeners in the constructor, I want to remove them when my object is deleted

A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered.
What you are actually looking for is a method of registering listeners without marking them as live root objects. (Ask your local eventsource manufacturer for such a feature).

1): Well, there is a beginning with the specification of WeakMap and WeakSet objects. However, true weak references are still in the pipeline [1][2].

Upload a file to Amazon S3 with NodeJS

Or Using promises:

const AWS = require('aws-sdk');
AWS.config.update({
    accessKeyId: 'accessKeyId',
    secretAccessKey: 'secretAccessKey',
    region: 'region'
});

let params = {
    Bucket: "yourBucketName",
    Key: 'someUniqueKey',
    Body: 'someFile'
};
try {
    let uploadPromise = await new AWS.S3().putObject(params).promise();
    console.log("Successfully uploaded data to bucket");
} catch (e) {
    console.log("Error uploading data: ", e);
}

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

$rootScope.$broadcast vs. $scope.$emit

enter image description here

$scope.$emit: This method dispatches the event in the upwards direction (from child to parent)

enter image description here $scope.$broadcast: Method dispatches the event in the downwards direction (from parent to child) to all the child controllers.

enter image description here $scope.$on: Method registers to listen to some event. All the controllers which are listening to that event get notification of the broadcast or emit based on the where those fit in the child-parent hierarchy.

The $emit event can be cancelled by any one of the $scope who is listening to the event.

The $on provides the "stopPropagation" method. By calling this method the event can be stopped from propagating further.

Plunker :https://embed.plnkr.co/0Pdrrtj3GEnMp2UpILp4/

In case of sibling scopes (the scopes which are not in the direct parent-child hierarchy) then $emit and $broadcast will not communicate to the sibling scopes.

enter image description here

For more details please refer to http://yogeshtutorials.blogspot.in/2015/12/event-based-communication-between-angularjs-controllers.html

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

Could me multiple reason for this. But you want might forget to add as @Bean for component which you have did @Autowired.

In my case, i have forgot to decorate with @Bean which causing this issue.

docker error: /var/run/docker.sock: no such file or directory

docker pull will fail if docker service is not running. Make sure it is running by

:~$ ps aux | grep docker
root     18745  1.7  0.9 284104 13976 ?   Ssl  21:19   0:01 /usr/bin/docker -d

If it is not running, you can start it by

sudo service docker start

For Ubuntu 15 and above use

sudo systemctl start docker

How to find what code is run by a button or element in Chrome using Developer Tools

Sounds like the "...and I jump line by line..." part is wrong. Do you StepOver or StepIn and are you sure you don't accidentally miss the relevant call?

That said, debugging frameworks can be tedious for exactly this reason. To alleviate the problem, you can enable the "Enable frameworks debugging support" experiment. Happy debugging! :)

Deciding between HttpClient and WebClient

Perhaps you could think about the problem in a different way. WebClient and HttpClient are essentially different implementations of the same thing. What I recommend is implementing the Dependency Injection pattern with an IoC Container throughout your application. You should construct a client interface with a higher level of abstraction than the low level HTTP transfer. You can write concrete classes that use both WebClient and HttpClient, and then use the IoC container to inject the implementation via config.

What this would allow you to do would be to switch between HttpClient and WebClient easily so that you are able to objectively test in the production environment.

So questions like:

Will HttpClient be a better design choice if we upgrade to .Net 4.5?

Can actually be objectively answered by switching between the two client implementations using the IoC container. Here is an example interface that you might depend on that doesn't include any details about HttpClient or WebClient.

/// <summary>
/// Dependency Injection abstraction for rest clients. 
/// </summary>
public interface IClient
{
    /// <summary>
    /// Adapter for serialization/deserialization of http body data
    /// </summary>
    ISerializationAdapter SerializationAdapter { get; }

    /// <summary>
    /// Sends a strongly typed request to the server and waits for a strongly typed response
    /// </summary>
    /// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
    /// <typeparam name="TRequestBody">The type of the request body if specified</typeparam>
    /// <param name="request">The request that will be translated to a http request</param>
    /// <returns></returns>
    Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(Request<TRequestBody> request);

    /// <summary>
    /// Default headers to be sent with http requests
    /// </summary>
    IHeadersCollection DefaultRequestHeaders { get; }

    /// <summary>
    /// Default timeout for http requests
    /// </summary>
    TimeSpan Timeout { get; set; }

    /// <summary>
    /// Base Uri for the client. Any resources specified on requests will be relative to this.
    /// </summary>
    Uri BaseUri { get; set; }

    /// <summary>
    /// Name of the client
    /// </summary>
    string Name { get; }
}

public class Request<TRequestBody>
{
    #region Public Properties
    public IHeadersCollection Headers { get; }
    public Uri Resource { get; set; }
    public HttpRequestMethod HttpRequestMethod { get; set; }
    public TRequestBody Body { get; set; }
    public CancellationToken CancellationToken { get; set; }
    public string CustomHttpRequestMethod { get; set; }
    #endregion

    public Request(Uri resource,
        TRequestBody body,
        IHeadersCollection headers,
        HttpRequestMethod httpRequestMethod,
        IClient client,
        CancellationToken cancellationToken)
    {
        Body = body;
        Headers = headers;
        Resource = resource;
        HttpRequestMethod = httpRequestMethod;
        CancellationToken = cancellationToken;

        if (Headers == null) Headers = new RequestHeadersCollection();

        var defaultRequestHeaders = client?.DefaultRequestHeaders;
        if (defaultRequestHeaders == null) return;

        foreach (var kvp in defaultRequestHeaders)
        {
            Headers.Add(kvp);
        }
    }
}

public abstract class Response<TResponseBody> : Response
{
    #region Public Properties
    public virtual TResponseBody Body { get; }

    #endregion

    #region Constructors
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response() : base()
    {
    }

    protected Response(
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    TResponseBody body,
    Uri requestUri
    ) : base(
        headersCollection,
        statusCode,
        httpRequestMethod,
        responseData,
        requestUri)
    {
        Body = body;
    }

    public static implicit operator TResponseBody(Response<TResponseBody> readResult)
    {
        return readResult.Body;
    }
    #endregion
}

public abstract class Response
{
    #region Fields
    private readonly byte[] _responseData;
    #endregion

    #region Public Properties
    public virtual int StatusCode { get; }
    public virtual IHeadersCollection Headers { get; }
    public virtual HttpRequestMethod HttpRequestMethod { get; }
    public abstract bool IsSuccess { get; }
    public virtual Uri RequestUri { get; }
    #endregion

    #region Constructor
    /// <summary>
    /// Only used for mocking or other inheritance
    /// </summary>
    protected Response()
    {
    }

    protected Response
    (
    IHeadersCollection headersCollection,
    int statusCode,
    HttpRequestMethod httpRequestMethod,
    byte[] responseData,
    Uri requestUri
    )
    {
        StatusCode = statusCode;
        Headers = headersCollection;
        HttpRequestMethod = httpRequestMethod;
        RequestUri = requestUri;
        _responseData = responseData;
    }
    #endregion

    #region Public Methods
    public virtual byte[] GetResponseData()
    {
        return _responseData;
    }
    #endregion
}

Full code

HttpClient Implementation

You can use Task.Run to make WebClient run asynchronously in its implementation.

Dependency Injection, when done well helps alleviate the problem of having to make low level decisions upfront. Ultimately, the only way to know the true answer is try both in a live environment and see which one works the best. It's quite possible that WebClient may work better for some customers, and HttpClient may work better for others. This is why abstraction is important. It means that code can quickly be swapped in, or changed with configuration without changing the fundamental design of the app.

BTW: there are numerous other reasons that you should use an abstraction instead of directly calling one of these low-level APIs. One huge one being unit-testability.

Could not resolve placeholder in string value

I´m frequently running into this issue on some custom properties that could not be found using IntelliJ IDEA - likely after changing branches.

What helpes in my case is

File -> Invalidate Caches / Restart

I had the assumption that it is more likely a Gradle caching issue than an IDE issue, but ./gradle clean did not help

BeanFactory not initialized or already closed - call 'refresh' before

This exception come due to you are providing listener ContextLoaderListener

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

but you are not providing context-param for your spring configuration file. like applicationContext.xml You must provide below snippet for your configuration

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>applicationContext.xml</param-value>
</context-param>

If You are providing the java based spring configuration , means you are not using xml file for spring configuration at that time you must provide below code:

<!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext
instead of the default XmlWebApplicationContext -->
<context-param>
    <param-name>contextClass</param-name>
    <param-value>
    org.springframework.web.context.support.AnnotationConfigWebApplicationContext
    </param-value>
</context-param>

<!-- Configuration locations must consist of one or more comma- or space-delimited
fully-qualified @Configuration classes. Fully-qualified packages may also
be specified for component-scanning -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.nirav.modi.config.SpringAppConfig</param-value>
</context-param>

WCF Exception: Could not find a base address that matches scheme http for the endpoint

My issue was also caused by missing https binding in IIS: Selected default website > On the far right pane selected Bindings > add > https

Choose 'IIS Express Development Certificate' and set port to 443

Remove All Event Listeners of Specific Type

You cant remove a single event, but all? at once? just do

document.body.innerHTML = document.body.innerHTML

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

My solution below is for cases when default maven repositories are not accessible (e.g. due to firewalls).

In case the default repository is not accessible appropriate local <pluginRepository> has to be specified in the settings.xml. If it's the same as your local artifact repository it still needs to be added to the <pluginRepositories> section for plugin jars to be found. Regular <repositories> section is not used to fetch plugin jars.

In my case, however, the issue was caused by the fact that there were multiple plugin repositories defined in that section.

The first repository in the list did not contain the required maven-filtering jar.

I had to change the order of <pluginRepository> definitions to ensure the first one contains maven-filtering.

Changing of repository definitions typically requires to clean ~/.m2/repository and start fresh.

-bash: export: `=': not a valid identifier

Try to surround the path with quotes, and remove the spaces

export PYTHONPATH="/home/user/my_project":$PYTHONPATH

And don't forget to preserve previous content suffixing by :$PYTHONPATH (which is the value of the variable)

Execute the following command to check everything is configured correctly:

echo $PYTHONPATH

Uncaught ReferenceError: function is not defined with onclick

I was receiving the error (I'm using Vue) and I switched my onclick="someFunction()" to @click="someFunction" and now they are working.

jQuery textbox change event doesn't fire until textbox loses focus?

Reading your comments took me to a dirty fix. This is not a right way, I know, but can be a work around.

$(function() {
    $( "#inputFieldId" ).autocomplete({
        source: function( event, ui ) {
            alert("do your functions here");
            return false;
        }
    });
});

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Deleting full .m2 local repository solved my problem, too.

If you don't know where it is, the locations are:

Unix/Mac OS X – ~/.m2/repository
Windows – C:\Documents and Settings\{your-username}\.m2\repository 
        ( %USERPROFILE%\.m2\repository too, as suggested by **MC Empero** )

How to get JSON response from http.Get

The results from json.Unmarshal (into var data interface{}) do not directly match your Go type and variable declarations. For example,

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

type Tracks struct {
    Toptracks []Toptracks_info
}

type Toptracks_info struct {
    Track []Track_info
    Attr  []Attr_info
}

type Track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []Streamable_info
    Artist     []Artist_info
    Attr       []Track_attr_info
}

type Attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type Streamable_info struct {
    Text      string
    Fulltrack string
}

type Artist_info struct {
    Name string
    Mbid string
    Url  string
}

type Track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
    url += "&limit=1" // limit data for testing
    res, err := http.Get(url)
    if err != nil {
        panic(err.Error())
    }
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err.Error())
    }
    var data interface{} // TopTracks
    err = json.Unmarshal(body, &data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Output:

Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]

OnClickListener in Android Studio

This worked for me:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_newarea);

    btnSave = (Button)findViewById(R.id.btnSave);

    OnClickListener btnListener = new OnClickListener() {
        @Override
        public void onClick(android.view.View view) {
            finish();
        }
    };
    btnSave.setOnClickListener(btnListener);

}

How to detect control+click in Javascript from an onclick div attribute?

From above only , just edited so it works right away

<script>
    var control = false;
    $(document).on('keyup keydown', function (e) {
        control = e.ctrlKey;
    });

    $(function () {
        $('#1x').on('click', function () {
            if (control) {
                // control-click
                alert("Control+Click");
            } else {
                // single-click
                alert("Single Click");
            }
        });
    }); 

</script>
<p id="1x">Click me</p>

How do I escape a single quote ( ' ) in JavaScript?

The answer here is very simple:

You're already containing it in double quotes, so there's no need to escape it with \.

If you want to escape single quotes in a single quote string:

var string = 'this isn\'t a double quoted string';
var string = "this isn\"t a single quoted string";
//           ^         ^ same types, hence we need to escape it with a backslash

or if you want to escape \', you can escape the bashslash to \\ and the quote to \' like so:

var string = 'this isn\\\'t a double quoted string';
//                    vvvv
//                     \ ' (the escaped characters)

However, if you contain the string with a different quote type, you don't need to escape:

var string = 'this isn"t a double quoted string';
var string = "this isn't a single quoted string";
//           ^        ^ different types, hence we don't need escaping

Playing HTML5 video on fullscreen in android webview

Just set
mWebView.setWebChromeClient(new WebChromeClient());

and video plays as normally wont need any custom view.

Given URL is not permitted by the application configuration

  1. From the menu item of your app name which is located on the top left corner, create a test app.
  2. In the settings section of the new test app: add 'http://localhost:3000' to the Website url and add 'localhost' to App domains.
  3. Update your app with the new Facebook APP Id
  4. Use Facebook sdk v2.2 or whatever the latest in your app.

Android + Pair devices via bluetooth programmatically

Edit: I have just explained logic to pair here. If anybody want to go with the complete code then see my another answer. I have answered here for logic only but I was not able to explain properly, So I have added another answer in the same thread.

Try this to do pairing:

If you are able to search the devices then this would be your next step

ArrayList<BluetoothDevice> arrayListBluetoothDevices = NEW ArrayList<BluetoothDevice>;

I am assuming that you have the list of Bluetooth devices added in the arrayListBluetoothDevices:

BluetoothDevice bdDevice;
bdDevice = arrayListBluetoothDevices.get(PASS_THE_POSITION_TO_GET_THE_BLUETOOTH_DEVICE);

Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
    Log.i("Log","Paired");
}
} catch (Exception e) 
{
    e.printStackTrace(); 
}

The createBond() method:

public boolean createBond(BluetoothDevice btDevice)  
    throws Exception  
    { 
        Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
        Method createBondMethod = class1.getMethod("createBond");  
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
        return returnValue.booleanValue();  
    }  

Add this line into your Receiver in the ACTION_FOUND

if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    arrayListBluetoothDevices.add(device);
                }

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

Here's my take on the problem. I create AbsoluteLayout overlay which contains Info Window (a regular view with every bit of interactivity and drawing capabilities). Then I start Handler which synchronizes the info window's position with position of point on the map every 16 ms. Sounds crazy, but actually works.

Demo video: https://www.youtube.com/watch?v=bT9RpH4p9mU (take into account that performance is decreased because of emulator and video recording running simultaneously).

Code of the demo: https://github.com/deville/info-window-demo

An article providing details (in Russian): http://habrahabr.ru/post/213415/

Spring profiles and testing

@EnableConfigurationProperties needs to be there (you also can annotate your test class), the application-localtest.yml from test/resources will be loaded. A sample with jUnit5

@ExtendWith(SpringExtension.class)
@EnableConfigurationProperties
@ContextConfiguration(classes = {YourClasses}, initializers = ConfigFileApplicationContextInitializer.class)
@ActiveProfiles(profiles = "localtest")
class TestActiveProfile {

    @Test
    void testActiveProfile(){

    }
}

JavaFX: How to get stage from controller during initialization?

Assign fx:id or declare variable to/of any node: anchorpane, button, etc. Then add event handler to it and within that event handler insert the given code below:

Stage stage = (Stage)((Node)((EventObject) eventVariable).getSource()).getScene().getWindow();

Hope, this works for you!!

If a DOM Element is removed, are its listeners also removed from memory?

Modern browsers

Plain JavaScript

If a DOM element which is removed is reference-free (no references pointing to it) then yes - the element itself is picked up by the garbage collector as well as any event handlers/listeners associated with it.

var a = document.createElement('div');
var b = document.createElement('p');
// Add event listeners to b etc...
a.appendChild(b);
a.removeChild(b);
b = null; 
// A reference to 'b' no longer exists 
// Therefore the element and any event listeners attached to it are removed.

However; if there are references that still point to said element, the element and its event listeners are retained in memory.

var a = document.createElement('div');
var b = document.createElement('p'); 
// Add event listeners to b etc...
a.appendChild(b);
a.removeChild(b); 
// A reference to 'b' still exists 
// Therefore the element and any associated event listeners are still retained.

jQuery

It would be fair to assume that the relevant methods in jQuery (such as remove()) would function in the exact same way (considering remove() was written using removeChild() for example).

However, this isn't true; the jQuery library actually has an internal method (which is undocumented and in theory could be changed at any time) called cleanData() (here is what this method looks like) which automatically cleans up all the data/events associated with an element upon removal from the DOM (be this via. remove(), empty(), html("") etc).


Older browsers

Older browsers - specifically older versions of IE - are known to have memory leak issues due to event listeners keeping hold of references to the elements they were attached to.

If you want a more in-depth explanation of the causes, patterns and solutions used to fix legacy IE version memory leaks, I fully recommend you read this MSDN article on Understanding and Solving Internet Explorer Leak Patterns.

A few more articles relevant to this:

Manually removing the listeners yourself would probably be a good habit to get into in this case (only if the memory is that vital to your application and you are actually targeting such browsers).

Adding event listeners to dynamically added elements using jQuery

Using .on() you can define your function once, and it will execute for any dynamically added elements.

for example

$('#staticDiv').on('click', 'yourSelector', function() {
  //do something
});

Key Listeners in python?

keyboard

Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.

Global event hook on all keyboards (captures keys regardless of focus). Listen and sends keyboard events. Works with Windows and Linux (requires sudo), with experimental OS X support (thanks @glitchassassin!). Pure Python, no C modules to be compiled. Zero dependencies. Trivial to install and deploy, just copy the files. Python 2 and 3. Complex hotkey support (e.g. Ctrl+Shift+M, Ctrl+Space) with controllable timeout. Includes high level API (e.g. record and play, add_abbreviation). Maps keys as they actually are in your layout, with full internationalization support (e.g. Ctrl+ç). Events automatically captured in separate thread, doesn't block main program. Tested and documented. Doesn't break accented dead keys (I'm looking at you, pyHook). Mouse support available via project mouse (pip install mouse).

From README.md:

import keyboard

keyboard.press_and_release('shift+s, space')

keyboard.write('The quick brown fox jumps over the lazy dog.')

# Press PAGE UP then PAGE DOWN to type "foobar".
keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar'))

# Blocks until you press esc.
keyboard.wait('esc')

# Record events until 'esc' is pressed.
recorded = keyboard.record(until='esc')
# Then replay back at three times the speed.
keyboard.play(recorded, speed_factor=3)

# Type @@ then press space to replace with abbreviation.
keyboard.add_abbreviation('@@', '[email protected]')
# Block forever.
keyboard.wait()

adding multiple event listeners to one element

You can just define a function and pass it. Anonymous functions are not special in any way, all functions can be passed around as values.

var elem = document.getElementById('first');

elem.addEventListener('touchstart', handler, false);
elem.addEventListener('click', handler, false);

function handler(event) {
    do_something();
}

This Handler class should be static or leaks might occur: IncomingHandler

I'm confused. The example I found avoids the static property entirely and uses the UI thread:

    public class example extends Activity {
        final int HANDLE_FIX_SCREEN = 1000;
        public Handler DBthreadHandler = new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                int imsg;
                imsg = msg.what;
                if (imsg == HANDLE_FIX_SCREEN) {
                    doSomething();
                }
            }
        };
    }

The thing I like about this solution is there is no problem trying to mix class and method variables.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

Please make sure that your applicationContext.xml file is loaded by specifying it in your web.xml file:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

Requested bean is currently in creation: Is there an unresolvable circular reference?

I think you could use Spring's

@Lazy

annotation on one of the autowired fields to break circular dependency.

I'm not sure if this works/exists in mentioned Spring version.

possible EventEmitter memory leak detected

By default, a maximum of 10 listeners can be registered for any single event.

If it's your code, you can specify maxListeners via:

const emitter = new EventEmitter()
emitter.setMaxListeners(100)
// or 0 to turn off the limit
emitter.setMaxListeners(0)

But if it's not your code you can use the trick to increase the default limit globally:

require('events').EventEmitter.prototype._maxListeners = 100;

Of course you can turn off the limits but be careful:

// turn off limits by default (BE CAREFUL)
require('events').EventEmitter.prototype._maxListeners = 0;

BTW. The code should be at the very beginning of the app.

ADD: Since node 0.11 this code also works to change the default limit:

require('events').EventEmitter.defaultMaxListeners = 0

How to remove all listeners in an element?

If you’re not opposed to jquery, this can be done in one line:

jQuery 1.7+

$("#myEl").off()

jQuery < 1.7

$('#myEl').replaceWith($('#myEl').clone());

Here’s an example:

http://jsfiddle.net/LkfLezgd/3/

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I faced exactly the same issue in a Spring web app. In fact, I had removed spring-security by commenting the config annotation:

// @ImportResource({"/WEB-INF/spring-security.xml"})

but I had forgotten to remove the corresponding filters in web.xml:

<!-- Filters --> 
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Commenting filters solved the issue.

Get event listeners attached to node using addEventListener

Chrome DevTools, Safari Inspector and Firebug support getEventListeners(node).

getEventListeners(document)

Eclipse hangs on loading workbench

I solved deleting *.snap from the workspace dir (and all subdirectories):

metadata\.plugins\*.snap

Binding multiple events to a listener (without JQuery)?

One way how to do it:

_x000D_
_x000D_
const troll = document.getElementById('troll');_x000D_
_x000D_
['mousedown', 'mouseup'].forEach(type => {_x000D_
 if (type === 'mousedown') {_x000D_
  troll.addEventListener(type, () => console.log('Mouse is down'));_x000D_
 }_x000D_
        else if (type === 'mouseup') {_x000D_
                troll.addEventListener(type, () => console.log('Mouse is up'));_x000D_
        }_x000D_
});
_x000D_
img {_x000D_
  width: 100px;_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<div id="troll">_x000D_
  <img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">_x000D_
</div>
_x000D_
_x000D_
_x000D_

onNewIntent() lifecycle and registered listeners

onNewIntent() is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate(). From activities lifecycle point of view it's therefore needed to call onPause() before onNewIntent(). I suggest you to rewrite your activity to not use these listeners inside of onNewIntent(). For example most of the time my onNewIntent() methods simply looks like this:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // getIntent() should always return the most recent
    setIntent(intent);
}

With all setup logic happening in onResume() by utilizing getIntent().

node.js - request - How to "emitter.setMaxListeners()"?

I use the code to increase the default limit globally: require('events').EventEmitter.prototype._maxListeners = 100;

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

Enable Mixed authentication mode while installing MSSQL server. Also provide password for sa user.

Explain ExtJS 4 event handling

Let's start by describing DOM elements' event handling.

DOM node event handling

First of all you wouldn't want to work with DOM node directly. Instead you probably would want to utilize Ext.Element interface. For the purpose of assigning event handlers, Element.addListener and Element.on (these are equivalent) were created. So, for example, if we have html:

<div id="test_node"></div>

and we want add click event handler.
Let's retrieve Element:

var el = Ext.get('test_node');

Now let's check docs for click event. It's handler may have three parameters:

click( Ext.EventObject e, HTMLElement t, Object eOpts )

Knowing all this stuff we can assign handler:

//       event name      event handler
el.on(    'click'        , function(e, t, eOpts){
  // handling event here
});

Widgets event handling

Widgets event handling is pretty much similar to DOM nodes event handling.

First of all, widgets event handling is realized by utilizing Ext.util.Observable mixin. In order to handle events properly your widget must containg Ext.util.Observable as a mixin. All built-in widgets (like Panel, Form, Tree, Grid, ...) has Ext.util.Observable as a mixin by default.

For widgets there are two ways of assigning handlers. The first one - is to use on method (or addListener). Let's for example create Button widget and assign click event to it. First of all you should check event's docs for handler's arguments:

click( Ext.button.Button this, Event e, Object eOpts )

Now let's use on:

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button'
});
myButton.on('click', function(btn, e, eOpts) {
  // event handling here
  console.log(btn, e, eOpts);
});

The second way is to use widget's listeners config:

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button',
  listeners : {
    click: function(btn, e, eOpts) {
      // event handling here
      console.log(btn, e, eOpts);
    }
  }
});

Notice that Button widget is a special kind of widgets. Click event can be assigned to this widget by using handler config:

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button',
  handler : function(btn, e, eOpts) {
    // event handling here
    console.log(btn, e, eOpts);
  }
});

Custom events firing

First of all you need to register an event using addEvents method:

myButton.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);

Using the addEvents method is optional. As comments to this method say there is no need to use this method but it provides place for events documentation.

To fire your event use fireEvent method:

myButton.fireEvent('myspecialevent1', arg1, arg2, arg3, /* ... */);

arg1, arg2, arg3, /* ... */ will be passed into handler. Now we can handle your event:

myButton.on('myspecialevent1', function(arg1, arg2, arg3, /* ... */) {
  // event handling here
  console.log(arg1, arg2, arg3, /* ... */);
});

It's worth mentioning that the best place for inserting addEvents method call is widget's initComponent method when you are defining new widget:

Ext.define('MyCustomButton', {
  extend: 'Ext.button.Button',
  // ... other configs,
  initComponent: function(){
    this.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
    // ...
    this.callParent(arguments);
  }
});
var myButton = Ext.create('MyCustomButton', { /* configs */ });

Preventing event bubbling

To prevent bubbling you can return false or use Ext.EventObject.preventDefault(). In order to prevent browser's default action use Ext.EventObject.stopPropagation().

For example let's assign click event handler to our button. And if not left button was clicked prevent default browser action:

myButton.on('click', function(btn, e){
  if (e.button !== 0)
    e.preventDefault();
});

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

I had a similar problem when running a spring web application in an Eclipse managed tomcat. I solved this problem by adding maven dependencies in the project's web deployment assembly.

  1. Open the project's properties (e.g., right-click on the project's name in the project explorer and select "Properties").
  2. Select "Deployment Assembly".
  3. Click the "Add..." button on the right margin.
  4. Select "Java Build Path Entries" from the menu of Directive Type and click "Next".
  5. Select "Maven Dependencies" from the Java Build Path Entries menu and click "Finish".

You should see "Maven Dependencies" added to the Web Deployment Assembly definition.

How to add action listener that listens to multiple buttons

You are declaring button1 in main method so you can not access it in actionPerform. You should make it global in class.

 JButton button1;
 public static void main(String[] args) {

    JFrame calcFrame = new JFrame();

    calcFrame.setSize(100, 100);
    calcFrame.setVisible(true);

    button1 = new JButton("1");
    button1.addActionListener(this);

    calcFrame.add(button1);
}

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == button1)
}

Using Switch Statement to Handle Button Clicks

Hi its quite simple to make switch between buttons using switch case:-

 package com.example.browsebutton;


    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;

        public class MainActivity extends Activity implements OnClickListener {
        Button b1,b2;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                b1=(Button)findViewById(R.id.button1);

                b2=(Button)findViewById(R.id.button2);
                b1.setOnClickListener(this);
                b2.setOnClickListener(this);
            }



            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                 int id=v.getId();
                 switch(id) {
                    case R.id.button1:
                  Toast.makeText(getBaseContext(), "btn1", Toast.LENGTH_LONG).show();
                //Your Operation

                  break;

                    case R.id.button2:
                          Toast.makeText(getBaseContext(), "btn2", Toast.LENGTH_LONG).show();


                          //Your Operation
                          break;
            }

        }}

Could not resolve Spring property placeholder

You may have more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer in your application. Try setting a breakpoint on the setLocations method of the superclass and see if it's called more than once at application startup. If there is more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer, you might need to look at configuring the ignoreUnresolvablePlaceholders property so that your application will start up cleanly.

android listview get selected item

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

How to turn on WCF tracing?

The following configuration taken from MSDN can be applied to enable tracing on your WCF service.

<configuration>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true" >
        <listeners>
             <add name="xml"/>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
            <add name="xml"/>
        </listeners>
      </source>
      <source name="myUserTraceSource"
              switchValue="Information, ActivityTracing">
        <listeners>
            <add name="xml"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
        <add name="xml"
             type="System.Diagnostics.XmlWriterTraceListener"
             initializeData="Error.svclog" />
    </sharedListeners>
  </system.diagnostics>
</configuration>

To view the log file, you can use "C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcTraceViewer.exe".

If "SvcTraceViewer.exe" is not on your system, you can download it from the "Microsoft Windows SDK for Windows 7 and .NET Framework 4" package here:

Windows SDK Download

You don't have to install the entire thing, just the ".NET Development / Tools" part.

When/if it bombs out during installation with a non-sensical error, Petopas' answer to Windows 7 SDK Installation Failure solved my issue.

Write string to output stream

OutputStream writes bytes, String provides chars. You need to define Charset to encode string to byte[]:

outputStream.write(string.getBytes(Charset.forName("UTF-8")));

Change UTF-8 to a charset of your choice.

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

You have included the dependency for sflj's api, but not the dependency for the implementation of the api, that is a separate jar, you could try slf4j-simple-1.6.1.jar.

JUnit tests pass in Eclipse but fail in Maven Surefire

I had a similar problem: JUnit tests failed in Maven Surefire but passed in Eclipse when I used JUnit library version 4.11.0 from SpringSource Bundle Repository. Particulary:

<dependency>
    <groupId>org.junit</groupId>
    <artifactId>com.springsource.org.junit</artifactId>
    <version>4.11.0</version>
</dependency>

Then I replaced it with following JUnit library version 4.11 and everything works fine.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
</dependency>

How to click or tap on a TextView text

This may not be quite what you are looking for but this is what worked for what I'm doing. All of this is after my onCreate:

boilingpointK = (TextView) findViewById(R.id.boilingpointK);

boilingpointK.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if ("Boiling Point K".equals(boilingpointK.getText().toString()))
            boilingpointK.setText("2792");
        else if ("2792".equals(boilingpointK.getText().toString()))
            boilingpointK.setText("Boiling Point K");
    }
});

Android: How can I validate EditText input?

I have created this library for android where you can validate a material design EditText inside and EditTextLayout easily like this:

    compile 'com.github.TeleClinic:SmartEditText:0.1.0'

then you can use it like this:

<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
    android:id="@+id/passwordSmartEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:setLabel="Password"
    app:setMandatoryErrorMsg="Mandatory field"
    app:setPasswordField="true"
    app:setRegexErrorMsg="Weak password"
    app:setRegexType="MEDIUM_PASSWORD_VALIDATION" />

<com.teleclinic.kabdo.smartmaterialedittext.CustomViews.SmartEditText
    android:id="@+id/ageSmartEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:setLabel="Age"
    app:setMandatoryErrorMsg="Mandatory field"
    app:setRegexErrorMsg="Is that really your age :D?"
    app:setRegexString=".*\\d.*" />

Then you can check if it is valid like this:

    ageSmartEditText.check()

For more examples and customization check the repository https://github.com/TeleClinic/SmartEditText

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/jsp-api-6.0.16.jar
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/servlet-api-6.0.16.jar

You should not have any server-specific libraries in the /WEB-INF/lib. Leave them in the appserver's own library. It would only lead to collisions in the classpath. Get rid of all appserver-specific libraries in /WEB-INF/lib (and also in JRE/lib and JRE/lib/ext if you have placed any of them there).

A common cause that the appserver-specific libraries are included in the webapp's library is that starters think that it is the right way to fix compilation errors of among others the javax.servlet classes not being resolveable. Putting them in webapp's library is the wrong solution. You should reference them in the classpath during compilation, i.e. javac -cp /path/to/server/lib/servlet.jar and so on, or if you're using an IDE, you should integrate the server in the IDE and associate the web project with the server. The IDE will then automatically take server-specific libraries in the classpath (buildpath) of the webapp project.

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

You have an incompatibility between the version of ASM required by Hibernate (asm-1.5.3.jar) and the one required by Spring. But, actually, I wonder why you have asm-2.2.3.jar on your classpath (ASM is bundled in spring.jar and spring-core.jar to avoid such problems AFAIK). See HHH-2222.

How to mock void methods with Mockito

I think I've found a simpler answer to that question, to call the real method for just one method (even if it has a void return) you can do this:

Mockito.doCallRealMethod().when(<objectInstance>).<method>();
<objectInstance>.<method>();

Or, you could call the real method for all methods of that class, doing this:

<Object> <objectInstance> = mock(<Object>.class, Mockito.CALLS_REAL_METHODS);

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class

Just leaving this here for future visitors:

In my case the /WEB-INF/classes directory was missing. If you are using Eclipse, make sure the .settings/org.eclipse.wst.common.component is correct (Deployment Assembly in the project settings).

In my case it was missing

    <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
    <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/test/resources"/>

This file is also a common source of errors as mentioned by Anuj (missing dependencies of other projects).

Otherwise, hopefully the other answers (or the "Problems" tab) will help you.

Android: How to detect double-tap?

Thread + Interface = DoubleTapListener, AnyTap listener etc

In this example, I have implemented the DoubleTap Listener with a Thread. You can add my listener with any View object as you do with any ClickListener. Using this approach you can easily pull off any kind of click listener.

yourButton.setOnClickListener(new DoubleTapListener(this));

1) My Listrener class

public class DoubleTapListener  implements View.OnClickListener{

   private boolean isRunning= false;
   private int resetInTime =500;
   private int counter=0;
   private DoubleTapCallback listener;

   public DoubleTapListener(Context context){
       listener = (DoubleTapCallback)context;
       Log.d("Double Tap","New");
   }

   @Override
   public void onClick(View v) {

       if(isRunning){
          if(counter==1)
              listener.onDoubleClick(v);
       }

       counter++;

       if(!isRunning){
          isRunning=true;
          new Thread(new Runnable() {
             @Override
             public void run() {
                 try {
                    Thread.sleep(resetInTime);
                    isRunning = false;
                    counter=0;
                 } catch (InterruptedException e) {
                    e.printStackTrace();
                 }
             }
           }).start();
       }
   }
}

2) Listener Callback

public interface DoubleTapCallback {

      public void onDoubleClick(View v);

}

3) Implement in your Activity

public class MainActivity extends AppCompatActivity implements DoubleTapCallback{

private Button button;
private int counter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button   = (Button)findViewById(R.id.button);      
    button.setOnClickListener(new DoubleTapListener(this));  // Set mt listener

}

@Override
public void onDoubleClick(View v) {
    counter++;
    textView.setText(counter+""); 
}

Relevant link:

You can see the full working code HERE

Scrollview vertical and horizontal in android

Option #1: You can come up with a new UI design that does not require simultaneous horizontal and vertical scrolling.

Option #2: You can obtain the source code to ScrollView and HorizontalScrollView, learn how the core Android team implemented those, and create your own BiDirectionalScrollView implementation.

Option #3: You can get rid of the dependencies that are requiring you to use the widget system and draw straight to the Canvas.

Option #4: If you stumble upon an open source application that seems to implement what you seek, look to see how they did it.

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Douglas Crockford, the author of jslint has written (and spoken) about this issue many times. There's a section on this page of his website which covers this:

for Statement

A for class of statements should have the following form:

for (initialization; condition; update) {
    statements
}

for (variable in object) {
    if (filter) {
        statements
    } 
}

The first form should be used with arrays and with loops of a predeterminable number of iterations.

The second form should be used with objects. Be aware that members that are added to the prototype of the object will be included in the enumeration. It is wise to program defensively by using the hasOwnProperty method to distinguish the true members of the object:

for (variable in object) {
    if (object.hasOwnProperty(variable)) {
        statements
    } 
}

Crockford also has a video series on YUI theater where he talks about this. Crockford's series of videos/talks about javascript are a must see if you're even slightly serious about javascript.

JavaScript closure inside loops – simple practical example

Another way of saying it is that the i in your function is bound at the time of executing the function, not the time of creating the function.

When you create the closure, i is a reference to the variable defined in the outside scope, not a copy of it as it was when you created the closure. It will be evaluated at the time of execution.

Most of the other answers provide ways to work around by creating another variable that won't change the value for you.

Just thought I'd add an explanation for clarity. For a solution, personally, I'd go with Harto's since it is the most self-explanatory way of doing it from the answers here. Any of the code posted will work, but I'd opt for a closure factory over having to write a pile of comments to explain why I'm declaring a new variable(Freddy and 1800's) or have weird embedded closure syntax(apphacker).

Is it possible to append to innerHTML without destroying descendants' event listeners?

Yes it is possible if you bind events using tag attribute onclick="sayHi()" directly in template similar like your <body onload="start()"> - this approach similar to frameworks angular/vue/react/etc. You can also use <template> to operate on 'dynamic' html like here. It is not strict unobtrusive js however it is acceptable for small projects

_x000D_
_x000D_
function start() {_x000D_
  mydiv.innerHTML += "bar";_x000D_
}_x000D_
_x000D_
function sayHi() {_x000D_
  alert("hi");_x000D_
}
_x000D_
<body onload="start()">_x000D_
  <div id="mydiv" style="border: solid red 2px">_x000D_
    <span id="myspan" onclick="sayHi()">foo</span>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Logging best practices

As far as aspect oriented logging is concerned I was recommended PostSharp on another SO question -

Aspect Oriented Logging with Unity\T4\anything else

The link provided in the answer is worth visiting if you are evaluating logging frameworks.

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

It is possible to list all event listeners in JavaScript: It's not that hard; you just have to hack the prototype's method of the HTML elements (before adding the listeners).

function reportIn(e){
    var a = this.lastListenerInfo[this.lastListenerInfo.length-1];
    console.log(a)
}


HTMLAnchorElement.prototype.realAddEventListener = HTMLAnchorElement.prototype.addEventListener;

HTMLAnchorElement.prototype.addEventListener = function(a,b,c){
    this.realAddEventListener(a,reportIn,c); 
    this.realAddEventListener(a,b,c); 
    if(!this.lastListenerInfo){  this.lastListenerInfo = new Array()};
    this.lastListenerInfo.push({a : a, b : b , c : c});
};

Now every anchor element (a) will have a lastListenerInfo property wich contains all of its listeners. And it even works for removing listeners with anonymous functions.

How do you add an ActionListener onto a JButton in Java

Two ways:

1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.

2. Use anonymous inner classes:

jBtnSelection.addActionListener(new ActionListener() { 
  public void actionPerformed(ActionEvent e) { 
    selectionButtonPressed();
  } 
} );

Later, you'll have to define selectionButtonPressed(). This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.

The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).

In JavaScript can I make a "click" event fire programmatically for a file input element?

Hey this solution works. for download we should be using MSBLOB

$scope.getSingleInvoicePDF = function(invoiceNumberEntity) {
   var fileName = invoiceNumberEntity + ".pdf";
   var pdfDownload = document.createElement("a");
   document.body.appendChild(pdfDownload);

   AngularWebService.getFileWithSuffix("ezbillpdfget",invoiceNumberEntity,"pdf" ).then(function(returnedJSON) {
       var fileBlob = new Blob([returnedJSON.data], {type: 'application/pdf'});
       if (navigator.appVersion.toString().indexOf('.NET') > 0) { // for IE browser
           window.navigator.msSaveBlob(fileBlob, fileName);
       } else { // for other browsers
           var fileURL = window.URL.createObjectURL(fileBlob);
           pdfDownload.href = fileURL;
           pdfDownload.download = fileName;
           pdfDownload.click();      
       }
   });
};

For AngularJS or even for normal javascript.

How can I add (simple) tracing in C#?

I followed around five different answers as well as all the blog posts in the previous answers and still had problems. I was trying to add a listener to some existing code that was tracing using the TraceSource.TraceEvent(TraceEventType, Int32, String) method where the TraceSource object was initialised with a string making it a 'named source'.

For me the issue was not creating a valid combination of source and switch elements to target this source. Here is an example that will log to a file called tracelog.txt. For the following code:

TraceSource source = new TraceSource("sourceName");
source.TraceEvent(TraceEventType.Verbose, 1, "Trace message");

I successfully managed to log with the following diagnostics configuration:

<system.diagnostics>
    <sources>
        <source name="sourceName" switchName="switchName">
            <listeners>
                <add
                    name="textWriterTraceListener"
                    type="System.Diagnostics.TextWriterTraceListener"
                    initializeData="tracelog.txt" />
            </listeners>
        </source>
    </sources>

    <switches>
        <add name="switchName" value="Verbose" />
    </switches>
</system.diagnostics>

How can I split a text file using PowerShell?

There's also this quick (and somewhat dirty) one-liner:

$linecount=0; $i=0; Get-Content .\BIG_LOG_FILE.txt | %{ Add-Content OUT$i.log "$_"; $linecount++; if ($linecount -eq 3000) {$I++; $linecount=0 } }

You can tweak the number of first lines per batch by changing the hard-coded 3000 value.

Difference between SelectedItem, SelectedValue and SelectedValuePath

inspired by this question I have written a blog along with the code snippet here. Below are some of the excerpts from the blog

SelectedItem – Selected Item helps to bind the actual value from the DataSource which will be displayed. This is of type object and we can bind any type derived from object type with this property. Since we will be using the MVVM binding for our combo boxes in that case this is the property which we can use to notify VM that item has been selected.

SelectedValue and SelectedValuePath – These are the two most confusing and misinterpreted properties for combobox. But these properties come to rescue when we want to bind our combobox with the value from already created object. Please check my last scenario in the following list to get a brief idea about the properties.

Object cannot be cast from DBNull to other types

I'm thinking that your output parameter is coming back with a DBNull value. Add a check for that like this

var outputParam = dataAccCom.GetParameterValue(IDbCmd, "op_Id");
if(!(outputParam is DBNull))
     DataTO.Id = Convert.ToInt64(outputParam);

How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

If AJAX isn't an option you can use nested data structures to simplify.

<?php
$var = array(
    'qwe' => 'asd',
    'asd' => array(
        1 => 2,
        3 => 4,
    ),
    'zxc' => 0,
);
?>
<script>var data = <?php echo json_encode($var); ?>;</script>

Why Git is not allowing me to commit even after configuration?

That’s a typo. You’ve accidently set user.mail with no e. Fix it by setting user.email in the global configuration with

git config --global user.email "[email protected]"

Is it better to use "is" or "==" for number comparison in Python?

Use ==.

Sometimes, on some python implementations, by coincidence, integers from -5 to 256 will work with is (in CPython implementations for instance). But don't rely on this or use it in real programs.

Escape double quotes in Java

Escaping the double quotes with backslashes is the only way to do this in Java.

Some IDEs around such as IntelliJ IDEA do this escaping automatically when pasting such a String into a String literal (i.e. between the double quotes surrounding a java String literal)

One other option would be to put the String into some kind of text file that you would then read at runtime

AngularJS multiple filter with custom filter function

In view file (HTML or EJS)

<div ng-repeat="item in vm.itemList  | filter: myFilter > </div>

and In Controller

$scope.myFilter = function(item) {
return (item.propertyA === 'value' || item.propertyA === 'value');
}

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

After like three (3) hours of google..ing.This is the solution to the problem: First, I run this command;

$mysqladmin -u root -p[your root password here] version Which outputs:

    Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.

    Server version      5.5.49-0ubuntu0.14.04.1
    Protocol version    10
    Connection      Localhost via UNIX socket
    UNIX socket     /var/run/mysqld/mysqld.sock
    Uptime:         1 hour 54 min 3 sec

Finally, I changed the connect_type parameter from tcp to socket and added the parameter socket in config.inc.php:

    $cfg['Servers'][$i]['host'] = 'localhost';
    $cfg['Servers'][$i]['connect_type'] = 'socket';
    $cfg['Servers'][$i]['socket'] = '/var/run/mysqld/mysqld.sock';

All credit goes to this person: This is the correct solution

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

In ConcurrentHashMap, the lock is applied to a segment instead of an entire Map. Each segment manages its own internal hash table. The lock is applied only for update operations. Collections.synchronizedMap(Map) synchronizes the entire map.

How to run server written in js with Node.js

Just go on that directory of your JS file from cmd and write node jsFile.js or even node jsFile; both will work fine.

Alter column, add default constraint

I use the stored procedure below to update the defaults on a column.

It automatically removes any prior defaults on the column, before adding the new default.

Examples of usage:

-- Update default to be a date.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','getdate()';
-- Update default to be a number.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
-- Update default to be a string. Note extra quotes, as this is not a function.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';

Stored procedure:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Sample function calls:
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','ColumnName','getdate()';
--exec [dbol].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';
create PROCEDURE [dbo].[ColumnDefaultUpdate]
    (
        -- Table name, including schema, e.g. '[dbo].[TableName]'
        @TABLE_NAME VARCHAR(100), 
        -- Column name, e.g. 'ColumnName'.
        @COLUMN_NAME VARCHAR(100),
        -- New default, e.g. '''MyDefault''' or 'getdate()'
        -- Note that if you want to set it to a string constant, the contents
        -- must be surrounded by extra quotes, e.g. '''MyConstant''' not 'MyConstant'
        @NEW_DEFAULT VARCHAR(100)
    )
AS 
BEGIN       
    -- Trim angle brackets so things work even if they are included.
    set @COLUMN_NAME = REPLACE(@COLUMN_NAME, '[', '')
    set @COLUMN_NAME = REPLACE(@COLUMN_NAME, ']', '')

    print 'Table name: ' + @TABLE_NAME;
    print 'Column name: ' + @COLUMN_NAME;
    DECLARE @ObjectName NVARCHAR(100)
    SELECT @ObjectName = OBJECT_NAME([default_object_id]) FROM SYS.COLUMNS
    WHERE [object_id] = OBJECT_ID(@TABLE_NAME) AND [name] = @COLUMN_NAME;

    IF @ObjectName <> '' 
    begin
        print 'Removed default: ' + @ObjectName;
        --print('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
        EXEC('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
    end

    EXEC('ALTER TABLE ' + @TABLE_NAME + ' ADD  DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
    --print('ALTER TABLE ' + @TABLE_NAME + ' ADD  DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
    print 'Added default of: ' + @NEW_DEFAULT;
END

Errors this stored procedure eliminates

If you attempt to add a default to a column when one already exists, you will get the following error (something you will never see if using this stored proc):

-- Using the stored procedure eliminates this error:
Msg 1781, Level 16, State 1, Line 1
Column already has a DEFAULT bound to it.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.

How do you wait for input on the same Console.WriteLine() line?

Use Console.Write instead, so there's no newline written:

Console.Write("What is your name? ");
var name = Console.ReadLine();

Default keystore file does not exist?

Use This for MAC users

keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

How to enable core dump in my Linux C++ program

By default many profiles are defaulted to 0 core file size because the average user doesn't know what to do with them.

Try ulimit -c unlimited before running your program.

Excel VBA Check if directory exists error

If Len(Dir(ThisWorkbook.Path & "\YOUR_DIRECTORY", vbDirectory)) = 0 Then
   MkDir ThisWorkbook.Path & "\YOUR_DIRECTORY"
End If

Best practice to run Linux service as a different user

On Debian we use the start-stop-daemon utility, which handles pid-files, changing the user, putting the daemon into background and much more.

I'm not familiar with RedHat, but the daemon utility that you are already using (which is defined in /etc/init.d/functions, btw.) is mentioned everywhere as the equivalent to start-stop-daemon, so either it can also change the uid of your program, or the way you do it is already the correct one.

If you look around the net, there are several ready-made wrappers that you can use. Some may even be already packaged in RedHat. Have a look at daemonize, for example.

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

Dynamic instantiation from string name of a class in dynamically imported module?

One can simply use the pydoc.locate function.

from pydoc import locate
my_class = locate("module.submodule.myclass")
instance = my_class()

Android setOnClickListener method - How does it work?

It works like this. View.OnClickListenere is defined -

public interface OnClickListener {
    void onClick(View v);
}

As far as we know you cannot instantiate an object OnClickListener, as it doesn't have a method implemented. So there are two ways you can go by - you can implement this interface which will override onClick method like this:

public class MyListener implements View.OnClickListener {
    @Override
    public void onClick (View v) {
         // your code here;
    }
}

But it's tedious to do it each time as you want to set a click listener. So in order to avoid this you can provide the implementation for the method on spot, just like in an example you gave.

setOnClickListener takes View.OnClickListener as its parameter.

What is the difference between HAVING and WHERE in SQL?

When GROUP BY is not used, the WHERE and HAVING clauses are essentially equivalent.

However, when GROUP BY is used:

  • The WHERE clause is used to filter records from a result. The filtering occurs before any groupings are made.
  • The HAVING clause is used to filter values from a group (i.e., to check conditions after aggregation into groups has been performed).

Resource from Here

How to store Query Result in variable using mysql

Select count(*) from table_name into @var1; 
Select @var1;

jquery - How to determine if a div changes its height or any css attribute?

Please don't use techniques described in other answers here. They are either not working with css3 animations size changes, floating layout changes or changes that don't come from jQuery land. You can use a resize-detector, a event-based approach, that doesn't waste your CPU time.

https://github.com/marcj/css-element-queries

It contains a ResizeSensor class you can use for that purpose.

new ResizeSensor(jQuery('#mainContent'), function(){ 
    console.log('main content dimension changed');
});

Disclaimer: I wrote this library

Bootstrap 4 card-deck with number of columns based on viewport

Updated 2018

If you want a responsive card-deck, use the visibility utils to force a wrap every X columns on different viewport width(breakpoints)...

Bootstrap 4 responsive card-deck (v 4.1)


Original answer for Bootstrap 4 alpha 2:

You can use the grid col-*-* to get the different widths (instead of card-deck) and then set equal height to the cols using flexbox.

.row > div[class*='col-'] {
  display: flex;
  flex:1 0 auto;
}

http://codeply.com/go/O0KdSG2YX2 (alpha 2)

The problem is that w/o flexbox enabled the card-deck uses table-cell where it becomes very hard to control the width. As of Bootstrap 4 Alpha 6, flexbox is default so the additional CSS is not required for flexbox, and the h-100 class can be used to make the cards full height: http://www.codeply.com/go/gnOzxd4Spk


Related question: Bootstrap 4 - Responsive cards in card-columns

How to get name of calling function/method in PHP?

You can also use the info provided by a php exception, it's an elegant solution:


function GetCallingMethodName(){
    $e = new Exception();
    $trace = $e->getTrace();
    //position 0 would be the line that called this function so we ignore it
    $last_call = $trace[1];
    print_r($last_call);
}

function firstCall($a, $b){
    theCall($a, $b);
}

function theCall($a, $b){
    GetCallingMethodName();
}

firstCall('lucia', 'php');

And you get this... (voilà!)

Array
(
    [file] => /home/lufigueroa/Desktop/test.php
    [line] => 12
    [function] => theCall
    [args] => Array
        (
            [0] => lucia
            [1] => php
        )

)

How to find the .NET framework version of a Visual Studio project?

It's as easy as in your Visual studio.

  1. go to the 4th menu option on top, 'website'.
  2. under websites go to option, 'start options'.
  3. under start options, go to 'build' option.
  4. change the target framework there to what so ever framework.

jquery datatables hide column

Hope this will help you. I am using this solution for Search on some columns but i don't want to display them on frontend.

$(document).ready(function() {
        $('#example').dataTable({
            "scrollY": "500px",
            "scrollCollapse": true,
            "scrollX": false,
            "bPaginate": false,
            "columnDefs": [
                { 
                    "width": "30px", 
                    "targets": 0,
                },
                { 
                    "width": "100px", 
                    "targets": 1,
                },
                { 
                    "width": "100px", 
                    "targets": 2,
                },              
                { 
                    "width": "76px",
                    "targets": 5, 
                },
                { 
                    "width": "80px", 
                    "targets": 6,
                },
                {
                    "targets": [ 7 ],
                    "visible": false,
                    "searchable": true
                },
                {
                    "targets": [ 8 ],
                    "visible": false,
                    "searchable": true
                },
                {
                    "targets": [ 9 ],
                    "visible": false,
                    "searchable": true
                },
              ]
        });
    });

How to read and write xml files?

The above answer only deal with DOM parser (that normally reads the entire file in memory and parse it, what for a big file is a problem), you could use a SAX parser that uses less memory and is faster (anyway that depends on your code).

SAX parser callback some functions when it find a start of element, end of element, attribute, text between elements, etc, so it can parse the document and at the same time you get what you need.

Some example code:

http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

Print array to a file

I just wrote this function to output an array as text:

Should output nicely formatted array.

IMPORTANT NOTE:

Beware of user input.

This script was created for internal use.

If you intend to use this for public use you will need to add some additional data validation to prevent script injection.

This is not fool proof and should be used with trusted data only.

The following function will output something like:

$var = array(
  'primarykey' => array(
    'test' => array(
      'var' => array(
        1 => 99,
        2 => 500,
      ),
    ),
    'abc' => 'd',
  ),
);

here is the function (note: function is currently formatted for oop implementation.)

  public function outArray($array, $lvl=0){
    $sub = $lvl+1;
    $return = "";
    if($lvl==null){
      $return = "\t\$var = array(\n";  
    }
      foreach($array as $key => $mixed){
        $key = trim($key);
        if(!is_array($mixed)){
          $mixed = trim($mixed);
        }
        if(empty($key) && empty($mixed)){continue;}
        if(!is_numeric($key) && !empty($key)){
          if($key == "[]"){
            $key = null;
          } else {
            $key = "'".addslashes($key)."'";
          }
        }

        if($mixed === null){
          $mixed = 'null';
        } elseif($mixed === false){
          $mixed = 'false';
        } elseif($mixed === true){
          $mixed = 'true';
        } elseif($mixed === ""){
          $mixed = "''";
        } 

        //CONVERT STRINGS 'true', 'false' and 'null' TO true, false and null
        //uncomment if needed
        //elseif(!is_numeric($mixed) && !is_array($mixed) && !empty($mixed)){
        //  if($mixed != 'false' && $mixed != 'true' && $mixed != 'null'){
        //    $mixed = "'".addslashes($mixed)."'";
        //  }
        //}


        if(is_array($mixed)){
          if($key !== null){
            $return .= "\t".str_repeat("\t", $sub)."$key => array(\n";
            $return .= $this->outArray($mixed, $sub);
            $return .= "\t".str_repeat("\t", $sub)."),\n";
          } else {
            $return .= "\t".str_repeat("\t", $sub)."array(\n";
            $return .= $this->outArray($mixed, $sub);
            $return .= "\t".str_repeat("\t", $sub)."),\n";            
          }
        } else {
          if($key !== null){
            $return .= "\t".str_repeat("\t", $sub)."$key => $mixed,\n";
          } else {
            $return .= "\t".str_repeat("\t", $sub).$mixed.",\n";
          }
        }
    }
    if($lvl==null){
      $return .= "\t);\n";
    }
    return $return;
  }

Alternately you can use this script I also wrote a while ago:

This one is nice to copy and paste parts of an array.

( Would be near impossible to do that with serialized output )

Not the cleanest function but it gets the job done.

This one will output as follows:

$array['key']['key2'] = 'value';
$array['key']['key3'] = 'value2';
$array['x'] = 7;
$array['y']['z'] = 'abc';

Also take care for user input. Here is the code.

public static function prArray($array, $path=false, $top=true) {
    $data = "";
    $delimiter = "~~|~~";
    $p = null;
    if(is_array($array)){
      foreach($array as $key => $a){
        if(!is_array($a) || empty($a)){
          if(is_array($a)){
            $data .= $path."['{$key}'] = array();".$delimiter;
          } else {
            $data .= $path."['{$key}'] = \"".htmlentities(addslashes($a))."\";".$delimiter;
          }
        } else {
          $data .= self::prArray($a, $path."['{$key}']", false);
        }    
      }
    }
    if($top){
      $return = "";
      foreach(explode($delimiter, $data) as $value){
        if(!empty($value)){
          $return .= '$array'.$value."<br>";
        }
      };
      echo $return;
    }
    return $data;
  }

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

In our case, the wrong version of the Sysdeo Tomcat plugin for Eclipse 3.5 was being used. The fix:

  • Use tomcatPluginV33 instead of tomcatPluginV321 (extract to C:\eclipse\dropins)
  • Ensure that DevloaderTomcat7.jar was placed in the tomcat lib folder
  • In Window > Preferences > Tomcat, set the Tomcat version to 7.x

This problem may have been unique to our environment; but, I'll record it here anyway, for posterity's sake.

How to check if a symlink exists

-L is the test for file exists and is also a symbolic link

If you do not want to test for the file being a symbolic link, but just test to see if it exists regardless of type (file, directory, socket etc) then use -e

So if file is really file and not just a symbolic link you can do all these tests and get an exit status whose value indicates the error condition.

if [ ! \( -e "${file}" \) ]
then
     echo "%ERROR: file ${file} does not exist!" >&2
     exit 1
elif [ ! \( -f "${file}" \) ]
then
     echo "%ERROR: ${file} is not a file!" >&2
     exit 2
elif [ ! \( -r "${file}" \) ]
then
     echo "%ERROR: file ${file} is not readable!" >&2
     exit 3
elif [ ! \( -s "${file}" \) ]
then
     echo "%ERROR: file ${file} is empty!" >&2
     exit 4
fi

Why do Sublime Text 3 Themes not affect the sidebar?

Just install package Synced?Sidebar?Bg:it will change the sidebar theme based on current color scheme.But it seems that every time you change the color scheme,sidebar will be changed after you open file Preferences.sublime-settings

Manually map column names with class properties

Note that Dapper object mapping isn't case sensitive, so you can name your properties like this:

public class Person 
{
    public int Person_Id { get; set; }
    public string First_Name { get; set; }
    public string Last_Name { get; set; }
}

Or keep the Person class and use a PersonMap:

  public class PersonMap 
        {
            public int Person_Id { get; set; }
            public string First_Name { get; set; }
            public string Last_Name { get; set; }
            public Person Map(){
              return new Person{
                PersonId = Person_Id,
                FirstName = First_Name,
                LastName = Last_Name
               }               
            }
        }

And then, in the query result:

var person = conn.Query<PersonMap>(sql).Select(x=>x.Map()).ToList();

How can I format the output of a bash command in neat columns

If your output is delimited by tabs a quick solution would be to use the tabs command to adjust the size of your tabs.

tabs 20
keys | awk '{ print $1"\t\t" $2 }'

Clear an input field with Reactjs?

Also after React v 16.8+ you have an ability to use hooks

import React, {useState} from 'react';

const ControlledInputs = () => {
  const [firstName, setFirstName] = useState(false);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (firstName) {
      console.log('firstName :>> ', firstName);
    }
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
          <label htmlFor="firstName">Name: </label>
          <input
            type="text"
            id="firstName"
            name="firstName"
            value={firstName}
            onChange={(e) => setFirstName(e.target.value)}
          />
        <button type="submit">add person</button>
      </form>
    </>
  );
};

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

Answered provided by Tom Saleeba is very helpful. Today I also struggled with the same error

Apr 28, 2015 7:53:27 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I followed the suggestion and added the logging.properties file. And below was my reason of failure:

java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded

The root cause of the issue was a listener (Log4jConfigListener) that I added into the web.xml. And as per the link SEVERE: Exception org.springframework.web.util.Log4jConfigListener , this listener cannot be added within a WAR that is not expanded.

It may be helpful for someone to know that this was happening on OpenShift JBoss gear.

npm install gives error "can't find a package.json file"

Use below command to create a package.json file.

npm init 
npm init --yes or -y flag

[This method will generate a default package.json using information extracted from the current directory.]

Working with package.json

Best way to disable button in Twitter's Bootstrap

For input and button:

$('button').prop('disabled', true);

For anchor:

$('a').attr('disabled', true);

Checked in firefox, chrome.

See http://jsfiddle.net/czL54/2/

How to use a different version of python during NPM install?

You can use --python option to npm like so:

npm install --python=python2.7

or set it to be used always:

npm config set python python2.7

Npm will in turn pass this option to node-gyp when needed.

(note: I'm the one who opened an issue on Github to have this included in the docs, as there were so many questions about it ;-) )

Pass by pointer & Pass by reference

Pass by pointer is the only way you could pass "by reference" in C, so you still see it used quite a bit.

The NULL pointer is a handy convention for saying a parameter is unused or not valid, so use a pointer in that case.

References can't be updated once they're set, so use a pointer if you ever need to reassign it.

Prefer a reference in every case where there isn't a good reason not to. Make it const if you can.

Remove all special characters from a string

This should do what you're looking for:

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

Usage:

echo clean('a|"bc!@£de^&$f g');

Will output: abcdef-g

Edit:

Hey, just a quick question, how can I prevent multiple hyphens from being next to each other? and have them replaced with just 1?

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}

Increase number of axis ticks

Additionally,

ggplot(dat, aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = seq(min(dat$x), max(dat$x), by = 0.05))

Works for binned or discrete scaled x-axis data (I.e., rounding not necessary).

JavaScript alert not working in Android WebView

if you wish to hide URL from the user, Show an AlertDialog as below.

myWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                Log.d(TAG, "onJsAlert url: " + url + "; message: " + message);
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        mContext);
                builder.setMessage(message)
                        .setNeutralButton("OK", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int arg1) {
                                dialog.dismiss();
                            }
                        }).show();
                result.cancel();
                return true;
            }
    }

Concept behind putting wait(),notify() methods in Object class

wait - wait method tells the current thread to give up monitor and go to sleep.

notify - Wakes up a single thread that is waiting on this object's monitor.

So you see wait() and notify() methods work at the monitor level, thread which is currently holding the monitor is asked to give up that monitor through wait() method and through notify method (or notifyAll) threads which are waiting on the object's monitor are notified that threads can wake up.

Important point to note here is that monitor is assigned to an object not to a particular thread. That's one reason why these methods are in Object class. To reiterate threads wait on an Object's monitor (lock) and notify() is also called on an object to wake up a thread waiting on the Object's monitor.

Get record counts for all tables in MySQL database

Based on @Nathan's answer above, but without needing to "remove the final union" and with the option to sort the output, I use the following SQL. It generates another SQL statement which then just run:

select CONCAT( 'select * from (\n', group_concat( single_select SEPARATOR ' UNION\n'), '\n ) Q order by Q.exact_row_count desc') as sql_query
from (
    SELECT CONCAT(
        'SELECT "', 
        table_name, 
        '" AS table_name, COUNT(1) AS exact_row_count
        FROM `', 
        table_schema,
        '`.`',
        table_name, 
        '`'
    ) as single_select
    FROM INFORMATION_SCHEMA.TABLES 
    WHERE table_schema = 'YOUR_SCHEMA_NAME'
      and table_type = 'BASE TABLE'
) Q 

You do need a sufficiently large value of group_concat_max_len server variable but from MariaDb 10.2.4 it should default to 1M.

CMake does not find Visual C++ compiler

If you are on Visual Studio 2017 you need at least CMake 3.8!

Abstract methods in Python

See the abc module. Basically, you define __metaclass__ = abc.ABCMeta on the class, then decorate each abstract method with @abc.abstractmethod. Classes derived from this class cannot then be instantiated unless all abstract methods have been overridden.

If your class is already using a metaclass, derive it from ABCMeta rather than type and you can continue to use your own metaclass.

A cheap alternative (and the best practice before the abc module was introduced) would be to have all your abstract methods just raise an exception (NotImplementedError is a good one) so that classes derived from it would have to override that method to be useful.

However, the abc solution is better because it keeps such classes from being instantiated at all (i.e., it "fails faster"), and also because you can provide a default or base implementation of each method that can be reached using the super() function in derived classes.

How to mount a host directory in a Docker container

boot2docker together with VirtualBox Guest Additions
How to mount /Users into boot2docker

https://medium.com/boot2docker-lightweight-linux-for-docker/boot2docker-together-with-virtualbox-guest-additions-da1e3ab2465c

tl;dr Build your own custom boot2docker.iso with VirtualBox Guest Additions (see link) or download http://static.dockerfiles.io/boot2docker-v1.0.1-virtualbox-guest-additions-v4.3.12.iso and save it to ~/.boot2docker/boot2docker.iso.

Call a global variable inside module

// global.d.ts
declare global {
  namespace NodeJS {
    interface Global {
      bootbox: string // Specify ur type here,use `string` for brief
    }
  }
}

// somewhere else
const bootbox = global.bootbox
// somewhere else
global.bootbox = 'boom'

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="author" content="Sandro Alvares - KingRider">
    </head>
    <body>
        <style type="text/css">
            li.title { 
                font-size: 20px; 
                font-weight: lighter; 
                padding: 15px; 
                counter-increment: ordem; 
            }
            .foo { 
                counter-reset: foo; 
                padding-left: 15px; 
            }
            .foo li { 
                list-style-type: none; 
            }
            .foo li:before { 
                counter-increment: foo; 
                content: counter(ordem) "." counter(foo) " "; 
            }
        </style>
        <ol>
            <li class="title">TITLE ONE</li>
            <ol class="foo">
                <li>text 1 one</li>
                <li>text 1 two</li>
                <li>text 1 three</li>
                <li>text 1 four</li>
            </ol>
            <li class="title">TITLE TWO</li>
            <ol class="foo">
                <li>text 2 one</li>
                <li>text 2 two</li>
                <li>text 2 three</li>
                <li>text 2 four</li>
            </ol>
            <li class="title">TITLE THREE</li>
            <ol class="foo">
                <li>text 3 one</li>
                <li>text 3 two</li>
                <li>text 3 three</li>
                <li>text 3 four</li>
            </ol>
        </ol>
    </body>
</html>

Result: http://i.stack.imgur.com/78bN8.jpg

How can I scale an entire web page with CSS?

This is a rather late answer, but you can use

body {
   transform: scale(1.1);
   transform-origin: 0 0;
   // add prefixed versions too.
}

to zoom the page by 110%. Although the zoom style is there, Firefox still does not support it sadly.

Also, this is slightly different than your zoom. The css transform works like an image zoom, so it will enlarge your page but not cause reflow, etc.


Edit updated the transform origin.

Set folder browser dialog start location

fldrDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)

"If the SelectedPath property is set before showing the dialog box, the folder with this path will be the selected folder, as long as SelectedPath is set to an absolute path that is a subfolder of RootFolder (or more accurately, points to a subfolder of the shell namespace represented by RootFolder)."

MSDN - SelectedPath

"The GetFolderPath method returns the locations associated with this enumeration. The locations of these folders can have different values on different operating systems, the user can change some of the locations, and the locations are localized."

Re: Desktop vs DesktopDirectory

Desktop

"The logical Desktop rather than the physical file system location."

DesktopDirectory:

"The directory used to physically store file objects on the desktop. Do not confuse this directory with the desktop folder itself, which is a virtual folder."

MSDN - Special Folder Enum

MSDN - GetFolderPath

View's SELECT contains a subquery in the FROM clause

Looks to me as MySQL 3.6 gives the following error while MySQL 3.7 no longer errors out. I am yet to find anything in the documentation regarding this fix.

ORDER BY date and time BEFORE GROUP BY name in mysql

As I am not allowed to comment on user1908688's answer, here a hint for MariaDB users:

SELECT *
FROM (
     SELECT *
     ORDER BY date ASC, time ASC
     LIMIT 18446744073709551615
     ) AS sub
GROUP BY sub.name

https://mariadb.com/kb/en/mariadb/why-is-order-by-in-a-from-subquery-ignored/

MongoDB logging all queries

Once profiling level is set using db.setProfilingLevel(2).

The below command will print the last executed query.
You may change the limit(5) as well to see less/more queries.
$nin - will filter out profile and indexes queries
Also, use the query projection {'query':1} for only viewing query field

db.system.profile.find(
{ 
    ns: { 
        $nin : ['meteor.system.profile','meteor.system.indexes']
    }
} 
).limit(5).sort( { ts : -1 } ).pretty()

Logs with only query projection

db.system.profile.find(
{ 
    ns: { 
        $nin : ['meteor.system.profile','meteor.system.indexes']
    }
},
{'query':1}
).limit(5).sort( { ts : -1 } ).pretty()

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

You also could just throw new HttpMessageNotReadableException("error description") to benefit from Spring's default error handling.

However, just as is the case with those default errors, no response body will be set.

I find these useful when rejecting requests that could reasonably only have been handcrafted, potentially indicating a malevolent intent, since they obscure the fact that the request was rejected based on a deeper, custom validation and its criteria.

Hth, dtk

Can I convert long to int?

Convert.ToInt32(myValue);

Though I don't know what it will do when it's greater than int.MaxValue.

Detecting superfluous #includes in C/C++?

To end this discussion: the c++ preprocessor is turing complete. It is a semantic property, whether an include is superfluous. Hence, it follows from Rice's theorem that it is undecidable whether an include is superfluous or not. There CAN'T be a program, that (always correctly) detects whether an include is superfluous.

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

Firefox simply does not show custom onbeforeunload messages. Mozilla say they are protecing end users from malicious sites that might show misleading text.

How can I measure the actual memory usage of an application or process?

Note: this works 100% well only when memory consumption increases

If you want to monitor memory usage by given process (or group of processed sharing common name, e.g. google-chrome, you can use my bash-script:

while true; do ps aux | awk ‚{print $5, $11}’ | grep chrome | sort -n > /tmp/a.txt; sleep 1; diff /tmp/{b,a}.txt; mv /tmp/{a,b}.txt; done;

this will continuously look for changes and print them.

Enter image description here

How to delete the contents of a folder?

Answer for a limited, specific situation: assuming you want to delete the files while maintainig the subfolders tree, you could use a recursive algorithm:

import os

def recursively_remove_files(f):
    if os.path.isfile(f):
        os.unlink(f)
    elif os.path.isdir(f):
        for fi in os.listdir(f):
            recursively_remove_files(os.path.join(f, fi))

recursively_remove_files(my_directory)

Maybe slightly off-topic, but I think many would find it useful

int array to string

at.net 3.5 use:

 String.Join("", new List<int>(array).ConvertAll(i => i.ToString()).ToArray());

at.net 4.0 or above use: (see @Jan Remunda's answer)

 string result = string.Join("", array);

Find oldest/youngest datetime object in a list

Oldest:

oldest = min(datetimes)

Youngest before now:

now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)

"The semaphore timeout period has expired" error for USB connection

This error could also appear if you are having network latency or internet or local network problems. Bridged connections that have a failing counterpart may be the culprit as well.

How can I get the day of a specific date with PHP

You can use the date function. I'm using strtotime to get the timestamp to that day ; there are other solutions, like mktime, for instance.

For instance, with the 'D' modifier, for the textual representation in three letters :

$timestamp = strtotime('2009-10-22');

$day = date('D', $timestamp);
var_dump($day);

You will get :

string 'Thu' (length=3)

And with the 'l' modifier, for the full textual representation :

$day = date('l', $timestamp);
var_dump($day);

You get :

string 'Thursday' (length=8)

Or the 'w' modifier, to get to number of the day (0 to 6, 0 being sunday, and 6 being saturday) :

$day = date('w', $timestamp);
var_dump($day);

You'll obtain :

string '4' (length=1)

jquery ajax function not working

put the event handler function inside $(document).ready(function(){...}). it shall work now

also add preventDefault() to restrict page refreshing

$(document).ready(function() {

            $("#postcontent").submit(function(e) {
                e.preventDefault();
                $.ajax({
                    type : "POST",
                    url : "add_new_post.php",
                    data : $("#postcontent").serialize(),
                    beforeSend : function() {
                          $(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
                    },
                    success : function(response) {
                        alert(response);
                        $("#return_update_msg").html(response);
                        $(".post_submitting").fadeOut(1000);
                    }
                });
                e.preventDefault();
            });

        });

Creating random colour in Java?

Use the random library:

import java.util.Random;

Then create a random generator:

Random rand = new Random();

As colours are separated into red green and blue, you can create a new random colour by creating random primary colours:

// Java 'Color' class takes 3 floats, from 0 to 1.
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();

Then to finally create the colour, pass the primary colours into the constructor:

Color randomColor = new Color(r, g, b);

You can also create different random effects using this method, such as creating random colours with more emphasis on certain colours ... pass in less green and blue to produce a "pinker" random colour.

// Will produce a random colour with more red in it (usually "pink-ish")
float r = rand.nextFloat();
float g = rand.nextFloat() / 2f;
float b = rand.nextFloat() / 2f;

Or to ensure that only "light" colours are generated, you can generate colours that are always > 0.5 of each colour element:

// Will produce only bright / light colours:
float r = rand.nextFloat() / 2f + 0.5;
float g = rand.nextFloat() / 2f + 0.5;
float b = rand.nextFloat() / 2f + 0.5;

There are various other colour functions that can be used with the Color class, such as making the colour brighter:

randomColor.brighter();

An overview of the Color class can be read here: http://download.oracle.com/javase/6/docs/api/java/awt/Color.html

matplotlib colorbar for scatter

From the matplotlib docs on scatter 1:

cmap is only used if c is an array of floats

So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.

How does this work for you?

import matplotlib.pyplot as plt
cm = plt.cm.get_cmap('RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)
plt.colorbar(sc)
plt.show()

Image Example

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

Python Set Comprehension

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

In .NET, which loop runs faster, 'for' or 'foreach'?

Starting from .NET Framework 4 you can also use Parallel.For and Parallel.ForEach like described here: C# Multithreading Loop with Parallel.For or Parallel.ForEach

How to align absolutely positioned element to center?

try this method, working fine for me

position: absolute;
left: 50%;
transform: translateX(-50%); 

Truncate (not round off) decimal numbers in javascript

var a = 5.467;
var truncated = Math.floor(a * 100) / 100; // = 5.46

outline on only one border

Try with Shadow( Like border ) + Border

border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;

Java better way to delete file if exists

file.delete();

if the file doesn't exist, it will return false.

How to change the href for a hyperlink using jQuery

Using

$("a").attr("href", "http://www.google.com/")

will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags:

<a name="MyLinks"></a>
<a href="http://www.codeproject.com/">The CodeProject</a>

...Then you probably don't want to accidentally add href attributes to them. For safety then, we can specify that our selector will only match <a> tags with an existing href attribute:

$("a[href]") //...

Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing href, you might use something like this:

$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')

This will find links where the href exactly matches the string http://www.google.com/. A more involved task might be matching, then updating only part of the href:

$("a[href^='http://stackoverflow.com']")
   .each(function()
   { 
      this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/, 
         "http://stackoverflow.com");
   });

The first part selects only links where the href starts with http://stackoverflow.com. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.

How can I get all the request headers in Django?

request.META.get('HTTP_AUTHORIZATION') /python3.6/site-packages/rest_framework/authentication.py

you can get that from this file though...

How to enable MySQL Query Log?

There is bug in MySQL 5.6 version. Even mysqld show as :

    Default options are read from the following files in the given order:
C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.ini c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.cnf 

Realy settings are reading in following order :

    Default options are read from the following files in the given order:
C:\ProgramData\MySQL\MySQL Server 5.6\my.ini C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.ini c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.cnf

Check file: "C:\ProgramData\MySQL\MySQL Server 5.6\my.ini"

Hope it help somebody.

How to change maven logging level to display only warning and errors?

If you are using Logback, just put this logback-test.xml file into src/test/resources directory:

<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>
<root level="INFO">
    <appender-ref ref="STDOUT" />
</root>
</configuration>

How to add more than one machine to the trusted hosts list using winrm

Same as @Altered-Ego but with txt.file:

Get-Content "C:\ServerList.txt"
machineA,machineB,machineC,machineD


$ServerList = Get-Content "C:\ServerList.txt"
    $currentTrustHost=(get-item WSMan:\localhost\Client\TrustedHosts).value
    if ( ($currentTrustHost).Length -gt "0" ) {
        $currentTrustHost+= ,$ServerList
        set-item WSMan:\localhost\Client\TrustedHosts –value $currentTrustHost -Force -ErrorAction SilentlyContinue
        }
    else {
        $currentTrustHost+= $ServerList
        set-item WSMan:\localhost\Client\TrustedHosts –value $currentTrustHost -Force -ErrorAction SilentlyContinue
    }

The "-ErrorAction SilentlyContinue" is required in old PS version to avoid fake error message:

PS C:\Windows\system32> get-item WSMan:\localhost\Client\TrustedHosts


   WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client

Type            Name                           SourceOfValue   Value
----            ----                           -------------   -----
System.String   TrustedHosts                                   machineA,machineB,machineC,machineD

Moving all files from one directory to another using Python

Please, take a look at implementation of the copytree function which:

  • List directory files with:

    names = os.listdir(src)

  • Copy files with:

for name in names:
  srcname = os.path.join(src, name)
  dstname = os.path.join(dst, name)
  copy2(srcname, dstname)

Getting dstname is not necessary, because if destination parameter specifies a directory, the file will be copied into dst using the base filename from srcname.

Replace copy2 by move.

Xcode - Warning: Implicit declaration of function is invalid in C99

The function has to be declared before it's getting called. This could be done in various ways:

  • Write down the prototype in a header
    Use this if the function shall be callable from several source files. Just write your prototype
    int Fibonacci(int number);
    down in a .h file (e.g. myfunctions.h) and then #include "myfunctions.h" in the C code.

  • Move the function before it's getting called the first time
    This means, write down the function
    int Fibonacci(int number){..}
    before your main() function

  • Explicitly declare the function before it's getting called the first time
    This is the combination of the above flavors: type the prototype of the function in the C file before your main() function

As an additional note: if the function int Fibonacci(int number) shall only be used in the file where it's implemented, it shall be declared static, so that it's only visible in that translation unit.

Best way to strip punctuation from a string

Try that one :)

regex.sub(r'\p{P}','', s)

How disable / remove android activity label and label bar?

You can achieve this by setting the android:theme attribute to @android:style/Theme.NoTitleBar on your <activity> element in your AndroidManifest.xml like this:

<activity android:name=".Activity"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.NoTitleBar">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

SQL "select where not in subquery" returns no results

this worked for me :)

select * from Common

where

common_id not in (select ISNULL(common_id,'dummy-data') from Table1)

and common_id not in (select ISNULL(common_id,'dummy-data') from Table2)

How to loop over a Class attributes in Java?

While I agree with Jörn's answer if your class conforms to the JavaBeabs spec, here is a good alternative if it doesn't and you use Spring.

Spring has a class named ReflectionUtils that offers some very powerful functionality, including doWithFields(class, callback), a visitor-style method that lets you iterate over a classes fields using a callback object like this:

public void analyze(Object obj){
    ReflectionUtils.doWithFields(obj.getClass(), field -> {

        System.out.println("Field name: " + field.getName());
        field.setAccessible(true);
        System.out.println("Field value: "+ field.get(obj));

    });
}

But here's a warning: the class is labeled as "for internal use only", which is a pity if you ask me

Get the value in an input text box

You can simply set the value in text box.

First, you get the value like

var getValue = $('#txt_name').val();

After getting a value set in input like

$('#txt_name').val(getValue);

Extract time from date String

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);

http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

Generate a random point within a circle (uniformly)

I don't know if this question is still open for a new solution with all the answer already given, but I happened to have faced exactly the same question myself. I tried to "reason" with myself for a solution, and I found one. It might be the same thing as some have already suggested here, but anyway here it is:

in order for two elements of the circle's surface to be equal, assuming equal dr's, we must have dtheta1/dtheta2 = r2/r1. Writing expression of the probability for that element as P(r, theta) = P{ r1< r< r1 + dr, theta1< theta< theta + dtheta1} = f(r,theta)*dr*dtheta1, and setting the two probabilities (for r1 and r2) equal, we arrive to (assuming r and theta are independent) f(r1)/r1 = f(r2)/r2 = constant, which gives f(r) = c*r. And the rest, determining the constant c follows from the condition on f(r) being a PDF.

How to read data From *.CSV file using javascript?

You can use PapaParse to help. https://www.papaparse.com/

Here is a CodePen. https://codepen.io/sandro-wiggers/pen/VxrxNJ

Papa.parse(e, {
            header:true,
            before: function(file, inputElem){ console.log('Attempting to Parse...')},
            error: function(err, file, inputElem, reason){ console.log(err); },
            complete: function(results, file){ $.PAYLOAD = results; }
        });

Android Fragment onClick button Method

If you want to use data binding you can follow this solution The following solution might be a better one to follow. the layout is in fragment_my.xml

<data>
    <variable
        name="listener"
        type="my_package.MyListener" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <Button
        android:id="@+id/moreTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="@{() -> listener.onClick()}"
        android:text="@string/login"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
And the Fragment would be as follows
class MyFragment : Fragment(), MyListener {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
            return FragmentMyBinding.inflate(
                inflater,
                container,
                false
            ).apply {
                lifecycleOwner = viewLifecycleOwner
                listener = this@MyFragment
            }.root
    }

    override fun onClick() {
        TODO("Not yet implemented")
    }

}

interface MyListener{
    fun onClick()
}

Check if DataRow exists by column name in c#?

You should try

if (row.Table.Columns.Contains("US_OTHERFRIEND"))

I don't believe that row has a columns property itself.

How to temporarily disable a click handler in jQuery?

This is a more idiomatic alternative to the artificial state variable solutions:

$("#button_id").one('click', DoSomething);

function DoSomething() {
  // do something.

  $("#button_id").one('click', DoSomething);
}

One will only execute once (until attached again). More info here: http://docs.jquery.com/Events/one

How to check whether a string contains a substring in JavaScript?

Another alternative is KMP (Knuth–Morris–Pratt).

The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n·m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.

Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:

// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.

_x000D_
_x000D_
function kmpSearch(pattern, text) {_x000D_
  if (pattern.length == 0)_x000D_
    return 0; // Immediate match_x000D_
_x000D_
  // Compute longest suffix-prefix table_x000D_
  var lsp = [0]; // Base case_x000D_
  for (var i = 1; i < pattern.length; i++) {_x000D_
    var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP_x000D_
    while (j > 0 && pattern.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1];_x000D_
    if (pattern.charAt(i) == pattern.charAt(j))_x000D_
      j++;_x000D_
    lsp.push(j);_x000D_
  }_x000D_
_x000D_
  // Walk through text string_x000D_
  var j = 0; // Number of chars matched in pattern_x000D_
  for (var i = 0; i < text.length; i++) {_x000D_
    while (j > 0 && text.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1]; // Fall back in the pattern_x000D_
    if (text.charAt(i) == pattern.charAt(j)) {_x000D_
      j++; // Next char matched, increment position_x000D_
      if (j == pattern.length)_x000D_
        return i - (j - 1);_x000D_
    }_x000D_
  }_x000D_
  return -1; // Not found_x000D_
}_x000D_
_x000D_
console.log(kmpSearch('ays', 'haystack') != -1) // true_x000D_
console.log(kmpSearch('asdf', 'haystack') != -1) // false
_x000D_
_x000D_
_x000D_

How to dynamically update labels captions in VBA form?

If you want to use this in VBA:

For i = 1 To X
    UserForm1.Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

How to enable Google Play App Signing

This guide is oriented to developers who already have an application in the Play Store. If you are starting with a new app the process it's much easier and you can follow the guidelines of paragraph "New apps" from here

Prerequisites that 99% of developers already have :

  1. Android Studio

  2. JDK 8 and after installation you need to setup an environment variable in your user space to simplify terminal commands. In Windows x64 you need to add this : C:\Program Files\Java\{JDK_VERSION}\bin to the Path environment variable. (If you don't know how to do this you can read my guide to add a folder to the Windows 10 Path environment variable).

Step 0: Open Google Play developer console, then go to Release Management -> App Signing.

enter image description here

Accept the App Signing TOS.

enter image description here

Step 1: Download PEPK Tool clicking the button identical to the image below

enter image description here

Step 2: Open a terminal and type:

java -jar PATH_TO_PEPK --keystore=PATH_TO_KEYSTORE --alias=ALIAS_YOU_USE_TO_SIGN_APK --output=PATH_TO_OUTPUT_FILE --encryptionkey=GOOGLE_ENCRYPTION_KEY

Legend:

  • PATH_TO_PEPK = Path to the pepk.jar you downloaded in Step 1, could be something like C:\Users\YourName\Downloads\pepk.jar for Windows users.
  • PATH_TO_KEYSTORE = Path to keystore which you use to sign your release APK. Could be a file of type *.keystore or *.jks or without extension. Something like C:\Android\mykeystore or C:\Android\mykeystore.keystore etc...
  • ALIAS_YOU_USE_TO_SIGN_APK = The name of the alias you use to sign the release APK.
  • PATH_TO_OUTPUT_FILE = The path of the output file with .pem extension, something like C:\Android\private_key.pem
  • GOOGLE_ENCRYPTION_KEY = This encryption key should be always the same. You can find it in the App Signing page, copy and paste it. Should be in this form: eb10fe8f7c7c9df715022017b00c6471f8ba8170b13049a11e6c09ffe3056a104a3bbe4ac5a955f4ba4fe93fc8cef27558a3eb9d2a529a2092761fb833b656cd48b9de6a

Example:

java -jar "C:\Users\YourName\Downloads\pepk.jar" --keystore="C:\Android\mykeystore" --alias=myalias --output="C:\Android\private_key.pem" --encryptionkey=eb10fe8f7c7c9df715022017b00c6471f8ba8170b13049a11e6c09ffe3056a104a3bbe4ac5a955f4ba4fe93fc8cef27558a3eb9d2a529a2092761fb833b656cd48b9de6a

Press Enter and you will need to provide in order:

  1. The keystore password
  2. The alias password

If everything has gone OK, you now will have a file in PATH_TO_OUTPUT_FILE folder called private_key.pem.

Step 3: Upload the private_key.pem file clicking the button identical to the image below

enter image description here

Step 4: Create a new keystore file using Android Studio.

YOU WILL NEED THIS KEYSTORE IN THE FUTURE TO SIGN THE NEXT RELEASES OF YOUR APP, DON'T FORGET THE PASSWORDS

Open one of your Android projects (choose one at random). Go to Build -> Generate Signed APK and press Create new.

enter image description here

Now you should fill the required fields.

Key store path represent the new keystore you will create, choose a folder and a name using the 3 dots icon on the right, i choosed C:\Android\upload_key.jks (.jks extension will be added automatically)

NOTE: I used upload as the new alias name but if you previously used the same keystore with different aliases to sign different apps, you should choose the same aliases name you had previously in the original keystore.

enter image description here

Press OK when finished, and now you will have a new upload_key.jks keystore. You can close Android Studio now.

Step 5: We need to extract the upload certificate from the newly created upload_key.jks keystore. Open a terminal and type:

keytool -export -rfc -keystore UPLOAD_KEYSTORE_PATH -alias UPLOAD_KEYSTORE_ALIAS -file PATH_TO_OUTPUT_FILE

Legend:

  • UPLOAD_KEYSTORE_PATH = The path of the upload keystore you just created. In this case was C:\Android\upload_key.jks.
  • UPLOAD_KEYSTORE_ALIAS = The new alias associated with the upload keystore. In this case was upload.
  • PATH_TO_OUTPUT_FILE = The path to the output file with .pem extension. Something like C:\Android\upload_key_public_certificate.pem.

Example:

keytool -export -rfc -keystore "C:\Android\upload_key.jks" -alias upload -file "C:\Android\upload_key_public_certificate.pem"

Press Enter and you will need to provide the keystore password.

Now if everything has gone OK, you will have a file in the folder PATH_TO_OUTPUT_FILE called upload_key_public_certificate.pem.

Step 6: Upload the upload_key_public_certificate.pem file clicking the button identical to the image below

enter image description here

Step 7: Click ENROLL button at the end of the App Signing page.

enter image description here

Now every new release APK must be signed with the upload_key.jks keystore and aliases created in Step 4, prior to be uploaded in the Google Play Developer console.

More Resources:

Q&A

Q: When i upload the APK signed with the new upload_key keystore, Google Play show an error like : You uploaded an unsigned APK. You need to create a signed APK.

A: Check to sign the APK with both signatures (V1 and V2) while building the release APK. Read here for more details.

UPDATED

The step 4,5,6 are to create upload key which is optional for existing apps

"Upload key (optional for existing apps): A new key you generate during your enrollment in the program. You will use the upload key to sign all future APKs prior to uploading them to the Play Console." https://support.google.com/googleplay/android-developer/answer/7384423

Import error: No module name urllib2

The above didn't work for me in 3.3. Try this instead (YMMV, etc)

import urllib.request
url = "http://www.google.com/"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
print (response.read().decode('utf-8'))

Submit HTML form on self page

If you are submitting a form using php be sure to use:

action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"

for security.

How to ignore parent css style

If I understood the question correctly: you can use auto in the CSS like this width: auto; and it will go back to default settings.

Find everything between two XML tags with RegEx

It is not good to use this method but if you really want to split it with regex

<primaryAddress.*>((.|\n)*?)<\/primaryAddress>

the verified answer returns the tags but this just return the value between tags.

TextFX menu is missing in Notepad++

It should usually work using the method Dave described in his answer. (I can confirm seeing "TextFX Characters" in the Available tab in Plugin Manager.)

If it does not, you can try downloading the zip file from here and put its contents (it's one file called NppTextFX.dll) inside the plugins folder where Notepad++ is installed. I suggest doing this while Notepad++ itself is not running.

How to return a value from try, catch, and finally?

To return a value when using try/catch you can use a temporary variable, e.g.

public static double add(String[] values) {
    double sum = 0.0;
    try {
        int length = values.length;
        double arrayValues[] = new double[length];
        for(int i = 0; i < length; i++) {
            arrayValues[i] = Double.parseDouble(values[i]);
            sum += arrayValues[i];
        }
    } catch(NumberFormatException e) {
        e.printStackTrace();
    } catch(RangeException e) {
        throw e;
    } finally {
        System.out.println("Thank you for using the program!");
    }
    return sum;
}

Else you need to have a return in every execution path (try block or catch block) that has no throw.

What does the C++ standard state the size of int, long type to be?

The C++ standard does not specify the size of integral types in bytes, but it specifies minimum ranges they must be able to hold. You can infer minimum size in bits from the required range. You can infer minimum size in bytes from that and the value of the CHAR_BIT macro that defines the number of bits in a byte. In all but the most obscure platforms it's 8, and it can't be less than 8.

One additional constraint for char is that its size is always 1 byte, or CHAR_BIT bits (hence the name). This is stated explicitly in the standard.

The C standard is a normative reference for the C++ standard, so even though it doesn't state these requirements explicitly, C++ requires the minimum ranges required by the C standard (page 22), which are the same as those from Data Type Ranges on MSDN:

  1. signed char: -127 to 127 (note, not -128 to 127; this accommodates 1's-complement and sign-and-magnitude platforms)
  2. unsigned char: 0 to 255
  3. "plain" char: same range as signed char or unsigned char, implementation-defined
  4. signed short: -32767 to 32767
  5. unsigned short: 0 to 65535
  6. signed int: -32767 to 32767
  7. unsigned int: 0 to 65535
  8. signed long: -2147483647 to 2147483647
  9. unsigned long: 0 to 4294967295
  10. signed long long: -9223372036854775807 to 9223372036854775807
  11. unsigned long long: 0 to 18446744073709551615

A C++ (or C) implementation can define the size of a type in bytes sizeof(type) to any value, as long as

  1. the expression sizeof(type) * CHAR_BIT evaluates to a number of bits high enough to contain required ranges, and
  2. the ordering of type is still valid (e.g. sizeof(int) <= sizeof(long)).

Putting this all together, we are guaranteed that:

  • char, signed char, and unsigned char are at least 8 bits
  • signed short, unsigned short, signed int, and unsigned int are at least 16 bits
  • signed long and unsigned long are at least 32 bits
  • signed long long and unsigned long long are at least 64 bits

No guarantee is made about the size of float or double except that double provides at least as much precision as float.

The actual implementation-specific ranges can be found in <limits.h> header in C, or <climits> in C++ (or even better, templated std::numeric_limits in <limits> header).

For example, this is how you will find maximum range for int:

C:

#include <limits.h>
const int min_int = INT_MIN;
const int max_int = INT_MAX;

C++:

#include <limits>
const int min_int = std::numeric_limits<int>::min();
const int max_int = std::numeric_limits<int>::max();

What is a provisioning profile used for when developing iPhone applications?

A Quote from : iPhone Developer Program (~8MB PDF)

A provisioning profile is a collection of digital entities that uniquely ties developers and devices to an authorized iPhone Development Team and enables a device to be used for testing. A Development Provisioning Profile must be installed on each device on which you wish to run your application code. Each Development Provisioning Profile will contain a set of iPhone Development Certificates, Unique Device Identifiers and an App ID. Devices specified within the provisioning profile can be used for testing only by those individuals whose iPhone Development Certificates are included in the profile. A single device can contain multiple provisioning profiles.

setting content between div tags using javascript

Try the following:

document.getElementById("successAndErrorMessages").innerHTML="someContent"; 

msdn link for detail : innerHTML Property

Update using LINQ to SQL

 DataClassesDataContext dc = new DataClassesDataContext();

 FamilyDetail fd = dc.FamilyDetails.Single(p => p.UserId == 1);

 fd.FatherName=txtFatherName.Text;
        fd.FatherMobile=txtMobile.Text;
        fd.FatherOccupation=txtFatherOccu.Text;
        fd.MotherName=txtMotherName.Text;
        fd.MotherOccupation=txtMotherOccu.Text;
        fd.Phone=txtPhoneNo.Text;
        fd.Address=txtAddress.Text;
        fd.GuardianName=txtGardianName.Text;

        dc.SubmitChanges();

Access localhost from the internet

There are couple of good free service that let you do the same. Ideal for showing something quickly for testing:

Edits:

  • add ngrok service
  • add localhost.run service

How to restart remote MySQL server running on Ubuntu linux?

  1. SSH into the machine. Using the proper credentials and ip address, ssh [email protected]. This should provide you with shell access to the Ubuntu server.
  2. Restart the mySQL service. sudo service mysql restart should do the job.

If your mySQL service is named something else like mysqld you may have to change the command accordingly or try this: sudo /etc/init.d/mysql restart

What is "pom" packaging in maven?

https://maven.apache.org/pom.html

The packaging type required to be pom for parent and aggregation (multi-module) projects. These types define the goals bound to a set of lifecycle stages. For example, if packaging is jar, then the package phase will execute the jar:jar goal. If the packaging is pom, the goal executed will be site:attach-descriptor

How to TryParse for Enum value?

Enum.IsDefined will get things done. It may not be as efficient as a TryParse would probably be, but it will work without exception handling.

public static TEnum ToEnum<TEnum>(this string strEnumValue, TEnum defaultValue)
{
    if (!Enum.IsDefined(typeof(TEnum), strEnumValue))
        return defaultValue;

    return (TEnum)Enum.Parse(typeof(TEnum), strEnumValue);
}

Worth noting: a TryParse method was added in .NET 4.0.

Set default heap size in Windows

Setup JAVA_OPTS as a system variable with the following content:

JAVA_OPTS="-Xms256m -Xmx512m"

After that in a command prompt run the following commands:

SET JAVA_OPTS="-Xms256m -Xmx512m"

This can be explained as follows:

  • allocate at minimum 256MBs of heap
  • allocate at maximum 512MBs of heap

These values should be changed according to application requirements.

EDIT:

You can also try adding it through the Environment Properties menu which can be found at:

  1. From the Desktop, right-click My Computer and click Properties.
  2. Click Advanced System Settings link in the left column.
  3. In the System Properties window click the Environment Variables button.
  4. Click New to add a new variable name and value.
  5. For variable name enter JAVA_OPTS for variable value enter -Xms256m -Xmx512m
  6. Click ok and close the System Properties Tab.
  7. Restart any java applications.

EDIT 2:

JAVA_OPTS is a system variable that stores various settings/configurations for your local Java Virtual Machine. By having JAVA_OPTS set as a system variable all applications running on top of the JVM will take their settings from this parameter.

To setup a system variable you have to complete the steps listed above from 1 to 4.

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

http://sourceforge.net/projects/xampp/files/

The old version, but the desired function will be sufficient.

Uninstall version 5.6.11 and downgrade to version 5.6.8.

CSS to make table 100% of max-width

Use this :

<div style="width:700px; background:#F2F2F2">
    <table style="width:100%;padding: 25px; margin: 0 auto; font-family:'Open Sans', 'Helvetica', 'Arial';">
        <tr align="center" style="margin: 0; padding: 0;">
            <td>
                <table style="width:100%;border-style:solid; border-width:2px; border-color: #c3d2d9;" cellspacing="0">
                    <tr style="background-color: white;">
                        <td style=" padding: 10px 15px 10px 15px; color: #000000;">
                            <p>Some content here</p>
                            <span style="font-weight: bold;">My Signature</span><br/>
                            My Title<br/>
                            My Company<br/>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</div>

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

They are the same thing. If you use the set transaction isolation level statement, it will apply to all the tables in the connection, so if you only want a nolock on one or two tables use that; otherwise use the other.

Both will give you dirty reads. If you are okay with that, then use them. If you can't have dirty reads, then consider snapshot or serializable hints instead.

Initialising a multidimensional array in Java

Try replacing the appropriate lines with:

myStringArray[0][x-1] = "a string";
myStringArray[0][y-1] = "another string";

Your code is incorrect because the sub-arrays have a length of y, and indexing starts at 0. So setting to myStringArray[0][y] or myStringArray[0][x] will fail because the indices x and y are out of bounds.

String[][] myStringArray = new String [x][y]; is the correct way to initialise a rectangular multidimensional array. If you want it to be jagged (each sub-array potentially has a different length) then you can use code similar to this answer. Note however that John's assertion that you have to create the sub-arrays manually is incorrect in the case where you want a perfectly rectangular multidimensional array.

gcc warning" 'will be initialized after'

Class C {
   int a;
   int b;
   C():b(1),a(2){} //warning, should be C():a(2),b(1)
}

the order is important because if a is initialized before b , and a is depend on b. undefined behavior will appear.

Does a `+` in a URL scheme/host/path represent a space?

use encodeURIComponent function to fix url, it works on Browser and node.js

res.redirect("/signin?email="+encodeURIComponent("[email protected]"));


> encodeURIComponent("http://a.com/a+b/c")
'http%3A%2F%2Fa.com%2Fa%2Bb%2Fc'

Python reshape list to ndim array

You can specify the interpretation order of the axes using the order parameter:

np.reshape(arr, (2, -1), order='F')

Node.js Hostname/IP doesn't match certificate's altnames

For developers using the Fetch API in a Node.js app, this is how I got this to work using rejectUnauthorized.

Keep in mind that using rejectUnauthorized is dangerous as it opens you up to potential security risks, as it circumvents a problematic certificate.

const fetch = require("node-fetch");
const https = require('https');

const httpsAgent = new https.Agent({
  rejectUnauthorized: false,
});

async function getData() {
  const resp = await fetch(
    "https://myexampleapi.com/endpoint",
    {
      agent: httpsAgent,
    },
  )
  const data = await resp.json()
  return data
}

How to use img src in vue.js?

Try this:

<img v-bind:src="'/media/avatars/' + joke.avatar" /> 

Don't forget single quote around your path string. also in your data check you have correctly defined image variable.

joke: {
  avatar: 'image.jpg'
}

A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output

Which Protocols are used for PING?

The usual command line ping tool uses ICMP Echo, but it's true that other protocols can also be used, and they're useful in debugging different kinds of network problems.

I can remember at least arping (for testing ARP requests) and tcping (which tries to establish a TCP connection and immediately closes it, it can be used to check if traffic reaches a certain port on a host) off the top of my head, but I'm sure there are others aswell.

How to find the nearest parent of a Git branch?

A solution

The solution based on git show-branch did not quite work for me (see below), so I've combined it with the one based on git log and ended up with this:

git log --decorate --simplify-by-decoration --oneline \ # selects only commits with a branch or tag
      | grep -v "(HEAD" \                               # removes current head (and branch)
      | head -n1 \                                      # selects only the closest decoration
      | sed 's/.* (\(.*\)) .*/\1/' \                    # filters out everything but decorations
      | sed 's/\(.*\), .*/\1/' \                        # picks only the first decoration
      | sed 's/origin\///'                              # strips "origin/" from the decoration

Limitations and Caveats

  • HEAD can be detached (many CI tools do so to ensure they build correct commit in a given branch), but origin branch and local branch have to be both at par or "above" the current HEAD.
  • There must be no tags in the way (I presume; I have not tested the script on commits with a tag between child and parent branch)
  • the script relies on the fact "HEAD" is always listed as the first decoration by the log command
  • running the script on master and develop results (mostly) in <SHA> Initial commit

The results

 A---B---D---E---F <-origin/master, master
      \      \
       \      \
        \      G---H---I <- origin/hotfix, hotfix
         \
          \
           J---K---L <-origin/develop, develop
                \
                 \
                  M---N---O <-origin/feature/a, feature/a
                       \   \
                        \   \
                         \   P---Q---R <-origin/feature/b, feature/b
                          \
                           \
                            S---T---U <-origin/feature/c, feature/c

Despite local branch existence (e.g. only origin/topic is present since the commit O was checked-out by directly by its SHA), the script should print as follows:

  • For commits G, H, I (branch hotfix) ? master
  • For commits M, N, O (branch feature/a) ? develop
  • For commits S, T, U (branch feature/c) ? develop
  • For commits P, Q, R (branch feature/b) ? feature/a
  • For commits J, K, L (branch develop) ? <sha> Initial commit*
  • For commits B, D, E, F (branch master) ? <sha> Initial commit

* - or master if develop's commits were on top of master's HEAD (~ the master would be fast-forwardable to develop)


Why did not show-branch work for me

The solution based on git show-branch proved unreliable for me in the following situations:

  • detached HEAD – including detached head case means replacing grep '\*' \ for `grep '!' \ – and that is just the beginning of all the troubles
  • running the script on master and develop results in develop and `` respectively
  • branches on master branch (hotfix/ branches) end up with the develop as a parent since their closest master branch parent was marked with ! instead of * for a reason.

Is there a short contains function for lists?

The list method index will return -1 if the item is not present, and will return the index of the item in the list if it is present. Alternatively in an if statement you can do the following:

if myItem in list:
    #do things

You can also check if an element is not in a list with the following if statement:

if myItem not in list:
    #do things

JQuery get all elements by class name

Alternative solution (you can replace createElement with a your own element)

var mvar = $('.mbox').wrapAll(document.createElement('div')).closest('div').text();
console.log(mvar);

Convert ascii value to char

To convert an int ASCII value to character you can also use:

int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z

How to prevent Browser cache on Angular 2 site?

angular-cli resolves this by providing an --output-hashing flag for the build command (versions 6/7, for later versions see here). Example usage:

ng build --output-hashing=all

Bundling & Tree-Shaking provides some details and context. Running ng help build, documents the flag:

--output-hashing=none|all|media|bundles (String)

Define the output filename cache-busting hashing mode.
aliases: -oh <value>, --outputHashing <value>

Although this is only applicable to users of angular-cli, it works brilliantly and doesn't require any code changes or additional tooling.

Update

A number of comments have helpfully and correctly pointed out that this answer adds a hash to the .js files but does nothing for index.html. It is therefore entirely possible that index.html remains cached after ng build cache busts the .js files.

At this point I'll defer to How do we control web page caching, across all browsers?

Add "Are you sure?" to my excel button, how can I?

On your existing button code, simply insert this line before the procedure:

If MsgBox("This will erase everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub

This will force it to quit if the user presses no.

Selecting element by data attribute with jQuery

Just to complete all the answers with some features of the 'living standard' - By now (in the html5-era) it is possible to do it without an 3rd party libs:

  • pure/plain JS with querySelector (uses CSS-selectors):
    • select the first in DOM: document.querySelector('[data-answer="42"],[type="submit"]')
    • select all in DOM: document.querySelectorAll('[data-answer="42"],[type="submit"]')
  • pure/plain CSS
    • some specific tags: [data-answer="42"],[type="submit"]
    • all tags with an specific attribute: [data-answer] or input[type]

Using SED with wildcard

The asterisk (*) means "zero or more of the previous item".

If you want to match any single character use

sed -i 's/string-./string-0/g' file.txt

If you want to match any string (i.e. any single character zero or more times) use

sed -i 's/string-.*/string-0/g' file.txt

When is each sorting algorithm used?

The Wikipedia page on sorting algorithms has a great comparison chart.

http://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms

Ways to insert javascript into URL?

The key to this is examining any information you recieve and then display and/or use in code on the server. Get/Post form variables if they contain javascript that you store and later redisplay is a security risk. As are any thing that gets concatenated unexamined into a sql statement you run.

One potential gotcha to watch for are attacks that mess with the character encoding. For instance if I submit a form with utf-8 character set but you store and later display in iso-8859-1 latin with no translation then I might be able to sneak something past your validator. The easiest way to handle this is to always display and store in the same character set. utf-8 is usually a good choice. Never depend on the browser to do the right thing for you in this case. Set explicit character sets and examine the character sets you recieve and do a translation to the expected storage set before you validate it.

Error when trying to access XAMPP from a network

This answer is for XAMPP on Ubuntu.

The manual for installation and download is on (site official)

http://www.apachefriends.org/it/xampp-linux.html

After to start XAMPP simply call this command:

sudo /opt/lampp/lampp start

You should now see something like this on your screen:

Starting XAMPP 1.8.1...
LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.

If you have this

Starting XAMPP for Linux 1.8.1...                                                             
XAMPP: Another web server daemon is already running.                                          
XAMPP: Another MySQL daemon is already running.                                               
XAMPP: Starting ProFTPD...                                                                    
XAMPP for Linux started

. The solution is

sudo /etc/init.d/apache2 stop
sudo /etc/init.d/mysql stop

And the restast with sudo //opt/lampp/lampp restart

You to fix most of the security weaknesses simply call the following command:

/opt/lampp/lampp security

After the change this file

sudo kate //opt/lampp/etc/extra/httpd-xampp.conf

Find and replace on

    #
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    Allow from all
    #\
    #   fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
    #   fe80::/10 169.254.0.0/16

    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

Python check if website exists

def isok(mypath):
    try:
        thepage = urllib.request.urlopen(mypath)
    except HTTPError as e:
        return 0
    except URLError as e:
        return 0
    else:
        return 1

How to know user has clicked "X" or the "Close" button?

I've done something like this.

private void Form_FormClosing(object sender, FormClosingEventArgs e)
    {
        if ((sender as Form).ActiveControl is Button)
        {
            //CloseButton
        }
        else
        {
            //The X has been clicked
        }
    }

How do you remove a Cookie in a Java Servlet

This is code that I have effectively used before, passing "/" as the strPath parameter.

public static Cookie eraseCookie(String strCookieName, String strPath) {
    Cookie cookie = new Cookie(strCookieName, "");
    cookie.setMaxAge(0);
    cookie.setPath(strPath);

    return cookie;
}

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

If

width = img.width;
height = img.height;
var ctx = canvas.getContext('2d');

Then you can use these transformations to turn the image to orientation 1

From orientation:

  1. ctx.transform(1, 0, 0, 1, 0, 0);
  2. ctx.transform(-1, 0, 0, 1, width, 0);
  3. ctx.transform(-1, 0, 0, -1, width, height);
  4. ctx.transform(1, 0, 0, -1, 0, height);
  5. ctx.transform(0, 1, 1, 0, 0, 0);
  6. ctx.transform(0, 1, -1, 0, height, 0);
  7. ctx.transform(0, -1, -1, 0, height, width);
  8. ctx.transform(0, -1, 1, 0, 0, width);

Before drawing the image on ctx

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

I want to share my experience on this issue!

Suppose you have a class A and class B.

class A {
    protected $userB;

    public function __construct() {
        $this->userB = new B();
    }
}

class B {
    protected $userA;

    public function __construct() {
        $this->userA = new A();
    }
}

this will initiate a chain formation of objects which may be create this kind of issue!

Remove a child with a specific attribute, in SimpleXML for PHP

Just unset the node:

$str = <<<STR
<a>
  <b>
    <c>
    </c>
  </b>
</a>
STR;

$xml = simplexml_load_string($str);
unset($xml –> a –> b –> c); // this would remove node c
echo $xml –> asXML(); // xml document string without node c

This code was taken from How to delete / remove nodes in SimpleXML.

CMake complains "The CXX compiler identification is unknown"

Your /home/gnu/bin/c++ seem to require additional flag to link things properly and CMake doesn't know about that.

To use /usr/bin/c++ as your compiler run cmake with -DCMAKE_CXX_COMPILER=/usr/bin/c++.

Also, CMAKE_PREFIX_PATH variable sets destination dir where your project' files should be installed. It has nothing to do with CMake installation prefix and CMake itself already know this.

Create a git patch from the uncommitted changes in the current working directory

git diff and git apply will work for text files, but won't work for binary files.

You can easily create a full binary patch, but you will have to create a temporary commit. Once you've made your temporary commit(s), you can create the patch with:

git format-patch <options...>

After you've made the patch, run this command:

git reset --mixed <SHA of commit *before* your working-changes commit(s)>

This will roll back your temporary commit(s). The final result leaves your working copy (intentionally) dirty with the same changes you originally had.

On the receiving side, you can use the same trick to apply the changes to the working copy, without having the commit history. Simply apply the patch(es), and git reset --mixed <SHA of commit *before* the patches>.

Note that you might have to be well-synced for this whole option to work. I've seen some errors when applying patches when the person making them hadn't pulled down as many changes as I had. There are probably ways to get it to work, but I haven't looked far into it.


Here's how to create the same patches in Tortoise Git (not that I recommend using that tool):

  1. Commit your working changes
  2. Right click the branch root directory and click Tortoise Git -> Create Patch Serial
    1. Choose whichever range makes sense (Since: FETCH_HEAD will work if you're well-synced)
    2. Create the patch(es)
  3. Right click the branch root directory and click Tortise Git -> Show Log
  4. Right click the commit before your temporary commit(s), and click reset "<branch>" to this...
  5. Select the Mixed option

And how to apply them:

  1. Right click the branch root directory and click Tortoise Git -> Apply Patch Serial
  2. Select the correct patch(es) and apply them
  3. Right click the branch root directory and click Tortise Git -> Show Log
  4. Right click the commit before the patch's commit(s), and click reset "<branch>" to this...
  5. Select the Mixed option

Difference between os.getenv and os.environ.get

In addition to the answers above:

$ python3 -m timeit -s 'import os' 'os.environ.get("TERM_PROGRAM")'
200000 loops, best of 5: 1.65 usec per loop

$ python3 -m timeit -s 'import os' 'os.getenv("TERM_PROGRAM")'
200000 loops, best of 5: 1.83 usec per loop

Click a button programmatically - JS

When using JavaScript to access an HTML element, there is a good chance that the element is not on the page and therefore not in the dom as far as JavaScript is concerned, when the code to access that element runs.

This problem can occur even though you can visually see the HTML element in the browser window or have the code set to be called in the onload method.

I ran into this problem after writing code to repopulate specific div elements on a page after retrieving the cookies.

What is apparently happening is that even though the HTML has loaded and is outputted by the browser, the JavaScript code is running before the page has completed loading.

The solution to this problem which just may be a JavaScript bug, is to place the code you want to run within a timer that delays the code run by 400 milliseconds or so. You will need to test it to determine how quick you can run the code.

I also made a point to test for the element before attempting to assign values to it.

window.setTimeout(function() { if( document.getElementById("book") ) { // Code goes here }, 400 /* but after 400 ms */);

This may or may not help you solve your problem, but keep this in mind and understand that browsers do not always function as expected.

How to define a connection string to a SQL Server 2008 database?

You need to specify how you'll authenticate with the database. If you want to use integrated security (this means using Windows authentication using your local or domain Windows account), add this to the connection string:

Integrated Security = True;

If you want to use SQL Server authentication (meaning you specify a login and password rather than using a Windows account), add this:

User ID = "username"; Password = "password";

Identify duplicate values in a list in Python

It looks like you want the indices of the duplicates. Here is some short code that will find those in O(n) time, without using any packages:

dups = {}
[dups.setdefault(v, []).append(i) for i, v in enumerate(mylist)]
dups = {k: v for k, v in dups.items() if len(v) > 1}
# dups now has keys for all the duplicate values
# and a list of matching indices for each

# The second line produces an unused list. 
# It could be replaced with this:
for i, v in enumerate(mylist):
    dups.setdefault(v, []).append(i)

css padding is not working in outlook

Make sure to throw on the !important for Outlook especially.

td {
border-collapse: separate;
padding: 15 !important
}

I also wanted borders, so might not work for someone who doesn't.

SQL Current month/ year question

This should work for SQL Server:

SELECT * FROM myTable
WHERE month = DATEPART(m, GETDATE()) AND
year = DATEPART(yyyy, GETDATE())

What does <T> (angle brackets) mean in Java?

<> is used to indicate generics in Java.

T is a type parameter in this example. And no: instantiating is one of the few things that you can't do with T.

Apart from the tutorial linked above Angelika Langers Generics FAQ is a great resource on the topic.

Why does comparing strings using either '==' or 'is' sometimes produce a different result?

is is identity testing and == is equality testing. This means is is a way to check whether two things are the same things, or just equivalent.

Say you've got a simple person object. If it is named 'Jack' and is '23' years old, it's equivalent to another 23-year-old Jack, but it's not the same person.

class Person(object):
   def __init__(self, name, age):
       self.name = name
       self.age = age

   def __eq__(self, other):
       return self.name == other.name and self.age == other.age

jack1 = Person('Jack', 23)
jack2 = Person('Jack', 23)

jack1 == jack2 # True
jack1 is jack2 # False

They're the same age, but they're not the same instance of person. A string might be equivalent to another, but it's not the same object.

Optional args in MATLAB functions

A good way of going about this is not to use nargin, but to check whether the variables have been set using exist('opt', 'var').

Example:

function [a] = train(x, y, opt)
    if (~exist('opt', 'var'))
        opt = true;
    end
end

See this answer for pros of doing it this way: How to check whether an argument is supplied in function call?

How to get a random number in Ruby

Use rand(range)

From Ruby Random Numbers:

If you needed a random integer to simulate a roll of a six-sided die, you'd use: 1 + rand(6). A roll in craps could be simulated with 2 + rand(6) + rand(6).

Finally, if you just need a random float, just call rand with no arguments.


As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby 1.9.2 has its own Random class (that Marc-André himself helped to debug, hence the 1.9.2 target for that feature).

For instance, in this game where you need to guess 10 numbers, you can initialize them with:

10.times.map{ 20 + Random.rand(11) } 
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]

Note:

This is why the equivalent of Random.new.rand(20..30) would be 20 + Random.rand(11), since Random.rand(int) returns “a random integer greater than or equal to zero and less than the argument.” 20..30 includes 30, I need to come up with a random number between 0 and 11, excluding 11.

Remove the last character from a string

You can use substr:

echo substr('a,b,c,d,e,', 0, -1);
# => 'a,b,c,d,e'

decompiling DEX into Java sourcecode

Since no one mentioned this, there's one more tool: DED homepage

Install how-to and some explanations: Installation.

It was used in a quite interesting study of the security of top market apps(not really related, just if you're curious): A Survey of Android Application Security

comparing strings in vb

In vb.net you can actually compare strings with =. Even though String is a reference type, in vb.net = on String has been redefined to do a case-sensitive comparison of contents of the two strings.

You can test this with the following code. Note that I have taken one of the values from user input to ensure that the compiler cannot use the same reference for the two variables like the Java compiler would if variables were defined from the same string Literal. Run the program, type "This" and press <Enter>.

Sub Main()
    Dim a As String = New String("This")
    Dim b As String

    b = Console.ReadLine()

    If a = b Then
        Console.WriteLine("They are equal")
    Else
        Console.WriteLine("Not equal")
    End If
    Console.ReadLine()
End Sub

How to use S_ISREG() and S_ISDIR() POSIX Macros?

[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);

int main(int argc, char *argv[]){

  DIR *dip;
  struct dirent *dit;
  struct stat statbuf;
  char currentPath[FILENAME_MAX];
  int depth = 0; /*Used to correctly space output*/

  /*Open Current Directory*/
  if((dip = opendir(".")) == NULL)
    return errno;

  /*Store Current Working Directory in currentPath*/
  if((getcwd(currentPath, FILENAME_MAX)) == NULL)
    return errno;

  /*Read all items in directory*/
  while((dit = readdir(dip)) != NULL){

    /*Skips . and ..*/
    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    /*Correctly forms the path for stat and then resets it for rest of algorithm*/
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    if(stat(currentPath, &statbuf) == -1){
      perror("stat");
      return errno;
    }
    getcwd(currentPath, FILENAME_MAX);


    /*Checks if current item is of the type file (type 8) and no command line arguments*/
    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*If a command line argument is given, checks for filename match*/
    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
      if(strcmp(dit->d_name, argv[1]) == 0)
         printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*Checks if current item is of the type directory (type 4)*/
    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);

  }
  closedir(dip);
  return 0;
}

/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf, 
        char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  if((dip = opendir(currentPath)) == NULL)
    printf("Error: Failed to open Directory ==> %s\n", currentPath);

  while((dit = readdir(dip)) != NULL){

    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    stat(currentPath, &statbuf);
    getcwd(currentPath, FILENAME_MAX);

    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
      for(i = 0; i < depth; i++)
    printf("    ");
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
    }

    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
      if(strcmp(dit->d_name, argv[1]) == 0){
    for(i = 0; i < depth; i++)
      printf("    ");
    printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
      }
    }

    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);
  }
  /*Changing back here is necessary because of how stat is done*/
    chdir("..");
    closedir(dip);
}

void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf, 
          char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  strcat(currentPath, "/");
  strcat(currentPath, dit->d_name);

  /*If two directories exist at the same level the path
    is built wrong and needs to be corrected*/
  if((chdir(currentPath)) == -1){
    chdir("..");
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);

    for(i = 0; i < depth; i++)
      printf ("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }

  else{
    for(i =0; i < depth; i++)
      printf("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    chdir(currentPath);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }
}

import an array in python

In Python, Storing a bare python list as a numpy.array and then saving it out to file, then loading it back, and converting it back to a list takes some conversion tricks. The confusion is because python lists are not at all the same thing as numpy.arrays:

import numpy as np
foods = ['grape', 'cherry', 'mango']
filename = "./outfile.dat.npy"
np.save(filename, np.array(foods))
z = np.load(filename).tolist()
print("z is: " + str(z))

This prints:

z is: ['grape', 'cherry', 'mango']

Which is stored on disk as the filename: outfile.dat.npy

The important methods here are the tolist() and np.array(...) conversion functions.

How to revert the last migration?

If you are facing trouble while reverting back the migration, and somehow have messed it, you can perform fake migrations.

./manage.py migrate <name> --ignore-ghost-migrations --merge --fake

For django version < 1.7 this will create entry in south_migrationhistory table, you need to delete that entry.

Now you'll be able to revert back the migration easily.

PS: I was stuck for a lot of time and performing fake migration and then reverting back helped me out.

How to increase the execution timeout in php?

optional : if you set config about php.ini but still can't upload

-this is php function to check error code

$error_type = [];
$error_type[0] = "There is no error";
$error_type[1] = "The uploaded file exceeds the upload_max_filesize directive in php.ini.";
$error_type[2] = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.";
$error_type[3] = "The uploaded file was only partially uploaded.";
$error_type[4] = "No file was uploaded.";
//$error_type["5"] = "";
$error_type[6] = "Missing a temporary folder. Introduced in PHP 5.0.3.";
$error_type[7] = "Failed to write file to disk. Introduced in PHP 5.1.0.";
$error_type[8] = "A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.";
//------------------------------
//--> show msg error.
$status_code = $_FILES["uploadfile"]["error"];
if($status_code != 0){
    echo $error_type[$status_code];
    exit;
}

regex error - nothing to repeat

Beyond the bug that was discovered and fixed, I'll just note that the error message sre_constants.error: nothing to repeat is a bit confusing. I was trying to use r'?.*' as a pattern, and thought it was complaining for some strange reason about the *, but the problem is actually that ? is a way of saying "repeat zero or one times". So I needed to say r'\?.*'to match a literal ?

How to correctly represent a whitespace character

Using regular expressions, you can represent any whitespace character with the metacharacter "\s"

MSDN Reference

Eclipse "this compilation unit is not on the build path of a java project"

I also had this problem after converting my java project into a maven project. I solved it as follows:

Right click on your project ->Project Facets -> click on Java, then Apply.

Accurate way to measure execution times of php scripts

You can use the microtime function for this. From the documentation:

microtime — Return current Unix timestamp with microseconds


If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

Example usage:

$start = microtime(true);
while (...) {

}
$time_elapsed_secs = microtime(true) - $start;

Determine if an element has a CSS class with jQuery

In the interests of helping anyone who lands here but was actually looking for a jQuery free way of doing this:

element.classList.contains('your-class-name')

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is non-standard and only supported by Internet Explorer on Windows.

There is no native cross browser way to write to the file system without using plugins, even the draft File API gives read only access.

If you want to work cross platform, then you need to look at such things as signed Java applets (keeping in mind that that will only work on platforms for which the Java runtime is available).

Determining type of an object in ruby

The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object.class.

Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.is_a?(ClassName) to see if object is of type ClassName or derived from it.

Normally type checking is not done in Ruby, but instead objects are assessed based on their ability to respond to particular methods, commonly called "Duck typing". In other words, if it responds to the methods you want, there's no reason to be particular about the type.

For example, object.is_a?(String) is too rigid since another class might implement methods that convert it into a string, or make it behave identically to how String behaves. object.respond_to?(:to_s) would be a better way to test that the object in question does what you want.

Label python data points on plot

How about print (x, y) at once.

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

plt.grid()
plt.show()

enter image description here

connecting MySQL server to NetBeans

Fist of all make sure your SQL server is running. Actually I'm working on windows and I have installed a nice tool which is called MySQL workbench (you can find it here for almost any platform ).

you can see the server is running

Thus I just create a new database to test the connection, let's call it stackoverflow, with one table called user.

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

DROP SCHEMA IF EXISTS `stackoverflow` ;
CREATE SCHEMA IF NOT EXISTS `stackoverflow` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `stackoverflow` ;

-- -----------------------------------------------------
-- Table `stackoverflow`.`user`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `stackoverflow`.`user` ;

CREATE TABLE IF NOT EXISTS `stackoverflow`.`user` (
  `iduser` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(75) NOT NULL,
  `email` VARCHAR(150) NOT NULL,
  PRIMARY KEY (`iduser`),
  UNIQUE INDEX `iduser_UNIQUE` (`iduser` ASC),
  UNIQUE INDEX `email_UNIQUE` (`email` ASC))
ENGINE = InnoDB;


SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

You can reduce important part to

 CREATE SCHEMA IF NOT EXISTS `stackoverflow`

 CREATE TABLE IF NOT EXISTS `stackoverflow`.`user` (
      `iduser` INT NOT NULL AUTO_INCREMENT,
      `name` VARCHAR(75) NOT NULL,
      `email` VARCHAR(150) NOT NULL,
      PRIMARY KEY (`iduser`),
      UNIQUE INDEX `iduser_UNIQUE` (`iduser` ASC),
      UNIQUE INDEX `email_UNIQUE` (`email` ASC))

So now I have my brand new stackoverflow database. Let's connect to it throught Netbeans. Launch netbeans and go to the services panel list of connections available Now right click on databases: new connection.. Choose MySql connector, they already come packed with netbeans. connector Then fill in the gaps the data you need. As shown in the picture add the database name and remove from the connection url the optional parameters as l?zeroDateTimeBehaviour=convertToNull . Use the right user name and password and test the connection. data

As you can see connection is successful.

Click FINISH.

You will have your connection successfully working and available under the services.

finish

How to initialize a static array?

If you are creating an array then there is no difference, however, the following is neater:

String[] suit = {
  "spades", 
  "hearts", 
  "diamonds", 
  "clubs"  
};

But, if you want to pass an array into a method you have to call it like this:

myMethod(new String[] {"spades", "hearts"});

myMethod({"spades", "hearts"}); //won't compile!

How to hide UINavigationBar 1px bottom line

In Xamarin Forms this worked for me. Just add this on AppDelegate.cs:

UINavigationBar.Appearance.ShadowImage = new UIImage();

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

My mistake, I shouldn't have used a method inside a LINQ query.

Correct code:

using Microsoft.AspNet.Identity;


string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);

Using os.walk() to recursively traverse directories in Python

This does it for folder names:

def printFolderName(init_indent, rootFolder):
    fname = rootFolder.split(os.sep)[-1]
    root_levels = rootFolder.count(os.sep)
    # os.walk treats dirs breadth-first, but files depth-first (go figure)
    for root, dirs, files in os.walk(rootFolder):
        # print the directories below the root
        levels = root.count(os.sep) - root_levels
        indent = ' '*(levels*2)
        print init_indent + indent + root.split(os.sep)[-1]

How can I limit the visible options in an HTML <select> dropdown?

It is not possible to limit the number of visible elements in the select dropdown (if you use it as dropdown box and not as list).

But you could use javascript/jQuery to replace this selectbox with something else, which just looks like a dropdown box. Then you can handle the height of dropdown as you want.

jNice would be a jQuery plugin which has such features. But there also exists many alternatives for that.

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

When this happened to me with the WindowsAPICodePack after I updated it, I just rebuilt the solution.

Build-->Rebuild Solution

Print <div id="printarea"></div> only?

The Best way to Print particular Div or any Element

printDiv("myDiv");

function printDiv(id){
        var printContents = document.getElementById(id).innerHTML;
        var originalContents = document.body.innerHTML;
        document.body.innerHTML = printContents;
        window.print();
        document.body.innerHTML = originalContents;
}

Gson: Is there an easier way to serialize a map

Only the TypeToken part is neccesary (when there are Generics involved).

Map<String, String> myMap = new HashMap<String, String>();
myMap.put("one", "hello");
myMap.put("two", "world");

Gson gson = new GsonBuilder().create();
String json = gson.toJson(myMap);

System.out.println(json);

Type typeOfHashMap = new TypeToken<Map<String, String>>() { }.getType();
Map<String, String> newMap = gson.fromJson(json, typeOfHashMap); // This type must match TypeToken
System.out.println(newMap.get("one"));
System.out.println(newMap.get("two"));

Output:

{"two":"world","one":"hello"}
hello
world

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

Sequelize OR condition object

String based operators will be deprecated in the future (You've probably seen the warning in console).

Getting this to work with symbolic operators was quite confusing for me, and I've updated the docs with two examples.

Post.findAll({
  where: {
    [Op.or]: [{authorId: 12}, {authorId: 13}]
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;

Post.findAll({
  where: {
    authorId: {
      [Op.or]: [12, 13]
    }
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;

Python: How to use RegEx in an if statement?

if re.search(r'pattern', string):

Simple if-test:

if re.search(r'ing\b', "seeking a great perhaps"):     # any words end with ing?
    print("yes")

Pattern check, extract a substring, case insensitive:

match_object = re.search(r'^OUGHT (.*) BE$', "ought to be", flags=re.IGNORECASE)
if match_object:
    assert "to" == match_object.group(1)     # what's between ought and be?

Notes:

  • Use re.search() not re.match. Match restricts to the start of strings, a confusing convention if you ask me. If you do want a string-starting match, use caret or \A instead, re.search(r'^...', ...)

  • Use raw string syntax r'pattern' for the first parameter. Otherwise you would need to double up backslashes, as in re.search('ing\\b', ...)

  • In this example, \b is a special sequence meaning word-boundary in regex. Not to be confused with backspace.

  • re.search() returns None if it doesn't find anything, which is always falsy.

  • re.search() returns a Match object if it finds anything, which is always truthy.

  • a group is what matched inside parentheses

  • group numbering starts at 1

  • Specs

  • Tutorial

How to pass datetime from c# to sql correctly?

You've already done it correctly by using a DateTime parameter with the value from the DateTime, so it should already work. Forget about ToString() - since that isn't used here.

If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).

I have a table and the date-times in it are in the format: 2011-07-01 15:17:33.357

Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.

"unexpected token import" in Nodejs5 and babel?

In your app, you must declare your require() modules, not using the 'import' keyword:

const app = require("example_dependency");

Then, create a .babelrc file:

{
"presets": [ 
    ["es2015", { "modules": false }]
]
}

Then, in your gulpfile, be sure to declare your require() modules:

var gulp = require("gulp");

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

In my case adding Microsoft.AspNet.WebApi.Owin reference via nuget did the trick.

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

if you can get the proper response in your localhost and getting this error kind of error and if you are using nginx.

  1. Go to Server and open nginx.conf with :

    nano etc/nginx/nginx.conf

  2. Add following line in http block :

    proxy_buffering off;

  3. Save and exit the file

This solved my issue

Regular expression to match a word or its prefix

I test examples in js. Simplest solution - just add word u need inside / /:

var reg = /cat/;
reg.test('some cat here');//1 test
true // result
reg.test('acatb');//2 test
true // result

Now if u need this specific word with boundaries, not inside any other signs-letters. We use b marker:

var reg = /\bcat\b/
reg.test('acatb');//1 test 
false // result
reg.test('have cat here');//2 test
true // result

We have also exec() method in js, whichone returns object-result. It helps f.g. to get info about place/index of our word.

var matchResult = /\bcat\b/.exec("good cat good");
console.log(matchResult.index); // 5

If we need get all matched words in string/sentence/text, we can use g modifier (global match):

"cat good cat good cat".match(/\bcat\b/g).length
// 3 

Now the last one - i need not 1 specific word, but some of them. We use | sign, it means choice/or.

"bad dog bad".match(/\bcat|dog\b/g).length
// 1

How do you do a ‘Pause’ with PowerShell 2.0?

I assume that you want to read input from the console. If so, use Read-Host.

How do I remove javascript validation from my eclipse project?

Window -> Preferences -> JavaScript -> Validator (also per project settings possible)

or

Window -> Preferences -> Validation (disable validations and configure their settings)

How do I invert BooleanToVisibilityConverter?

Here's one I wrote and use a lot. It uses a boolean converter parameter that indicates whether or not to invert the value and then uses XOR to perform the negation:

[ValueConversion(typeof(bool), typeof(System.Windows.Visibility))]
public class BooleanVisibilityConverter : IValueConverter
{
    System.Windows.Visibility _visibilityWhenFalse = System.Windows.Visibility.Collapsed;

    /// <summary>
    /// Gets or sets the <see cref="System.Windows.Visibility"/> value to use when the value is false. Defaults to collapsed.
    /// </summary>
    public System.Windows.Visibility VisibilityWhenFalse
    {
        get { return _visibilityWhenFalse; }
        set { _visibilityWhenFalse = value; }
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool negateValue;
        Boolean.TryParse(parameter as string, out negateValue);

        bool val = negateValue ^ System.Convert.ToBoolean(value); //Negate the value when negateValue is true using XOR
        return val ? System.Windows.Visibility.Visible : _visibilityWhenFalse;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool negateValue;
        Boolean.TryParse(parameter as string, out negateValue);

        if ((System.Windows.Visibility)value == System.Windows.Visibility.Visible)
            return true ^ negateValue;
        else
            return false ^ negateValue;
    }
}

Here's an XOR truth table for reference:

        XOR
        x  y  XOR
        ---------
        0  0  0
        0  1  1
        1  0  1
        1  1  0

'node' is not recognized as an internal or external command

Try adding C:\Program Files\Nodejs to your PATH environment variable. The PATH environment variable allows run executables or access files within the folders specified (separated by semicolons).

On the command prompt, the command would be set PATH=%PATH%;C:\Program Files\Nodejs.

Python base64 data decode

Python 3 (and 2)

import base64
a = 'eW91ciB0ZXh0'
base64.b64decode(a)

Python 2

A quick way to decode it without importing anything:

'eW91ciB0ZXh0'.decode('base64')

or more descriptive

>>> a = 'eW91ciB0ZXh0'
>>> a.decode('base64')
'your text'

How do you display JavaScript datetime in 12 hour AM/PM format?

<script>
var todayDate = new Date();
var getTodayDate = todayDate.getDate();
var getTodayMonth =  todayDate.getMonth()+1;
var getTodayFullYear = todayDate.getFullYear();
var getCurrentHours = todayDate.getHours();
var getCurrentMinutes = todayDate.getMinutes();
var getCurrentAmPm = getCurrentHours >= 12 ? 'PM' : 'AM';
getCurrentHours = getCurrentHours % 12;
getCurrentHours = getCurrentHours ? getCurrentHours : 12; 
getCurrentMinutes = getCurrentMinutes < 10 ? '0'+getCurrentMinutes : getCurrentMinutes;
var getCurrentDateTime = getTodayDate + '-' + getTodayMonth + '-' + getTodayFullYear + ' ' + getCurrentHours + ':' + getCurrentMinutes + ' ' + getCurrentAmPm;
alert(getCurrentDateTime);
</script>

How do I open workbook programmatically as read-only?

Does this work?

Workbooks.Open Filename:=filepath, ReadOnly:=True

Or, as pointed out in a comment, to keep a reference to the opened workbook:

Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)

What is *.o file?

A file ending in .o is an object file. The compiler creates an object file for each source file, before linking them together, into the final executable.

Twitter Bootstrap: div in container with 100% height

It is very simple. You can use

.fill .map 
{
  min-height: 100vh;
}

You can change height according to your requirement.

How to toggle font awesome icon on click?

You can toggle the class of the i element within the clicked anchor like

<i class="fa fa-plus-circle"></i>

then

$('#category-tabs li a').click(function(){
    $(this).next('ul').slideToggle('500');
    $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle')
});

Demo: Fiddle

How to check if ping responded or not in a batch file

The following checklink.cmd program is a good place to start. It relies on the fact that you can do a single-shot ping and that, if successful, the output will contain the line:

Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),

By extracting tokens 5 and 7 and checking they're respectively "Received" and "1,", you can detect the success.

@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
:loop
set state=down
for /f "tokens=5,6,7" %%a in ('ping -n 1 !ipaddr!') do (
    if "x%%b"=="xunreachable." goto :endloop
    if "x%%a"=="xReceived" if "x%%c"=="x1,"  set state=up
)
:endloop
echo.Link is !state!
ping -n 6 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal

Call it with the name (or IP address) you want to test:

checklink 127.0.0.1
checklink localhost
checklink nosuchaddress

Take into account that, if your locale is not English, you must replace Received with the corresponding keyword in your locale, for example recibidos for Spanish. Do a test ping to discover what keyword is used in your locale.


To only notify you when the state changes, you can use:

@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
set oldstate=neither
:loop
set state=down
for /f "tokens=5,7" %%a in ('ping -n 1 !ipaddr!') do (
    if "x%%a"=="xReceived" if "x%%b"=="x1," set state=up
)
if not !state!==!oldstate! (
    echo.Link is !state!
    set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal

However, as Gabe points out in a comment, you can just use ERRORLEVEL so the equivalent of that second script above becomes:

@setlocal enableextensions enabledelayedexpansion
@echo off
set ipaddr=%1
set oldstate=neither
:loop
set state=up
ping -n 1 !ipaddr! >nul: 2>nul:
if not !errorlevel!==0 set state=down
if not !state!==!oldstate! (
    echo.Link is !state!
    set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal

Initializing C dynamic arrays

p = {1,2,3} is wrong.

You can never use this:

int * p;
p = {1,2,3};

loop is right

int *p,i;
p = malloc(3*sizeof(int));
for(i = 0; i<3; ++i)
    p[i] = i;

Get connection string from App.config

First you have to add System.Configuration reference to your project and then use below code to get connection string.

_connectionString = ConfigurationManager.ConnectionStrings["MYSQLConnection"].ConnectionString.ToString();

HTTP Range header

As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.

A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges response. Chrome always sends a Range: bytes=0- with its first GET request for a video, so it's something you can't dismiss.

Whenever a client includes Range: in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:

Range: bytes=3744-

So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.

You can handle the type of 'range' you specified in your question in two ways:

First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:

Request:

GET /BigBuckBunny_320x180.mp4 
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927

Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:

Request:

GET /BigBuckBunny_320x180.mp4
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*

Tips:

You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:

Request: Range: bytes=500-1000

Response: Content-Range: bytes 500-1000/123456

Remember that the range is zero-indexed, so Range: bytes=0-999 is actually requesting 1000 bytes, not 999, so respond with something like:

Content-Length: 1000
Content-Range: bytes 0-999/123456

Or:

Content-Length: 1000
Content-Range: bytes 0-999/*

But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:

X-Content-Duration: 63.23 

This must be a floating point. Unlike Content-Length, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:

X-Content-Duration: 7200.00 

With some media types, such as webm, you must also include the content-type, such as:

Content-Type: video/webm 

All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.

X-Content-Duration is being phased out in favor of Content-Duration, so I'd include that too. A basic, response to a "0-" request would include at least the following:

HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53

One more point: Chrome always starts its first video request with the following:

Range: bytes=0-

Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.