Programs & Examples On #Slk

Solving sslv3 alert handshake failure when trying to use a client certificate

Not a definite answer but too much to fit in comments:

I hypothesize they gave you a cert that either has a wrong issuer (although their server could use a more specific alert code for that) or a wrong subject. We know the cert matches your privatekey -- because both curl and openssl client paired them without complaining about a mismatch; but we don't actually know it matches their desired CA(s) -- because your curl uses openssl and openssl SSL client does NOT enforce that a configured client cert matches certreq.CAs.

Do openssl x509 <clientcert.pem -noout -subject -issuer and the same on the cert from the test P12 that works. Do openssl s_client (or check the one you did) and look under Acceptable client certificate CA names; the name there or one of them should match (exactly!) the issuer(s) of your certs. If not, that's most likely your problem and you need to check with them you submitted your CSR to the correct place and in the correct way. Perhaps they have different regimes in different regions, or business lines, or test vs prod, or active vs pending, etc.

If the issuer of your cert does match desiredCAs, compare its subject to the working (test-P12) one: are they in similar format? are there any components in the working one not present in yours? If they allow it, try generating and submitting a new CSR with a subject name exactly the same as the test-P12 one, or as close as you can get, and see if that produces a cert that works better. (You don't have to generate a new key to do this, but if you choose to, keep track of which certs match which keys so you don't get them mixed up.) If that doesn't help look at the certificate extensions with openssl x509 <cert -noout -text for any difference(s) that might reasonably be related to subject authorization, like KeyUsage, ExtendedKeyUsage, maybe Policy, maybe Constraints, maybe even something nonstandard.

If all else fails, ask the server operator(s) what their logs say about the problem, or if you have access look at the logs yourself.

ReactJS call parent method

2019 Update with react 16+ and ES6

Posting this since React.createClass is deprecated from react version 16 and the new Javascript ES6 will give you more benefits.

Parent

import React, {Component} from 'react';
import Child from './Child';
  
export default class Parent extends Component {

  es6Function = (value) => {
    console.log(value)
  }

  simplifiedFunction (value) {
    console.log(value)
  }

  render () {
  return (
    <div>
    <Child
          es6Function = {this.es6Function}
          simplifiedFunction = {this.simplifiedFunction} 
        />
    </div>
    )
  }

}

Child

import React, {Component} from 'react';

export default class Child extends Component {

  render () {
  return (
    <div>
    <h1 onClick= { () =>
            this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
          }
        > Something</h1>
    </div>
    )
  }
}

Simplified stateless child as ES6 constant

import React from 'react';

const Child = () => {
  return (
    <div>
    <h1 onClick= { () =>
        this.props.es6Function(<SomethingThatYouWantToPassIn>)
      }
      > Something</h1>
    </div>
  )

}
export default Child;

How can I get the last 7 characters of a PHP string?

For simplicity, if you do not want send a message, try this

$new_string = substr( $dynamicstring, -min( strlen( $dynamicstring ), 7 ) );

Occurrences of substring in a string

Here it is, wrapped up in a nice and reusable method:

public static int count(String text, String find) {
        int index = 0, count = 0, length = find.length();
        while( (index = text.indexOf(find, index)) != -1 ) {                
                index += length; count++;
        }
        return count;
}

Convert to/from DateTime and Time in Ruby

You'll need two slightly different conversions.

To convert from Time to DateTime you can amend the Time class as follows:

require 'date'
class Time
  def to_datetime
    # Convert seconds + microseconds into a fractional number of seconds
    seconds = sec + Rational(usec, 10**6)

    # Convert a UTC offset measured in minutes to one measured in a
    # fraction of a day.
    offset = Rational(utc_offset, 60 * 60 * 24)
    DateTime.new(year, month, day, hour, min, seconds, offset)
  end
end

Similar adjustments to Date will let you convert DateTime to Time .

class Date
  def to_gm_time
    to_time(new_offset, :gm)
  end

  def to_local_time
    to_time(new_offset(DateTime.now.offset-offset), :local)
  end

  private
  def to_time(dest, method)
    #Convert a fraction of a day to a number of microseconds
    usec = (dest.sec_fraction * 60 * 60 * 24 * (10**6)).to_i
    Time.send(method, dest.year, dest.month, dest.day, dest.hour, dest.min,
              dest.sec, usec)
  end
end

Note that you have to choose between local time and GM/UTC time.

Both the above code snippets are taken from O'Reilly's Ruby Cookbook. Their code reuse policy permits this.

Setting transparent images background in IrfanView

If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").

Local Storage vs Cookies

In the context of JWTs, Stormpath have written a fairly helpful article outlining possible ways to store them, and the (dis-)advantages pertaining to each method.

It also has a short overview of XSS and CSRF attacks, and how you can combat them.

I've attached some short snippets of the article below, in case their article is taken offline/their site goes down.

Local Storage

Problems:

Web Storage (localStorage/sessionStorage) is accessible through JavaScript on the same domain. This means that any JavaScript running on your site will have access to web storage, and because of this can be vulnerable to cross-site scripting (XSS) attacks. XSS in a nutshell is a type of vulnerability where an attacker can inject JavaScript that will run on your page. Basic XSS attacks attempt to inject JavaScript through form inputs, where the attacker puts alert('You are Hacked'); into a form to see if it is run by the browser and can be viewed by other users.

Prevention:

To prevent XSS, the common response is to escape and encode all untrusted data. But this is far from the full story. In 2015, modern web apps use JavaScript hosted on CDNs or outside infrastructure. Modern web apps include 3rd party JavaScript libraries for A/B testing, funnel/market analysis, and ads. We use package managers like Bower to import other peoples’ code into our apps.

What if only one of the scripts you use is compromised? Malicious JavaScript can be embedded on the page, and Web Storage is compromised. These types of XSS attacks can get everyone’s Web Storage that visits your site, without their knowledge. This is probably why a bunch of organizations advise not to store anything of value or trust any information in web storage. This includes session identifiers and tokens.

As a storage mechanism, Web Storage does not enforce any secure standards during transfer. Whoever reads Web Storage and uses it must do their due diligence to ensure they always send the JWT over HTTPS and never HTTP.

Cookies

Problems:

Cookies, when used with the HttpOnly cookie flag, are not accessible through JavaScript, and are immune to XSS. You can also set the Secure cookie flag to guarantee the cookie is only sent over HTTPS. This is one of the main reasons that cookies have been leveraged in the past to store tokens or session data. Modern developers are hesitant to use cookies because they traditionally required state to be stored on the server, thus breaking RESTful best practices. Cookies as a storage mechanism do not require state to be stored on the server if you are storing a JWT in the cookie. This is because the JWT encapsulates everything the server needs to serve the request.

However, cookies are vulnerable to a different type of attack: cross-site request forgery (CSRF). A CSRF attack is a type of attack that occurs when a malicious web site, email, or blog causes a user’s web browser to perform an unwanted action on a trusted site on which the user is currently authenticated. This is an exploit of how the browser handles cookies. A cookie can only be sent to the domains in which it is allowed. By default, this is the domain that originally set the cookie. The cookie will be sent for a request regardless of whether you are on galaxies.com or hahagonnahackyou.com.

Prevention:

Modern browsers support the SameSite flag, in addition to HttpOnly and Secure. The purpose of this flag is to prevent the cookie from being transmitted in cross-site requests, preventing many kinds of CSRF attack.

For browsers that do not support SameSite, CSRF can be prevented by using synchronized token patterns. This sounds complicated, but all modern web frameworks have support for this.

For example, AngularJS has a solution to validate that the cookie is accessible by only your domain. Straight from AngularJS docs:

When performing XHR requests, the $http service reads a token from a cookie (by default, XSRF-TOKEN) and sets it as an HTTP header (X-XSRF-TOKEN). Since only JavaScript that runs on your domain can read the cookie, your server can be assured that the XHR came from JavaScript running on your domain. You can make this CSRF protection stateless by including a xsrfToken JWT claim:

{
  "iss": "http://galaxies.com",
  "exp": 1300819380,
  "scopes": ["explorer", "solar-harvester", "seller"],
  "sub": "[email protected]",
  "xsrfToken": "d9b9714c-7ac0-42e0-8696-2dae95dbc33e"
}

Leveraging your web app framework’s CSRF protection makes cookies rock solid for storing a JWT. CSRF can also be partially prevented by checking the HTTP Referer and Origin header from your API. CSRF attacks will have Referer and Origin headers that are unrelated to your application.

The full article can be found here: https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage/

They also have a helpful article on how to best design and implement JWTs, with regards to the structure of the token itself: https://stormpath.com/blog/jwt-the-right-way/

offsetting an html anchor to adjust for fixed header

The above methods don't work very well if your anchor is a table element or within a table (row or cell).

I had to use javascript and bind to the window hashchange event to work around this (demo):

function moveUnderNav() {
    var $el, h = window.location.hash;
    if (h) {
        $el = $(h);
        if ($el.length && $el.closest('table').length) {
            $('body').scrollTop( $el.closest('table, tr').position().top - 26 );
        }
    }
}

$(window)
    .load(function () {
        moveUnderNav();
    })
    .on('hashchange', function () {
        moveUnderNav();
    });

* Note: The hashchange event is not available in all browsers.

cannot find zip-align when publishing app

Zipalign gradle task is deprecated since Android Plugin for Gradle, Revision 2.2.0 (September 2016).

If you want to keep using it, add android.useOldPackaging=true to your gradle.properties file.

Click here for detailed explanation.

Improves build performance by adopting a new default packaging pipeline which handles zipping, signing, and zipaligning in one task. You can revert to using the older packaging tools by adding android.useOldPackaging=true to your gradle.properties file. While using the new packaging tool, the zipalignDebug task is not available. However, you can create one yourself by calling the createZipAlignTask(String taskName, File inputFile, File outputFile) method. APK signing now uses APK Signature Scheme v2 in addition to traditional JAR signing. All Android platforms accept the resulting APKs. Any modification to these APKs after signing invalidates their v2 signatures and prevents installation on a device. Blockquote

Chrome Extension - Get DOM content

The terms "background page", "popup", "content script" are still confusing you; I strongly suggest a more in-depth look at the Google Chrome Extensions Documentation.

Regarding your question if content scripts or background pages are the way to go:

Content scripts: Definitely
Content scripts are the only component of an extension that has access to the web-page's DOM.

Background page / Popup: Maybe (probably max. 1 of the two)
You may need to have the content script pass the DOM content to either a background page or the popup for further processing.


Let me repeat that I strongly recommend a more careful study of the available documentation!
That said, here is a sample extension that retrieves the DOM content on StackOverflow pages and sends it to the background page, which in turn prints it in the console:

background.js:

// Regex-pattern to check URLs against. 
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;

// A function to use as callback
function doStuffWithDom(domContent) {
    console.log('I received the following DOM content:\n' + domContent);
}

// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
    // ...check the URL of the active tab against our pattern and...
    if (urlRegex.test(tab.url)) {
        // ...if it matches, send a message specifying a callback too
        chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
    }
});

content.js:

// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    // If the received message has the expected format...
    if (msg.text === 'report_back') {
        // Call the specified callback, passing
        // the web-page's DOM content as argument
        sendResponse(document.all[0].outerHTML);
    }
});

manifest.json:

{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "0.0",
  ...

  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "content_scripts": [{
    "matches": ["*://*.stackoverflow.com/*"],
    "js": ["content.js"]
  }],
  "browser_action": {
    "default_title": "Test Extension"
  },

  "permissions": ["activeTab"]
}

How to create multidimensional array

I've written a one linear for this:

[1, 3, 1, 4, 1].reduceRight((x, y) => new Array(y).fill().map(() => JSON.parse(JSON.stringify(x))), 0);

I feel however I can spend more time to make a JSON.parse(JSON.stringify())-free version which is used for cloning here.

Btw, have a look at my another answer here.

SQL - Rounding off to 2 decimal places

Works in both with postgresql and Oracle

SELECT ename, sal, round(((sal * .15 + comm) /12),2) 
FROM emp where job = 'SALESMAN' 

Count number of occurrences by month

Use a pivot table. You can manually refresh a pivot table's data source by right-clicking on it and clicking refresh. Otherwise you can set up a worksheet_change macro - or just a refresh button. Pivot Table tutorial is here: http://chandoo.org/wp/2009/08/19/excel-pivot-tables-tutorial/

1) Create a Month column from your Date column (e.g. =TEXT(B2,"MMM") )

image1

2) Create a Year column from your Date column (e.g. =TEXT(B2,"YYYY") )

image2

3) Add a Count column, with "1" for each value

image3

4) Create a Pivot table with the fields, Count, Month and Year 5) Drag the Year and Month fields into Row Labels. Ensure that Year is above month so your Pivot table first groups by year, then by month 6) Drag the Count field into Values to create a Count of Count

image4

There are better tutorials I'm sure just google/bing "pivot table tutorial".

Inner join vs Where

If the query optimizer is doing its job right, there should be no difference between those queries. They are just two ways to specify the same desired result.

Using Chrome, how to find to which events are bound to an element

Edit: in lieu of my own answer, this one is quite excellent: How to debug JavaScript/jQuery event bindings with Firebug (or similar tool)

Google Chromes developer tools has a search function built into the scripts section

If you are unfamiliar with this tool: (just in case)

  • right click anywhere on a page (in chrome)
  • click 'Inspect Element'
  • click the 'Scripts' tab
  • Search bar in the top right

Doing a quick search for the #ID should take you to the binding function eventually.

Ex: searching for #foo would take you to

$('#foo').click(function(){ alert('bar'); })

enter image description here

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Use preventDefault() to stop the event of submit button and in ajax call success submit the form using submit():

$('#btnSave').click(function (e) {
    e.preventDefault(); // <------------------ stop default behaviour of button
    var element = this;    
    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.status == "Success") {
                alert("Done");
                $(element).closest("form").submit(); //<------------ submit form
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

delete word after or around cursor in VIM

Since there are so many ways to delete a word, let's illustrate them.

Assuming you edit:

foo-bar quux

and invoke a command while the cursor is on the 'a' in 'bar':

foo-bquux  # dw:  letters then spaces right of cursor
foo-quux   # daw: letters on both sides of cursor then spaces on the right 
foo- quux  # diw: letters on both sides of cursor
foo-bquux  # dW:  non-whitespace then spaces right of cursor
quux       # daW: non-whitespace on both sides of cursor then spaces on the right
 quux      # diW: non-whitespace on both sides of cursor

Get error message if ModelState.IsValid fails?

I have no idea if this is your problem, but if you add a user and then change the name of your application, that user will remain in the database (of course), but will be invalid (which is correct behavior). However, there will be no error added for this type of failure. The error list is empty, but ModelState.IsValid will return false for the login.

How do I create a unique constraint that also allows nulls?

CREATE UNIQUE NONCLUSTERED INDEX [UIX_COLUMN_NAME]
ON [dbo].[Employee]([Username] ASC) WHERE ([Username] IS NOT NULL) 
WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, 
DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF, 
MAXDOP = 0) ON [PRIMARY];

What is the difference between exit(0) and exit(1) in C?

The difference is the value returned to the environment is 0 in the former case and 1 in the latter case:

$ ./prog_with_exit_0
$ echo $?
0
$

and

$ ./prog_with_exit_1
$ echo $?
1
$

Also note that the macros value EXIT_SUCCESS and EXIT_FAILURE used as an argument to exit function are implementation defined but are usually set to respectively 0 and a non-zero number. (POSIX requires EXIT_SUCCESS to be 0). So usually exit(0) means a success and exit(1) a failure.

An exit function call with an argument in main function is equivalent to the statement return with the same argument.

Can angularjs routes have optional parameter values?

Like @g-eorge mention, you can make it like this:

module.config(['$routeProvider', function($routeProvider) {
$routeProvider.
  when('/users/:userId?', {templateUrl: 'template.tpl.html', controller: myCtrl})
}]);

You can also make as much as u need optional parameters.

How to embed images in email

As you are aware, everything passed as email message has to be textualized.

  • You must create an email with a multipart/mime message.
  • If you're adding a physical image, the image must be base 64 encoded and assigned a Content-ID (cid). If it's an URL, then the <img /> tag is sufficient (the url of the image must be linked to a Source ID).

A Typical email example will look like this:

From: foo1atbar.net
To: foo2atbar.net
Subject: A simple example
Mime-Version: 1.0
Content-Type: multipart/related; boundary="boundary-example"; type="text/html"

--boundary-example
Content-Type: text/html; charset="US-ASCII"

... text of the HTML document, which might contain a URI
referencing a resource in another body part, for example
through a statement such as:
<IMG SRC="cid:foo4atfoo1atbar.net" ALT="IETF logo">

--boundary-example
Content-Location: CID:somethingatelse ; this header is disregarded
Content-ID: <foo4atfoo1atbar.net>
Content-Type: IMAGE/GIF
Content-Transfer-Encoding: BASE64

R0lGODlhGAGgAPEAAP/////ZRaCgoAAAACH+PUNv
cHlyaWdodCAoQykgMTk5LiBVbmF1dGhvcml6ZWQgZHV
wbGljYXRpb24gcHJvaGliaXRlZC4A etc...

--boundary-example--

As you can see, the Content-ID: <foo4atfoo1atbar.net> ID is matched to the <IMG> at SRC="cid:foo4atfoo1atbar.net". That way, the client browser will render your image as a content and not as an attachement.

Hope this helps.

Why should I use IHttpActionResult instead of HttpResponseMessage?

I'd rather implement TaskExecuteAsync interface function for IHttpActionResult. Something like:

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);

        switch ((Int32)_respContent.Code)
        { 
            case 1:
            case 6:
            case 7:
                response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
                break;
            case 2:
            case 3:
            case 4:
                response = _request.CreateResponse(HttpStatusCode.BadRequest, _respContent);
                break;
        } 

        return Task.FromResult(response);
    }

, where _request is the HttpRequest and _respContent is the payload.

PHP - check if variable is undefined

You can use -

Ternary oprator to check wheather value set by POST/GET or not somthing like this

$value1 = $_POST['value1'] = isset($_POST['value1']) ? $_POST['value1'] : '';
$value2 = $_POST['value2'] = isset($_POST['value2']) ? $_POST['value2'] : '';
$value3 = $_POST['value3'] = isset($_POST['value3']) ? $_POST['value3'] : '';
$value4 = $_POST['value4'] = isset($_POST['value4']) ? $_POST['value4'] : '';

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

jQuery UI 1.10: dialog and zIndex option

You don't tell it, but you are using jQuery UI 1.10.

In jQuery UI 1.10 the zIndex option is removed:

Removed zIndex option

Similar to the stack option, the zIndex option is unnecessary with a proper stacking implementation. The z-index is defined in CSS and stacking is now controlled by ensuring the focused dialog is the last "stacking" element in its parent.

you have to use pure css to set the dialog "on the top":

.ui-dialog { z-index: 1000 !important ;}

you need the key !important to override the default styling of the element; this affects all your dialogs if you need to set it only for a dialog use the dialogClass option and style it.

If you need a modal dialog set the modal: true option see the docs:

If set to true, the dialog will have modal behavior; other items on the page will be disabled, i.e., cannot be interacted with. Modal dialogs create an overlay below the dialog but above other page elements.

You need to set the modal overlay with an higher z-index to do so use:

.ui-front { z-index: 1000 !important; }

for this element too.

Docker command can't connect to Docker daemon

Giving non-root access - from docker

Add the docker group if it doesn't already exist.

$ sudo groupadd docker

Add the connected user "${USER}" to the docker group.

Change the user name to match your preferred user.

You may have to logout and log back in again for this to take effect.

$ sudo gpasswd -a ${USER} docker

Restart the Docker daemon.

$ sudo service docker restart

Change language of Visual Studio 2017 RC

I didn't find a complete answer here

Firstly

You should install your preferred language

  1. Open the Visual Studio Installer.
  2. In installed products click on plus Dropdown menu
  3. click edit
  4. then click on language packs
  5. choose you preferred language and finally click on install

Secondly

  1. Go to Tools -> Options

    2.Select International Settings in Environment

    3.click on Menu and select you preferred language

    4.Click on Ok

    5.restart visual studio

Return Boolean Value on SQL Select Statement

Given that commonly 1 = true and 0 = false, all you need to do is count the number of rows, and cast to a boolean.

Hence, your posted code only needs a COUNT() function added:

SELECT CAST(COUNT(1) AS BIT) AS Expr1
FROM [User]
WHERE (UserID = 20070022)

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

Posed question

Responding to the question 'what metric should be used for multi-class classification with imbalanced data': Macro-F1-measure. Macro Precision and Macro Recall can be also used, but they are not so easily interpretable as for binary classificaion, they are already incorporated into F-measure, and excess metrics complicate methods comparison, parameters tuning, and so on.

Micro averaging are sensitive to class imbalance: if your method, for example, works good for the most common labels and totally messes others, micro-averaged metrics show good results.

Weighting averaging isn't well suited for imbalanced data, because it weights by counts of labels. Moreover, it is too hardly interpretable and unpopular: for instance, there is no mention of such an averaging in the following very detailed survey I strongly recommend to look through:

Sokolova, Marina, and Guy Lapalme. "A systematic analysis of performance measures for classification tasks." Information Processing & Management 45.4 (2009): 427-437.

Application-specific question

However, returning to your task, I'd research 2 topics:

  1. metrics commonly used for your specific task - it lets (a) to compare your method with others and understand if you do something wrong, and (b) to not explore this by yourself and reuse someone else's findings;
  2. cost of different errors of your methods - for example, use-case of your application may rely on 4- and 5-star reviewes only - in this case, good metric should count only these 2 labels.

Commonly used metrics. As I can infer after looking through literature, there are 2 main evaluation metrics:

  1. Accuracy, which is used, e.g. in

Yu, April, and Daryl Chang. "Multiclass Sentiment Prediction using Yelp Business."

(link) - note that the authors work with almost the same distribution of ratings, see Figure 5.

Pang, Bo, and Lillian Lee. "Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales." Proceedings of the 43rd Annual Meeting on Association for Computational Linguistics. Association for Computational Linguistics, 2005.

(link)

  1. MSE (or, less often, Mean Absolute Error - MAE) - see, for example,

Lee, Moontae, and R. Grafe. "Multiclass sentiment analysis with restaurant reviews." Final Projects from CS N 224 (2010).

(link) - they explore both accuracy and MSE, considering the latter to be better

Pappas, Nikolaos, Rue Marconi, and Andrei Popescu-Belis. "Explaining the Stars: Weighted Multiple-Instance Learning for Aspect-Based Sentiment Analysis." Proceedings of the 2014 Conference on Empirical Methods In Natural Language Processing. No. EPFL-CONF-200899. 2014.

(link) - they utilize scikit-learn for evaluation and baseline approaches and state that their code is available; however, I can't find it, so if you need it, write a letter to the authors, the work is pretty new and seems to be written in Python.

Cost of different errors. If you care more about avoiding gross blunders, e.g. assinging 1-star to 5-star review or something like that, look at MSE; if difference matters, but not so much, try MAE, since it doesn't square diff; otherwise stay with Accuracy.

About approaches, not metrics

Try regression approaches, e.g. SVR, since they generally outperforms Multiclass classifiers like SVC or OVA SVM.

Full Screen Theme for AppCompat

When you use Theme.AppCompat in your application you can use FullScreenTheme by adding the code below to styles.

<style name="Theme.AppCompat.Light.NoActionBar.FullScreen" parent="@style/Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

and also mention in your manifest file.

<activity
   android:name=".activities.FullViewActivity"
   android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen" 
/>

How to resolve this JNI error when trying to run LWJGL "Hello World"?

I had same issue using different dependancy what helped me is to set scope to compile.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>compile</scope>
    </dependency>

CSS3 equivalent to jQuery slideUp and slideDown?

Getting height transitions to work can be a bit tricky mainly because you have to know the height to animate for. This is further complicated by padding in the element to be animated.

Here is what I came up with:

use a style like this:

    .slideup, .slidedown {
        max-height: 0;            
        overflow-y: hidden;
        -webkit-transition: max-height 0.8s ease-in-out;
        -moz-transition: max-height 0.8s ease-in-out;
        -o-transition: max-height 0.8s ease-in-out;
        transition: max-height 0.8s ease-in-out;
    }
    .slidedown {            
        max-height: 60px ;  // fixed width                  
    }

Wrap your content into another container so that the container you're sliding has no padding/margins/borders:

  <div id="Slider" class="slideup">
    <!-- content has to be wrapped so that the padding and
            margins don't effect the transition's height -->
    <div id="Actual">
            Hello World Text
        </div>
  </div>

Then use some script (or declarative markup in binding frameworks) to trigger the CSS classes.

  $("#Trigger").click(function () {
    $("#Slider").toggleClass("slidedown slideup");
  });

Example here: http://plnkr.co/edit/uhChl94nLhrWCYVhRBUF?p=preview

This works fine for fixed size content. For a more generic soltution you can use code to figure out the size of the element when the transition is activated. The following is a jQuery plug-in that does just that:

$.fn.slideUpTransition = function() {
    return this.each(function() {
        var $el = $(this);
        $el.css("max-height", "0");
        $el.addClass("height-transition-hidden");
    });
};

$.fn.slideDownTransition = function() {
    return this.each(function() {
        var $el = $(this);
        $el.removeClass("height-transition-hidden");

        // temporarily make visible to get the size
        $el.css("max-height", "none");
        var height = $el.outerHeight();

        // reset to 0 then animate with small delay
        $el.css("max-height", "0");

        setTimeout(function() {
            $el.css({
                "max-height": height
            });
        }, 1);
    });
};

which can be triggered like this:

$("#Trigger").click(function () {

    if ($("#SlideWrapper").hasClass("height-transition-hidden"))
        $("#SlideWrapper").slideDownTransition();
    else
        $("#SlideWrapper").slideUpTransition();
});

against markup like this:

<style>
#Actual {
    background: silver;
    color: White;
    padding: 20px;
}

.height-transition {
    -webkit-transition: max-height 0.5s ease-in-out;
    -moz-transition: max-height 0.5s ease-in-out;
    -o-transition: max-height 0.5s ease-in-out;
    transition: max-height 0.5s ease-in-out;
    overflow-y: hidden;            
}
.height-transition-hidden {            
    max-height: 0;            
}
</style>
<div id="SlideWrapper" class="height-transition height-transition-hidden">
    <!-- content has to be wrapped so that the padding and
        margins don't effect the transition's height -->
    <div id="Actual">
     Your actual content to slide down goes here.
    </div>
</div>

Example: http://plnkr.co/edit/Wpcgjs3FS4ryrhQUAOcU?p=preview

I wrote this up recently in a blog post if you're interested in more detail:

http://weblog.west-wind.com/posts/2014/Feb/22/Using-CSS-Transitions-to-SlideUp-and-SlideDown

Cassandra cqlsh - connection refused

You need to edit cassandra.yaml on the node you are trying to connect to and set the node ip address for rpc_address and listen_address and restart Cassandra.

rpc_address is the address on which Cassandra listens to the client calls.

listen_address is the address on which Cassandra listens to the other Cassandra nodes.

DevTools failed to load SourceMap: Could not load content for chrome-extension

Right: it has nothing to do with your code. I've found two valid solutions to this warning (not just disabling it). To better understand what a SourceMap is, I suggest you check out this answer, where it explains how it's something that helps you debug:

The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.

  1. First solution: apparently, Mr Heelis was the closest one: you should add the .map file and there are some tools that help you with this problem (Grunt, Gulp and Google closure for example, quoting the answer). Otherwise you can download the .map file from official sites like Bootstrap, jquery, font-awesome, preload and so on.. (maybe installing things like popper or swiper by the npm command in a random folder and copying just the .map file in your js/css destination folder)

  2. Second solution (the one I used): add the source files using a CDN (here all the advantages of using a CDN). Using the Content delivery network (CDN) you can simply add the cdn link, instead of the path to your folder. You can find cdn on official websites (Bootstrap, jquery, popper, etc..) or you can easily search on some websites like cloudflare, cdnjs, etc..

How to search a specific value in all tables (PostgreSQL)?

Here's a pl/pgsql function that locates records where any column contains a specific value. It takes as arguments the value to search in text format, an array of table names to search into (defaults to all tables) and an array of schema names (defaults all schema names).

It returns a table structure with schema, name of table, name of column and pseudo-column ctid (non-durable physical location of the row in the table, see System Columns)

CREATE OR REPLACE FUNCTION search_columns(
    needle text,
    haystack_tables name[] default '{}',
    haystack_schema name[] default '{}'
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
begin
  FOR schemaname,tablename,columnname IN
      SELECT c.table_schema,c.table_name,c.column_name
      FROM information_schema.columns c
        JOIN information_schema.tables t ON
          (t.table_name=c.table_name AND t.table_schema=c.table_schema)
        JOIN information_schema.table_privileges p ON
          (t.table_name=p.table_name AND t.table_schema=p.table_schema
              AND p.privilege_type='SELECT')
        JOIN information_schema.schemata s ON
          (s.schema_name=t.table_schema)
      WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
        AND (c.table_schema=ANY(haystack_schema) OR haystack_schema='{}')
        AND t.table_type='BASE TABLE'
  LOOP
    FOR rowctid IN
      EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
       schemaname,
       tablename,
       columnname,
       needle
      )
    LOOP
      -- uncomment next line to get some progress report
      -- RAISE NOTICE 'hit in %.%', schemaname, tablename;
      RETURN NEXT;
    END LOOP;
 END LOOP;
END;
$$ language plpgsql;

See also the version on github based on the same principle but adding some speed and reporting improvements.

Examples of use in a test database:

  • Search in all tables within public schema:
select * from search_columns('foobar');
 schemaname | tablename | columnname | rowctid 
------------+-----------+------------+---------
 public     | s3        | usename    | (0,11)
 public     | s2        | relname    | (7,29)
 public     | w         | body       | (0,2)
(3 rows)
  • Search in a specific table:
 select * from search_columns('foobar','{w}');
 schemaname | tablename | columnname | rowctid 
------------+-----------+------------+---------
 public     | w         | body       | (0,2)
(1 row)
  • Search in a subset of tables obtained from a select:
select * from search_columns('foobar', array(select table_name::name from information_schema.tables where table_name like 's%'), array['public']);
 schemaname | tablename | columnname | rowctid 
------------+-----------+------------+---------
 public     | s2        | relname    | (7,29)
 public     | s3        | usename    | (0,11)
(2 rows)
  • Get a result row with the corresponding base table and and ctid:
select * from public.w where ctid='(0,2)';
 title |  body  |         tsv         
-------+--------+---------------------
 toto  | foobar | 'foobar':2 'toto':1

Variants

  • To test against a regular expression instead of strict equality, like grep, this part of the query:

    SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L

    may be changed to:

    SELECT ctid FROM %I.%I WHERE cast(%I as text) ~ %L

  • For case insensitive comparisons, you could write:

    SELECT ctid FROM %I.%I WHERE lower(cast(%I as text)) = lower(%L)

Android: How can I pass parameters to AsyncTask's onPreExecute()?

You can override the constructor. Something like:

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

    public MyAsyncTask(boolean showLoading) {
        super();
        // do stuff
    }

    // doInBackground() et al.
}

Then, when calling the task, do something like:

new MyAsyncTask(true).execute(maybe_other_params);

Edit: this is more useful than creating member variables because it simplifies the task invocation. Compare the code above with:

MyAsyncTask task = new MyAsyncTask();
task.showLoading = false;
task.execute();

Reusing output from last command in Bash

If you are on mac, and don't mind storing your output in the clipboard instead of writing to a variable, you can use pbcopy and pbpaste as a workaround.

For example, instead of doing this to find a file and diff its contents with another file:

$ find app -name 'one.php' 
/var/bar/app/one.php

$ diff /var/bar/app/one.php /var/bar/two.php

You could do this:

$ find app -name 'one.php' | pbcopy
$ diff $(pbpaste) /var/bar/two.php

The string /var/bar/app/one.php is in the clipboard when you run the first command.

By the way, pb in pbcopy and pbpaste stand for pasteboard, a synonym for clipboard.

Group by & count function in sqlalchemy

The documentation on counting says that for group_by queries it is better to use func.count():

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

Wait for Angular 2 to load/resolve model before rendering view/template

Set a local value with the observer

...also, don't forget to initialize the value with dummy data to avoid uninitialized errors.

export class ModelService {
    constructor() {
      this.mode = new Model();

      this._http.get('/api/v1/cats')
      .map(res => res.json())
      .subscribe(
        json => {
          this.model = new Model(json);
        },
        error => console.log(error);
      );
    }
}

This assumes Model, is a data model representing the structure of your data.

Model with no parameters should create a new instance with all values initialized (but empty). That way, if the template renders before the data is received it won't throw an error.

Ideally, if you want to persist the data to avoid unnecessary http requests you should put this in an object that has its own observer that you can subscribe to.

How to set default values in Rails?

In Ruby on Rails v3.2.8, using the after_initialize ActiveRecord callback, you can call a method in your model that will assign the default values for a new object.

after_initialize callback is triggered for each object that is found and instantiated by a finder, with after_initialize being triggered after new objects are instantiated as well (see ActiveRecord Callbacks).

So, IMO it should look something like:

class Foo < ActiveRecord::Base
  after_initialize :assign_defaults_on_new_Foo
  ...
  attr_accessible :bar
  ...
  private
  def assign_defaults_on_new_Foo
    # required to check an attribute for existence to weed out existing records
    self.bar = default_value unless self.attribute_whose_presence_has_been_validated
  end
end

Foo.bar = default_value for this instance unless the instance contains an attribute_whose_presence_has_been_validated previously on save/update. The default_value will then be used in conjunction with your view to render the form using the default_value for the bar attribute.

At best this is hacky...

EDIT - use 'new_record?' to check if instantiating from a new call

Instead of checking an attribute value, use the new_record? built-in method with rails. So, the above example should look like:

class Foo < ActiveRecord::Base
  after_initialize :assign_defaults_on_new_Foo, if: 'new_record?'
  ...
  attr_accessible :bar
  ...
  private
  def assign_defaults_on_new_Foo
    self.bar = default_value
  end
end

This is much cleaner. Ah, the magic of Rails - it's smarter than me.

Triggering change detection manually in Angular

I used accepted answer reference and would like to put an example, since Angular 2 documentation is very very hard to read, I hope this is easier:

  1. Import NgZone:

    import { Component, NgZone } from '@angular/core';
    
  2. Add it to your class constructor

    constructor(public zone: NgZone, ...args){}
    
  3. Run code with zone.run:

    this.zone.run(() => this.donations = donations)
    

How to create an Observable from static data similar to http one in Angular?

Things seem to have changed since Angular 2.0.0

import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
// ...
public fetchModel(uuid: string = undefined): Observable<string> {
  if(!uuid) {
    return new Observable<TestModel>((subscriber: Subscriber<TestModel>) => subscriber.next(new TestModel())).map(o => JSON.stringify(o));
  }
  else {
    return this.http.get("http://localhost:8080/myapp/api/model/" + uuid)
            .map(res => res.text());
  }
}

The .next() function will be called on your subscriber.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

.htaccess or .htpasswd equivalent on IIS?

This is the documentation that you want: http://msdn.microsoft.com/en-us/library/aa292114(VS.71).aspx

I guess the answer is, yes, there is an equivalent that will accomplish the same thing, integrated with Windows security.

Google Maps API Multiple Markers with Infowindows

You could use a closure. Just modify your code like this:

google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){ 
    return function() {
        infowindow.setContent(content);
        infowindow.open(map,marker);
    };
})(marker,content,infowindow));  

Here is the DEMO

How much memory can a 32 bit process access on a 64 bit operating system?

2 GB by default. If the application is large address space aware (linked with /LARGEADDRESSAWARE), it gets 4 GB (not 3 GB, see http://msdn.microsoft.com/en-us/library/aa366778.aspx)

They're still limited to 2 GB since many application depends on the top bit of pointers to be zero.

Search for highest key/index in an array

This should work fine

$arr = array( 1 => "A", 10 => "B", 5 => "C" );
max(array_keys($arr));

How to style a clicked button in CSS

If you just want the button to have different styling while the mouse is pressed you can use the :active pseudo class.

.button:active {
}

If on the other hand you want the style to stay after clicking you will have to use javascript.

How do I find Waldo with Mathematica?

I have a quick solution for finding Waldo using OpenCV.

I used the template matching function available in OpenCV to find Waldo.

To do this a template is needed. So I cropped Waldo from the original image and used it as a template.

enter image description here

Next I called the cv2.matchTemplate() function along with the normalized correlation coefficient as the method used. It returned a high probability at a single region as shown in white below (somewhere in the top left region):

enter image description here

The position of the highest probable region was found using cv2.minMaxLoc() function, which I then used to draw the rectangle to highlight Waldo:

enter image description here

Disabling buttons on react native

Just do this

<TouchableOpacity activeOpacity={disabled ? 1 : 0.7} onPress={!disabled && onPress}>
  <View>
    <Text>{text}</Text>
  </View>
</TouchableOpacity>

MySQL Where DateTime is greater than today

Remove the date() part

SELECT name, datum 
FROM tasks 
WHERE datum >= NOW()

and if you use a specific date, don't forget the quotes around it and use the proper format with :

SELECT name, datum 
FROM tasks 
WHERE datum >= '2014-05-18 15:00:00'

nginx - read custom header from upstream server

I was facing the same issue. I tried both $http_my_custom_header and $sent_http_my_custom_header but it did not work for me.

Although solved this issue by using $upstream_http_my_custom_header.

What is setContentView(R.layout.main)?

As per the documentation :

Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.

Your Launcher activity in the manifest first gets called and it set the layout view as specified in respective java files setContentView(R.layout.main);. Now this activity uses setContentView(R.layout.main) to set xml layout to that activity which will actually render as the UI of your activity.

How to change identity column values programmatically?

Identity modifying may fail depending on a number of factors, mainly revolving around the objects/relationships linked to the id column. It seems like db design is as issue here as id's should rarely if ever change (i'm sure you have your reasons and are cascasding the changes). If you really need to change id's from time to time, I'd suggest either creating a new dummy id column that isn't the primary key/autonumber that you can manage yourself and generate from the current values. Alternately, Chrisotphers idea above would be my other suggestion if you're having issues with allowing identity insert.

Good luck

PS it's not failing because the sequential order it's running in is trying to update a value in the list to an item that already exists in the list of ids? clutching at straws, perhaps add the number of rows+1, then if that works subtract the number of rows :-S

What is the proper way to check and uncheck a checkbox in HTML5?

In jQuery:

To check the checkbox:

$("#checkboxid").attr("checked","checked");

To uncheck the checkbox:

$("#checkboxid").removeAttr("checked");

The other answers hint at the solution and point you to documentation that after further digging will get you to this answer. Jukka K. Korpela has the reason this is the correct answer, basically I followed his link and then looked up the jQuery docs to get to that result. Just figured I'd save future people who find this article those extra steps.

Use placeholders in yaml

I suppose https://get-ytt.io/ would be an acceptable solution to your problem

How to set up devices for VS Code for a Flutter emulator

First, You have to install the Android Studio and Xcode to create phone emulator.

In VSCode you can use the Android IOS Emulator plugin to set the path of emulator to run.

How can I create a memory leak in Java?

There are many answers on how to create a memory leak in Java, but please note the point asked during the interview.

"how to create a memory leak with Java?" is an open-ended question, whose purpose is to evaluate the degree of experience a developer has.

If I ask you "Do you have experience troubleshooting memory leaks in Java?", your answer would be a simple "Yes". I would have then to follow up with "Could you give me examples where you hat to troubleshoot memory leaks?", to which you would give me one or two examples.

However, when the interviewer asks "how to create a memory leak with Java?" the expected answer should follow alongs these lines:

  • I've encountered a memory leak ... (say when) [that shows me experience]
  • The code that was causing it was... (explain code) [you fixed it yourself]
  • The fix I applied was based on ... (explain fix) [this gives me a chance to ask specifics about the fix]
  • The test I did was ... [gives me the chance of asking other testing methodologies]
  • I documented it this way ... [extra points. Good if you documented it]
  • So, it is reasonable to think that, if we follow this in reverse order, which is, get the code I fixed, and remove my fix, that we would have a memory leak.

When the developer fails to follow this line of thought I try to guide him/her asking "Could you give me an example of how could Java leak memory?", followed by "Did you ever have to fix any memory leak in Java?"

Note that I am not asking for an example on how to leak memory in Java. That would be silly. Who would be interested in a developer who can effectively write code that leaks memory?

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

I have added below code to terminate tasks you can use it. You may change the retry numbers.

package com.xxx.test.schedulers;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import com.xxx.core.XProvLogger;

@Component
class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> , ApplicationContextAware,BeanPostProcessor{


private ApplicationContext context;

public Logger logger = XProvLogger.getInstance().x;

public void onApplicationEvent(ContextClosedEvent event) {


    Map<String, ThreadPoolTaskScheduler> schedulers = context.getBeansOfType(ThreadPoolTaskScheduler.class);

    for (ThreadPoolTaskScheduler scheduler : schedulers.values()) {         
        scheduler.getScheduledExecutor().shutdown();
        try {
            scheduler.getScheduledExecutor().awaitTermination(20000, TimeUnit.MILLISECONDS);
            if(scheduler.getScheduledExecutor().isTerminated() || scheduler.getScheduledExecutor().isShutdown())
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has stoped");
            else{
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has not stoped normally and will be shut down immediately");
                scheduler.getScheduledExecutor().shutdownNow();
                logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has shut down immediately");
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    Map<String, ThreadPoolTaskExecutor> executers = context.getBeansOfType(ThreadPoolTaskExecutor.class);

    for (ThreadPoolTaskExecutor executor: executers.values()) {
        int retryCount = 0;
        while(executor.getActiveCount()>0 && ++retryCount<51){
            try {
                logger.info("Executer "+executor.getThreadNamePrefix()+" is still working with active " + executor.getActiveCount()+" work. Retry count is "+retryCount);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(!(retryCount<51))
            logger.info("Executer "+executor.getThreadNamePrefix()+" is still working.Since Retry count exceeded max value "+retryCount+", will be killed immediately");
        executor.shutdown();
        logger.info("Executer "+executor.getThreadNamePrefix()+" with active " + executor.getActiveCount()+" work has killed");
    }
}


@Override
public void setApplicationContext(ApplicationContext context)
        throws BeansException {
    this.context = context;

}


@Override
public Object postProcessAfterInitialization(Object object, String arg1)
        throws BeansException {
    return object;
}


@Override
public Object postProcessBeforeInitialization(Object object, String arg1)
        throws BeansException {
    if(object instanceof ThreadPoolTaskScheduler)
        ((ThreadPoolTaskScheduler)object).setWaitForTasksToCompleteOnShutdown(true);
    if(object instanceof ThreadPoolTaskExecutor)
        ((ThreadPoolTaskExecutor)object).setWaitForTasksToCompleteOnShutdown(true);
    return object;
}

}

Granting Rights on Stored Procedure to another user of Oracle

You can't do what I think you're asking to do.

The only privileges you can grant on procedures are EXECUTE and DEBUG.

If you want to allow user B to create a procedure in user A schema, then user B must have the CREATE ANY PROCEDURE privilege. ALTER ANY PROCEDURE and DROP ANY PROCEDURE are the other applicable privileges required to alter or drop user A procedures for user B. All are wide ranging privileges, as it doesn't restrict user B to any particular schema. User B should be highly trusted if granted these privileges.

EDIT:

As Justin mentioned, the way to give execution rights to A for a procedure owned by B:

GRANT EXECUTE ON b.procedure_name TO a;

"Post Image data using POSTMAN"

That's not how you send file on postman. What you did is sending a string which is the path of your image, nothing more.

What you should do is;

  1. After setting request method to POST, click to the 'body' tab.
  2. Select form-data. At first line, you'll see text boxes named key and value. Write 'image' to the key. You'll see value type which is set to 'text' as default. Make it File and upload your file.
  3. Then select 'raw' and paste your json file. Also just next to the binary choice, You'll see 'Text' is clicked. Make it JSON.

form-data section

raw section

You're ready to go.

In your Django view,

from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser
from rest_framework.decorators import parser_classes

@parser_classes((MultiPartParser, ))
class UploadFileAndJson(APIView):

    def post(self, request, format=None):
        thumbnail = request.FILES["file"]
        info = json.loads(request.data['info'])
        ...
        return HttpResponse()

How might I force a floating DIV to match the height of another floating DIV?

You can always use a background image to do it too. I tend to vote for this option 100% of the time as the only other perfect solution is the Jquery option.

As with using the outer div with a background color you'll end up having to have the content in both divs reaching the same height.

Add and remove attribute with jquery

If you want to do this, you need to save it in a variable first. So you don't need to use id to query this element every time.

var el = $("#page_navigation1");

$("#add").click(function(){
  el.attr("id","page_navigation1");
});     

$("#remove").click(function(){
  el.removeAttr("id");
});     

$http get parameters does not work

The 2nd parameter in the get call is a config object. You want something like this:

$http
    .get('accept.php', {
        params: {
            source: link,
            category_id: category
        }
     })
     .success(function (data,status) {
          $scope.info_show = data
     });

See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail

How to export the Html Tables data into PDF using Jspdf

Try to put

doc.fromHTML($('#target').get(0), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

instead of

doc.fromHTML($('#target').html(), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

How to change Tkinter Button state from disabled to normal?

You simply have to set the state of the your button self.x to normal:

self.x['state'] = 'normal'

or

self.x.config(state="normal")

This code would go in the callback for the event that will cause the Button to be enabled.


Also, the right code should be:

self.x = Button(self.dialog, text="Download", state=DISABLED, command=self.download)
self.x.pack(side=LEFT)

The method pack in Button(...).pack() returns None, and you are assigning it to self.x. You actually want to assign the return value of Button(...) to self.x, and then, in the following line, use self.x.pack().

Replace \n with actual new line in Sublime Text

What I did is simple and straightforward.

Enter Space or \n or whatever you want to find to Find.

Then hit Find All at right bottom corner, this will select all results.

Then hit enter on your keyboard and it will break all selected into new lines.

How do I abort/cancel TPL Tasks?

To answer Prerak K's question about how to use CancellationTokens when not using an anonymous method in Task.Factory.StartNew(), you pass the CancellationToken as a parameter into the method you're starting with StartNew(), as shown in the MSDN example here.

e.g.

var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;

Task.Factory.StartNew( () => DoSomeWork(1, token), token);

static void DoSomeWork(int taskNum, CancellationToken ct)
{
    // Do work here, checking and acting on ct.IsCancellationRequested where applicable, 

}

How to make picturebox transparent?

One way to do this is by changing the parent of the overlapping picture box to the PictureBox over which it is lapping. Since the Visual Studio designer doesn't allow you to add a PictureBox to a PictureBox, this will have to be done in your code (Form1.cs) and within the Intializing function:

public Form1()
{
    InitializeComponent();
    pictureBox7.Controls.Add(pictureBox8);
    pictureBox8.Location = new Point(0, 0);
    pictureBox8.BackColor = Color.Transparent;
}

Just change the picture box names to what ever you need. This should return:

enter image description here

Socket.io + Node.js Cross-Origin Request Blocked

After read a lot of subjetcs on StakOverflow and other forums, I found the working solution for me. This solution is for working without Express.

here are the prerequisites.


SERVER SIDE

// DEPENDENCIES
var fs       = require('fs'),
    winston  = require('winston'),
    path     = require('path');


// LOGS
const logger = winston.createLogger({
    level     : 'info',
    format    : winston.format.json(),
    transports: [
        new winston.transports.Console({ level: 'debug' }),
        new winston.transports.File({ filename: 'err.log', level: 'err' }),
        new winston.transports.File({ filename: 'combined.log' })
    ]
});


// CONSTANTS
const Port          = 9000,
      certsPath     = '/etc/letsencrypt/live/my.domain.com/';


// STARTING HTTPS SERVER 
var server = require('https').createServer({
    key:                fs.readFileSync(certsPath + 'privkey.pem'), 
    cert:               fs.readFileSync(certsPath + 'cert.pem'), 
    ca:                 fs.readFileSync(certsPath + 'chain.pem'), 
    requestCert:        false, 
    rejectUnauthorized: false 
},
(req, res) => {

    var filePath = '.' + req.url;
    logger.info('FILE ASKED : ' + filePath);

    // Default page for visitor calling directly URL
    if (filePath == './')
        filePath = './index.html';

    var extname = path.extname(filePath);
    var contentType = 'text/html';

    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
        case '.json':
            contentType = 'application/json';
            break;
        case '.png':
            contentType = 'image/png';
            break;      
        case '.jpg':
            contentType = 'image/jpg';
            break;
        case '.wav':
            contentType = 'audio/wav';
            break;
    }

    var headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'OPTIONS, POST, GET',
        'Access-Control-Max-Age': 2592000, // 30 days
        'Content-Type': contentType
    };

    fs.readFile(filePath, function(err, content) {
        if (err) {
            if(err.code == 'ENOENT'){
                fs.readFile('./errpages/404.html', function(err, content) {
                    res.writeHead(404, headers);
                    res.end(content, 'utf-8');
                });
            }
            else {
                fs.readFile('./errpages/500.html', function(err, content) {
                    res.writeHead(500, headers);
                    res.end(content, 'utf-8');
                });
            }
        }
        else {
            res.writeHead(200, headers);
            res.end(content, 'utf-8');
        }
    });

    if (req.method === 'OPTIONS') {
        res.writeHead(204, headers);
        res.end();
    }

}).listen(port); 


//OPENING SOCKET
var io = require('socket.io')(server).on('connection', function(s) {

    logger.info("SERVER > Socket opened from client");

    //... your code here

});

CLIENT SIDE

<script src="https://my.domain.com:port/js/socket.io.js"></script>
<script>
    $(document).ready(function() {

        $.socket = io.connect('https://my.domain.com:port', {
            secure: true // for SSL
        });

        //... your code here

    });
</script>

Filter by Dates in SQL

If your dates column does not contain time information, you could get away with:

WHERE dates BETWEEN '20121211' and '20121213'

However, given your dates column is actually datetime, you want this

WHERE dates >= '20121211'
  AND dates < '20121214'  -- i.e. 00:00 of the next day

Another option for SQL Server 2008 onwards that retains SARGability (ability to use index for good performance) is:

WHERE CAST(dates as date) BETWEEN '20121211' and '20121213'

Note: always use ISO-8601 format YYYYMMDD with SQL Server for unambiguous date literals.

How do I make a C++ macro behave like a function?

Create a block using

 #define MACRO(...) do { ... } while(false)

Do not add a ; after the while(false)

Best way to disable button in Twitter's Bootstrap

What ever attribute is added to the button/anchor/link to disable it, bootstrap is just adding style to it and user will still be able to click it while there is still onclick event. So my simple solution is to check if it is disabled and remove/add onclick event:

if (!('#button').hasAttr('disabled'))
 $('#button').attr('onclick', 'someFunction();');
else
 $('#button').removeattr('onclick');

How can I solve the error LNK2019: unresolved external symbol - function?

One option would be to include function.cpp in your UnitTest1 project, but that may not be the most ideal solution structure. The short answer to your problem is that when building your UnitTest1 project, the compiler and linker have no idea that function.cpp exists, and also have nothing to link that contains a definition of multiple. A way to fix this is making use of linking libraries.

Since your unit tests are in a different project, I'm assuming your intention is to make that project a standalone unit-testing program. With the functions you are testing located in another project, it's possible to build that project to either a dynamically or statically linked library. Static libraries are linked to other programs at build time, and have the extension .lib, and dynamic libraries are linked at runtime, and have the extension .dll. For my answer I'll prefer static libraries.

You can turn your first program into a static library by changing it in the projects properties. There should be an option under the General tab where the project is set to build to an executable (.exe). You can change this to .lib. The .lib file will build to the same place as the .exe.

In your UnitTest1 project, you can go to its properties, and under the Linker tab in the category Additional Library Directories, add the path to which MyProjectTest builds. Then, for Additional Dependencies under the Linker - Input tab, add the name of your static library, most likely MyProjectTest.lib.

That should allow your project to build. Note that by doing this, MyProjectTest will not be a standalone executable program unless you change its build properties as needed, which would be less than ideal.

Python SQL query string formatting

To avoid formatting entirely, I think a great solution is to use procedures.

Calling a procedure gives you the result of whatever query you want to put in this procedure. You can actually process multiple queries within a procedure. The call will just return the last query that was called.

MYSQL

DROP PROCEDURE IF EXISTS example;
 DELIMITER //
 CREATE PROCEDURE example()
   BEGIN
   SELECT 2+222+2222+222+222+2222+2222 AS this_is_a_really_long_string_test;
   END //
 DELIMITER;

#calling the procedure gives you the result of whatever query you want to put in this procedure. You can actually process multiple queries within a procedure. The call just returns the last query result
 call example;

Python

sql =('call example;')

Difference between MongoDB and Mongoose

One more difference I found with respect to both is that it is fairly easy to connect to multiple databases with mongodb native driver while you have to use work arounds in mongoose which still have some drawbacks.

So if you wanna go for a multitenant application, go for mongodb native driver.

Java AES encryption and decryption

Complete example of encrypting/Decrypting a huge video without throwing Java OutOfMemoryException and using Java SecureRandom for Initialization Vector generation. Also depicted storing key bytes to database and then reconstructing same key from those bytes.

https://stackoverflow.com/a/18892960/185022

How to make a HTTP request using Ruby on Rails?

You can use Ruby's Net::HTTP class:

require 'net/http'

url = URI.parse('http://www.example.com/index.html')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
  http.request(req)
}
puts res.body

How to Use Order By for Multiple Columns in Laravel 4?

You can do as @rmobis has specified in his answer, [Adding something more into it]

Using order by twice:

MyTable::orderBy('coloumn1', 'DESC')
    ->orderBy('coloumn2', 'ASC')
    ->get();

and the second way to do it is,

Using raw order by:

MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
    ->get();

Both will produce same query as follow,

SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC

As @rmobis specified in comment of first answer you can pass like an array to order by column like this,

$myTable->orders = array(
    array('column' => 'coloumn1', 'direction' => 'desc'), 
    array('column' => 'coloumn2', 'direction' => 'asc')
);

one more way to do it is iterate in loop,

$query = DB::table('my_tables');

foreach ($request->get('order_by_columns') as $column => $direction) {
    $query->orderBy($column, $direction);
}

$results = $query->get();

Hope it helps :)

How can I dismiss the on screen keyboard?

try using a text editing controller. at the begining,

    final myController = TextEditingController();
     @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

and in the on press event,

onPressed: () {
            commentController.clear();}

this will dismiss the keybord.

AVD Manager - Cannot Create Android Virtual Device

Had the exact same trouble... loading the ARM EABI v7a System Image worked for me too. Thanks very much.

I had previously seen on the Android SDK manager that a system image with the same name (ARM EABI v7a System Image) WAS installed on my system for a more recent SDK (Android 4.2). Consequently I thought it would negate the need to install the earlier Android 2.2 SDK ARM image, but apparently not.

How to reposition Chrome Developer Tools

Keyboard shortcut to toggle the docking position (side/bottom)

CTRL+SHIFT+D

And there are many shortcuts you can see them by going to

Settings » Shortcuts, as displayed here:
Settings screenshot

Alternatively, use CTRL + ? to go to the settings, from there one can reach the "Shortcuts" sub-item on the left or use the Official reference.

How do I pass data to Angular routed components?

I think since we don't have $rootScope kind of thing in angular 2 as in angular 1.x. We can use angular 2 shared service/class while in ngOnDestroy pass data to service and after routing take the data from the service in ngOnInit function:

Here I am using DataService to share hero object:

import { Hero } from './hero';
export class DataService {
  public hero: Hero;
}

Pass object from first page component:

 ngOnDestroy() {
    this.dataService.hero = this.hero; 
 }

Take object from second page component:

 ngOnInit() {
    this.hero = this.dataService.hero; 
 }

Here is an example: plunker

Using File.listFiles with FileNameExtensionFilter

Is there a specific reason you want to use FileNameExtensionFilter? I know this works..

private File[] getNewTextFiles() {
    return dir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".txt");
        }
    });
}

In Python, what happens when you import inside of a function?

It imports once when the function is called for the first time.

I could imagine doing it this way if I had a function in an imported module that is used very seldomly and is the only one requiring the import. Looks rather far-fetched, though...

jQuery first child of "this"

This can be done with a simple magic like this:

$(":first-child", element).toggleClass("redClass");

Reference: http://www.snoopcode.com/jquery/jquery-first-child-selector

Should I use `import os.path` or `import os`?

os.path works in a funny way. It looks like os should be a package with a submodule path, but in reality os is a normal module that does magic with sys.modules to inject os.path. Here's what happens:

  • When Python starts up, it loads a bunch of modules into sys.modules. They aren't bound to any names in your script, but you can access the already-created modules when you import them in some way.

    • sys.modules is a dict in which modules are cached. When you import a module, if it already has been imported somewhere, it gets the instance stored in sys.modules.
  • os is among the modules that are loaded when Python starts up. It assigns its path attribute to an os-specific path module.

  • It injects sys.modules['os.path'] = path so that you're able to do "import os.path" as though it was a submodule.

I tend to think of os.path as a module I want to use rather than a thing in the os module, so even though it's not really a submodule of a package called os, I import it sort of like it is one and I always do import os.path. This is consistent with how os.path is documented.


Incidentally, this sort of structure leads to a lot of Python programmers' early confusion about modules and packages and code organization, I think. This is really for two reasons

  1. If you think of os as a package and know that you can do import os and have access to the submodule os.path, you may be surprised later when you can't do import twisted and automatically access twisted.spread without importing it.

  2. It is confusing that os.name is a normal thing, a string, and os.path is a module. I always structure my packages with empty __init__.py files so that at the same level I always have one type of thing: a module/package or other stuff. Several big Python projects take this approach, which tends to make more structured code.

Leaflet - How to find existing markers, and delete markers?

In my case, I have various layer groups so that users can show/hide clusters of like type markers. But, in any case you delete an individual marker by looping over your layer groups to find and delete it. While looping, search for a marker with a custom attribute, in my case a 'key', added when the marker was added to the layer group. Add your 'key' just like adding a title attribute. Later this is gotten an a layer option. When you find that match, you .removeLayer() and it gets rid of that particular marker. Hope that helps you out!

eventsLayerGroup.addLayer(L.marker([tag.latitude, tag.longitude],{title:tag.title, layer:tag.layer, timestamp:tag.timestamp, key:tag.key, bounceOnAdd: true, icon: L.AwesomeMarkers.icon({icon: 'vignette', markerColor: 'blue', prefix: '', iconColor: 'white'}) }).bindPopup(customPopup(tag),customOptions).on('click', markerClick)); 

function removeMarker(id){
    var layerGroupsArray = [eventsLayerGroup,landmarksLayerGroup,travelerLayerGroup,marketplaceLayerGroup,myLayerGroup];
    $.each(layerGroupsArray, function (key, value) {
        value.eachLayer(function (layer) {
            if(typeof value !== "undefined"){
                if (layer.options.layer){
                    console.log(layer.options.key);
                    console.log(id);
                    if (id === layer.options.key){
                        value.removeLayer(layer);
                    }
                }
            }
        });
    });
}

WHERE Clause to find all records in a specific month

More one tip very simple. You also could use to_char function, look:

For Month:

to_char(happened_at , 'MM') = 01

For Year:
to_char(happened_at , 'YYYY') = 2009

For Day:

to_char(happened_at , 'DD') = 01

to_char funcion is suported by sql language and not by one specific database.

I hope help anybody more...

Abs!

best practice to generate random token for forgot password

The earlier version of the accepted answer (md5(uniqid(mt_rand(), true))) is insecure and only offers about 2^60 possible outputs -- well within the range of a brute force search in about a week's time for a low-budget attacker:

Since a 56-bit DES key can be brute-forced in about 24 hours, and an average case would have about 59 bits of entropy, we can calculate 2^59 / 2^56 = about 8 days. Depending on how this token verification is implemented, it might be possible to practically leak timing information and infer the first N bytes of a valid reset token.

Since the question is about "best practices" and opens with...

I want to generate identifier for forgot password

...we can infer that this token has implicit security requirements. And when you add security requirements to a random number generator, the best practice is to always use a cryptographically secure pseudorandom number generator (abbreviated CSPRNG).


Using a CSPRNG

In PHP 7, you can use bin2hex(random_bytes($n)) (where $n is an integer larger than 15).

In PHP 5, you can use random_compat to expose the same API.

Alternatively, bin2hex(mcrypt_create_iv($n, MCRYPT_DEV_URANDOM)) if you have ext/mcrypt installed. Another good one-liner is bin2hex(openssl_random_pseudo_bytes($n)).

Separating the Lookup from the Validator

Pulling from my previous work on secure "remember me" cookies in PHP, the only effective way to mitigate the aforementioned timing leak (typically introduced by the database query) is to separate the lookup from the validation.

If your table looks like this (MySQL)...

CREATE TABLE account_recovery (
    id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT 
    userid INTEGER(11) UNSIGNED NOT NULL,
    token CHAR(64),
    expires DATETIME,
    PRIMARY KEY(id)
);

... you need to add one more column, selector, like so:

CREATE TABLE account_recovery (
    id INTEGER(11) UNSIGNED NOT NULL AUTO_INCREMENT 
    userid INTEGER(11) UNSIGNED NOT NULL,
    selector CHAR(16),
    token CHAR(64),
    expires DATETIME,
    PRIMARY KEY(id),
    KEY(selector)
);

Use a CSPRNG When a password reset token is issued, send both values to the user, store the selector and a SHA-256 hash of the random token in the database. Use the selector to grab the hash and User ID, calculate the SHA-256 hash of the token the user provides with the one stored in the database using hash_equals().

Example Code

Generating a reset token in PHP 7 (or 5.6 with random_compat) with PDO:

$selector = bin2hex(random_bytes(8));
$token = random_bytes(32);

$urlToEmail = 'http://example.com/reset.php?'.http_build_query([
    'selector' => $selector,
    'validator' => bin2hex($token)
]);

$expires = new DateTime('NOW');
$expires->add(new DateInterval('PT01H')); // 1 hour

$stmt = $pdo->prepare("INSERT INTO account_recovery (userid, selector, token, expires) VALUES (:userid, :selector, :token, :expires);");
$stmt->execute([
    'userid' => $userId, // define this elsewhere!
    'selector' => $selector,
    'token' => hash('sha256', $token),
    'expires' => $expires->format('Y-m-d\TH:i:s')
]);

Verifying the user-provided reset token:

$stmt = $pdo->prepare("SELECT * FROM account_recovery WHERE selector = ? AND expires >= NOW()");
$stmt->execute([$selector]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($results)) {
    $calc = hash('sha256', hex2bin($validator));
    if (hash_equals($calc, $results[0]['token'])) {
        // The reset token is valid. Authenticate the user.
    }
    // Remove the token from the DB regardless of success or failure.
}

These code snippets are not complete solutions (I eschewed the input validation and framework integrations), but they should serve as an example of what to do.

How can I write a byte array to a file in Java?

To write a byte array to a file use the method

public void write(byte[] b) throws IOException

from BufferedOutputStream class.

java.io.BufferedOutputStream implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written.

For your example you need something like:

String filename= "C:/SO/SOBufferedOutputStreamAnswer";
BufferedOutputStream bos = null;
try {
//create an object of FileOutputStream
FileOutputStream fos = new FileOutputStream(new File(filename));

//create an object of BufferedOutputStream
bos = new BufferedOutputStream(fos);

KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
kgen.init(128); 
SecretKey key = kgen.generateKey(); 
byte[] encoded = key.getEncoded();

bos.write(encoded);

} 
// catch and handle exceptions...

How to convert currentTimeMillis to a date in Java?

The easiest way to do this is to use the Joda DateTime class and specify both the timestamp in milliseconds and the DateTimeZone you want.

I strongly recommend avoiding the built-in Java Date and Calendar classes; they're terrible.

How to provide a mysql database connection in single file in nodejs

I took a similar approach as Sean3z but instead I have the connection closed everytime i make a query.

His way works if it's only executed on the entry point of your app, but let's say you have controllers that you want to do a var db = require('./db'). You can't because otherwise everytime you access that controller you will be creating a new connection.

To avoid that, i think it's safer, in my opinion, to open and close the connection everytime.

here is a snippet of my code.

mysq_query.js

// Dependencies
var mysql   = require('mysql'),
    config  = require("../config");

/*
 * @sqlConnection
 * Creates the connection, makes the query and close it to avoid concurrency conflicts.
 */
var sqlConnection = function sqlConnection(sql, values, next) {

    // It means that the values hasnt been passed
    if (arguments.length === 2) {
        next = values;
        values = null;
    }

    var connection = mysql.createConnection(config.db);
    connection.connect(function(err) {
        if (err !== null) {
            console.log("[MYSQL] Error connecting to mysql:" + err+'\n');
        }
    });

    connection.query(sql, values, function(err) {

        connection.end(); // close the connection

        if (err) {
            throw err;
        }

        // Execute the callback
        next.apply(this, arguments);
    });
}

module.exports = sqlConnection;

Than you can use it anywhere just doing like

var mysql_query = require('path/to/your/mysql_query');
mysql_query('SELECT * from your_table where ?', {id: '1'}, function(err, rows)   {
    console.log(rows);
});

UPDATED: config.json looks like

{
        "db": {
        "user"     : "USERNAME",
        "password" : "PASSWORD",
        "database" : "DATABASE_NAME",
        "socketPath": "/tmp/mysql.sock"
    }
}

Hope this helps.

Multiple submit buttons in an HTML form

Change the previous button type into a button like this:

<input type="button" name="prev" value="Previous Page" />

Now the Next button would be the default, plus you could also add the default attribute to it so that your browser will highlight it like so:

<input type="submit" name="next" value="Next Page" default />

Concatenate two string literals

Your second example does not work because there is no operator + for two string literals. Note that a string literal is not of type string, but instead is of type const char *. Your second example will work if you revise it like this:

const string message = string("Hello") + ",world" + exclam;

Get max and min value from array in JavaScript

arr = [9,4,2,93,6,2,4,61,1];
ArrMax = Math.max.apply(Math, arr);

HTTP Headers for File Downloads

Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):

The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data in a file

So I'd go for that one.

Postgresql GROUP_CONCAT equivalent?

This is probably a good starting point (version 8.4+ only):

SELECT id_field, array_agg(value_field1), array_agg(value_field2)
FROM data_table
GROUP BY id_field

array_agg returns an array, but you can CAST that to text and edit as needed (see clarifications, below).

Prior to version 8.4, you have to define it yourself prior to use:

CREATE AGGREGATE array_agg (anyelement)
(
    sfunc = array_append,
    stype = anyarray,
    initcond = '{}'
);

(paraphrased from the PostgreSQL documentation)

Clarifications:

  • The result of casting an array to text is that the resulting string starts and ends with curly braces. Those braces need to be removed by some method, if they are not desired.
  • Casting ANYARRAY to TEXT best simulates CSV output as elements that contain embedded commas are double-quoted in the output in standard CSV style. Neither array_to_string() or string_agg() (the "group_concat" function added in 9.1) quote strings with embedded commas, resulting in an incorrect number of elements in the resulting list.
  • The new 9.1 string_agg() function does NOT cast the inner results to TEXT first. So "string_agg(value_field)" would generate an error if value_field is an integer. "string_agg(value_field::text)" would be required. The array_agg() method requires only one cast after the aggregation (rather than a cast per value).

Twitter Bootstrap button click to toggle expand/collapse text section above button

Elaborating a bit more on Taylor Gautier's reply (sorry, I dont have enough reputation to add a comment), I'd reply to Dean Richardson on how to do what he wanted, without any additional JS code. Pure CSS.

You would replace his .btn with the following:

<a class="btn showdetails" data-toggle="collapse" data-target="#viewdetails"></a>

And add a small CSS for when the content is displayed:

.in.collapse+a.btn.showdetails:before { 
    content:'Hide details «';
}
.collapse+a.btn.showdetails:before { 
    content:'Show details »'; 
}

Here is his modified example

What is the difference between min SDK version/target SDK version vs. compile SDK version?

The formula is

minSdkVersion <= targetSdkVersion <= compileSdkVersion

minSdkVersion - is a marker that defines a minimum Android version on which application will be able to install. Also it is used by Lint to prevent calling API that doesn’t exist. Also it has impact on Build Time. So you can use build flavors to override minSdkVersion to maximum during the development. It will help to make build faster using all improvements that the Android team provides for us. For example some features Java 8 are available only from specific version of minSdkVersion.

targetSdkVersion - If AndroidOS version is >= targetSdkVersion it says Android system to turn on specific(new) behavior changes. *Please note that some of new behaviors will be turned on by default even if thought targetSdkVersion is <, you should read official doc.

For example:

  • Starting in Android 6.0 (API level 23) Runtime Permissions were introduced. If you set targetSdkVersion to 22 or lower your application does not ask a user for some permission in run time.

  • Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear. On devices running Android 7.1 (API level 25) and lower, users can manage notifications on a per-app basis only (effectively each app only has one channel on Android 7.1 and lower).

  • Starting in Android 9 (API level 28), Web-based data directories separated by process. If targetSdkVersion is 28+ and you create several WebView in different processes you will get java.lang.RuntimeException

compileSdkVersion - actually it is SDK Platform version and tells Gradle which Android SDK use to compile. When you want to use new features or debug .java files from Android SDK you should take care of compileSdkVersion. One more example is using AndroidX that forces to use compileSdkVersion - level 28. compileSdkVersion is not included in your APK: it is purely used at compile time. Changing your compileSdkVersion does not change runtime behavior. It can generate for example new compiler warnings/errors. Therefore it is strongly recommended that you always compile with the latest SDK. You’ll get all the benefits of new compilation checks on existing code, avoid newly deprecated APIs, and be ready to use new APIs. One more fact is compileSdkVersion >= Support Library version

You can read more about it here. Also I would recommend you to take a look at the example of migration to Android 8.0.

[buildToolsVersion]

Why does the JFrame setSize() method not set the size correctly?

JFrame SetSize() contains the the Area + Border.

I think you have to set the size of ContentPane of that

jFrame.getContentPane().setSize(800,400);

So I would advise you to use JPanel embedded in a JFrame and you draw on that JPanel. This would minimize your problem.

JFrame jf = new JFrame();
JPanel jp = new JPanel();
jp.setPreferredSize(new Dimension(400,800));// changed it to preferredSize, Thanks!
jf.getContentPane().add( jp );// adding to content pane will work here. Please read the comment bellow.
jf.pack();

I am reading this from Javadoc

The JFrame class is slightly incompatible with Frame. Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case. For example, to add a child to an AWT frame you'd write:

frame.add(child);

However using JFrame you need to add the child to the JFrame's content pane instead:

frame.getContentPane().add(child);

How to get all elements which name starts with some string?

You can use getElementsByName("input") to get a collection of all the inputs on the page. Then loop through the collection, checking the name on the way. Something like this:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>

</head>
<body>

  <input name="q1_a" type="text" value="1A"/>
  <input name="q1_b" type="text" value="1B"/>
  <input name="q1_c" type="text" value="1C"/>
  <input name="q2_d" type="text" value="2D"/>

  <script type="text/javascript">
  var inputs = document.getElementsByTagName("input");
  for (x = 0 ; x < inputs.length ; x++){
    myname = inputs[x].getAttribute("name");
    if(myname.indexOf("q1_")==0){
      alert(myname);
      // do more stuff here
       }
    }
    </script>
</body>
</html>

Demo

Differences between "java -cp" and "java -jar"?

Like already said, the -cp is just for telling the jvm in the command line which class to use for the main thread and where it can find the libraries (define classpath). In -jar it expects the class-path and main-class to be defined in the jar file manifest. So other is for defining things in command line while other finding them inside the jar manifest. There is no difference in performance. You can't use them at the same time, -jar will override the -cp.

Though even if you use -cp, it will still check the manifest file. So you can define some of the class-paths in the manifest and some in the command line. This is particularly useful when you have a dependency on some 3rd party jar, which you might not provide with your build or don't want to provide (expecting it to be found already in the system where it's to be installed for example). So you can use it to provide external jars. It's location may vary between systems or it may even have a different version on different system (but having the same interfaces). This way you can build the app with other version and add the actual 3rd party dependency to class-path on the command line when running it on different systems.

How get all values in a column using PHP?

Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.


This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php

$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $storeArray[] =  $row['names'];  
}
// now $storeArray will have all the names.

Find Oracle JDBC driver in Maven repository

You can find a Github simple sample project for use a Oracle JDBC Driver on Maven Project here.

You can find all explication for your continous integration + a sample and run on Travis-CI.

DEMO

How to Validate Google reCaptcha on Form Submit

One issue I came up with that prevented these two files from working correctly was with my php.ini file for the website. Make sure this property is properly set, as follows:

allow_url_fopen = 

Angular 4.3 - HttpClient set params

In more recent versions of @angular/common/http (5.0 and up, by the looks of it), you can use the fromObject key of HttpParamsOptions to pass the object straight in:

let httpParams = new HttpParams({ fromObject: { aaa: 111, bbb: 222 } });

This just runs a forEach loop under the hood, though:

this.map = new Map<string, string[]>();
Object.keys(options.fromObject).forEach(key => {
  const value = (options.fromObject as any)[key];
  this.map !.set(key, Array.isArray(value) ? value : [value]);
});

JSON Parse File Path

If Resources is the root path, best way to access file.json would be via /data/file.json

How to git ignore subfolders / subdirectories?

You can use .gitignore in the top level to ignore all directories in the project with the same name. For example:

Debug/
Release/

This should update immediately so it's visible when you do git status. Ensure that these directories are not already added to git, as that will override the ignores.

How to have multiple conditions for one if statement in python

Might be a bit odd or bad practice but this is one way of going about it.

(arg1, arg2, arg3) = (1, 2, 3)

if (arg1 == 1)*(arg2 == 2)*(arg3 == 3):
    print('Example.')

Anything multiplied by 0 == 0. If any of these conditions fail then it evaluates to false.

Why use a ReentrantLock if one can use synchronized(this)?

I think the wait/notify/notifyAll methods don't belong on the Object class as it pollutes all objects with methods that are rarely used. They make much more sense on a dedicated Lock class. So from this point of view, perhaps it's better to use a tool that is explicitly designed for the job at hand - ie ReentrantLock.

Random "Element is no longer attached to the DOM" StaleElementReferenceException

I was facing the same problem today and made up a wrapper class, which checks before every method if the element reference is still valid. My solution to retrive the element is pretty simple so i thought i'd just share it.

private void setElementLocator()
{
    this.locatorVariable = "selenium_" + DateTimeMethods.GetTime().ToString();
    ((IJavaScriptExecutor)this.driver).ExecuteScript(locatorVariable + " = arguments[0];", this.element);
}

private void RetrieveElement()
{
    this.element = (IWebElement)((IJavaScriptExecutor)this.driver).ExecuteScript("return " + locatorVariable);
}

You see i "locate" or rather save the element in a global js variable and retrieve the element if needed. If the page gets reloaded this reference will not work anymore. But as long as only changes are made to doom the reference stays. And that should do the job in most cases.

Also it avoids re-searching the element.

John

Click events on Pie Charts in Chart.js

  var ctx = document.getElementById('pie-chart').getContext('2d');
 var myPieChart = new Chart(ctx, {
                // The type of chart we want to create
                type: 'pie',

            });

             //define click event
  $("#pie-chart").click(
            function (evt) {
                var activePoints = myPieChart.getElementsAtEvent(evt);
                var labeltag = activePoints[0]._view.label;

                      });

How to create exe of a console application

The following steps are necessary to create .exe i.e. executable files which are as 1) Open visual studio framework 2) Then, create a new project or application 3) Build or execute your application by pressing F5

List of Java processes

ps aux | grep java

or

$ ps -fea|grep -i java

Saving the PuTTY session logging

I always have to check my cheatsheet :-)

Step 1: right-click on the top of putty window and select 'Change settings'.

Step 2: type the name of the session and save.

That's it!. Enjoy!

Can I create links with 'target="_blank"' in Markdown?

I don't think there is a markdown feature.

Though there may be other options available if you want to open links which point outside your own site automatically with JavaScript.

var links = document.links;

for (var i = 0, linksLength = links.length; i < linksLength; i++) {
   if (links[i].hostname != window.location.hostname) {
       links[i].target = '_blank';
   } 
}

jsFiddle.

If you're using jQuery it's a tad simpler...

$(document.links).filter(function() {
    return this.hostname != window.location.hostname;
}).attr('target', '_blank');

jsFiddle.

Display Two <div>s Side-by-Side

I removed the float from the second div to make it work.

http://jsfiddle.net/rhEyM/2/

How to set JAVA_HOME for multiple Tomcat instances?

If you are a Windows user, put the content below in a setenv.bat file that you must create in Tomcat bin directory.

set JAVA_HOME=C:\Program Files\Java\jdk1.6.x

If you are a Linux user, put the content below in a setenv.sh file that you must create in Tomcat bin directory.

JAVA_HOME=/usr/java/jdk1.6.x

How to send a JSON object over Request with Android?

There's a surprisingly nice library for Android HTTP available at the link below:

http://loopj.com/android-async-http/

Simple requests are very easy:

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
        System.out.println(response);
    }
});

To send JSON (credit to `voidberg' at https://github.com/loopj/android-async-http/issues/125):

// params is a JSONObject
StringEntity se = null;
try {
    se = new StringEntity(params.toString());
} catch (UnsupportedEncodingException e) {
    // handle exceptions properly!
}
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

client.post(null, "www.example.com/objects", se, "application/json", responseHandler);

It's all asynchronous, works well with Android and safe to call from your UI thread. The responseHandler will run on the same thread you created it from (typically, your UI thread). It even has a built-in resonseHandler for JSON, but I prefer to use google gson.

How can I access Google Sheet spreadsheets only with Javascript?

For this type of thing you should use Google Fusion Tables. The API is designed for that purpose.

How to recover closed output window in netbeans?

in Netbeans 7.4 try Window -> Output OR Ctrl + 4

How do I install Composer on a shared hosting?

Most of the time you can't - depending on the host. You can contact the support team where your hosting is subscribed to, and if they confirmed that it is really not allowed, you can just set up the composer on your dev machine, and commit and push all dependencies to your live server using Git or whatever you prefer.

pass JSON to HTTP POST Request

Now with new JavaScript version (ECMAScript 6 http://es6-features.org/#ClassDefinition) there is a better way to submit requests using nodejs and Promise request (http://www.wintellect.com/devcenter/nstieglitz/5-great-features-in-es6-harmony)

Using library: https://github.com/request/request-promise

npm install --save request
npm install --save request-promise

client:

//Sequential execution for node.js using ES6 ECMAScript
var rp = require('request-promise');

rp({
    method: 'POST',
    uri: 'http://localhost:3000/',
    body: {
        val1 : 1,
        val2 : 2
    },
    json: true // Automatically stringifies the body to JSON
}).then(function (parsedBody) {
        console.log(parsedBody);
        // POST succeeded...
    })
    .catch(function (err) {
        console.log(parsedBody);
        // POST failed...
    });

server:

var express = require('express')
    , bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.post('/', function(request, response){
    console.log(request.body);      // your JSON

    var jsonRequest = request.body;
    var jsonResponse = {};

    jsonResponse.result = jsonRequest.val1 + jsonRequest.val2;

    response.send(jsonResponse);
});


app.listen(3000);

How to make a GridLayout fit screen size

Do you know View.getViewTreeObserver().addOnGlobalLayoutListener()

By this you can calculate the sizes.

I achieve your UI effect by GridView:

GridView g;
g.setNumColumns(2);
g.setStretchMode(GridView.STRETCH_SPACING_UNIFORM);

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Response you are getting is in object form i.e.

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

Replace below line of code :

List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))

with

Post post = gson.fromJson(reader, Post.class);

Error on line 2 at column 1: Extra content at the end of the document

I think you are creating a document that looks like this:

<mycatch>
    ....
</mycatch>
<mycatch>
    ....
</mycatch>

This is not a valid XML document as it has more than one root element. You must have a single top-level element, as in

<mydocument>      
  <mycatch>
      ....
  </mycatch>
  <mycatch>
      ....
  </mycatch>
  ....
</mydocument>

How to map and remove nil values in Ruby

If you wanted a looser criterion for rejection, for example, to reject empty strings as well as nil, you could use:

[1, nil, 3, 0, ''].reject(&:blank?)
 => [1, 3, 0] 

If you wanted to go further and reject zero values (or apply more complex logic to the process), you could pass a block to reject:

[1, nil, 3, 0, ''].reject do |value| value.blank? || value==0 end
 => [1, 3]

[1, nil, 3, 0, '', 1000].reject do |value| value.blank? || value==0 || value>10 end
 => [1, 3]

jQuery: How to get to a particular child of a parent?

$(this).parent()

Tree traversal is fun

$(this).parent().siblings(".something1");

$(this).parent().prev(); // if you always want the parent's previous sibling

$(this).parents(".box").children(".something1");

And much more ways, you might find these docs helpful.

aspx page to redirect to a new page

Redirect aspx :

<iframe>

    <script runat="server">
    private void Page_Load(object sender, System.EventArgs e)
    {
    Response.Status = "301 Moved Permanently";
    Response.AddHeader("Location","http://www.avsapansiyonlar.com/altinkum-tatil-konaklari.aspx");
    }
    </script>

</iframe>

HTML Tags in Javascript Alert() method

alert() doesn't support HTML, but you have some alternatives to format your message.

You can use Unicode characters as others stated, or you can make use of the ES6 Template literals. For example:

...
.catch(function (error) {
  const alertMessage = `Error retrieving resource. Please make sure:
    • the resource server is accessible
    • you're logged in

    Error: ${error}`;
  window.alert(alertMessage);
}

Output: enter image description here

As you can see, it maintains the line breaks and spaces that we included in the variable, with no extra characters.

jQuery detect if string contains something

You get the value of the textarea, use it :

$('.type').keyup(function() {
    var v = $('.type').val(); // you'd better use this.value here
    if (v.indexOf('> <')!=-1) {
       console.log('contains > <');        
    }
});

Field 'id' doesn't have a default value?

I was getting error while ExecuteNonQuery() resolved with adding AutoIncrement to Primary Key of my table. In your case if you don't want to add primary key then we must need to assign value to primary key.

ALTER TABLE `t1` 
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT ;

How do malloc() and free() work?

OK some answers about malloc were already posted.

The more interesting part is how free works (and in this direction, malloc too can be understood better).

In many malloc/free implementations, free does normally not return the memory to the operating system (or at least only in rare cases). The reason is that you will get gaps in your heap and thus it can happen, that you just finish off your 2 or 4 GB of virtual memory with gaps. This should be avoided, since as soon as the virtual memory is finished, you will be in really big trouble. The other reason is, that the OS can only handle memory chunks that are of a specific size and alignment. To be specific: Normally the OS can only handle blocks that the virtual memory manager can handle (most often multiples of 512 bytes e.g. 4KB).

So returning 40 Bytes to the OS will just not work. So what does free do?

Free will put the memory block in its own free block list. Normally it also tries to meld together adjacent blocks in the address space. The free block list is just a circular list of memory chunks which have some administrative data in the beginning. This is also the reason why managing very small memory elements with the standard malloc/free is not efficient. Every memory chunk needs additional data and with smaller sizes more fragmentation happens.

The free-list is also the first place that malloc looks at when a new chunk of memory is needed. It is scanned before it calls for new memory from the OS. When a chunk is found that is bigger than the needed memory, it is divided into two parts. One is returned to caller, the other is put back into the free list.

There are many different optimizations to this standard behaviour (for example for small chunks of memory). But since malloc and free must be so universal, the standard behaviour is always the fallback when alternatives are not usable. There are also optimizations in handling the free-list — for example storing the chunks in lists sorted by sizes. But all optimizations also have their own limitations.

Why does your code crash:

The reason is that by writing 9 chars (don't forget the trailing null byte) into an area sized for 4 chars, you will probably overwrite the administrative-data stored for another chunk of memory that resides "behind" your chunk of data (since this data is most often stored "in front" of the memory chunks). When free then tries to put your chunk into the free list, it can touch this administrative-data and therefore stumble over an overwritten pointer. This will crash the system.

This is a rather graceful behaviour. I have also seen situations where a runaway pointer somewhere has overwritten data in the memory-free-list and the system did not immediately crash but some subroutines later. Even in a system of medium complexity such problems can be really, really hard to debug! In the one case I was involved, it took us (a larger group of developers) several days to find the reason of the crash -- since it was in a totally different location than the one indicated by the memory dump. It is like a time-bomb. You know, your next "free" or "malloc" will crash, but you don't know why!

Those are some of the worst C/C++ problems, and one reason why pointers can be so problematic.

Click event on select option element in chrome

<select id="myselect">
    <option value="0">sometext</option>
    <option value="2">Ready for Review</option>
    <option value="3">Registration Date</option>
</select>

$('#myselect').change(function() {
    if($('#myselect option:selected').val() == 0) {
    ...
    }
    else {
    ...
    }
});

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

mysql datetime comparison

...this is obviously performing a 'string' comparison

No - if the date/time format matches the supported format, MySQL performs implicit conversion to convert the value to a DATETIME, based on the column it is being compared to. Same thing happens with:

WHERE int_column = '1'

...where the string value of "1" is converted to an INTeger because int_column's data type is INT, not CHAR/VARCHAR/TEXT.

If you want to explicitly convert the string to a DATETIME, the STR_TO_DATE function would be the best choice:

WHERE expires_at <= STR_TO_DATE('2010-10-15 10:00:00', '%Y-%m-%d %H:%i:%s')

How can I get onclick event on webview in android?

WebViewClient.shouldOverrideUrlLoading might be helpful. We are having a similar requirement in one of our app. Not tried yet.

How to change Visual Studio 2012,2013 or 2015 License Key?

For those of you using Visual Studio 2017 Professional, the registry key is:

HKCR\Licenses\5C505A59-E312-4B89-9508-E162F8150517

I also recommend you first export the registry key, before you delete it, so you'll have a backup if you accidentally delete the wrong key.

Struct memory layout in C

You can start by reading the data structure alignment wikipedia article to get a better understanding of data alignment.

From the wikipedia article:

Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

From 6.54.8 Structure-Packing Pragmas of the GCC documentation:

For compatibility with Microsoft Windows compilers, GCC supports a set of #pragma directives which change the maximum alignment of members of structures (other than zero-width bitfields), unions, and classes subsequently defined. The n value below always is required to be a small power of two and specifies the new alignment in bytes.

  1. #pragma pack(n) simply sets the new alignment.
  2. #pragma pack() sets the alignment to the one that was in effect when compilation started (see also command line option -fpack-struct[=] see Code Gen Options).
  3. #pragma pack(push[,n]) pushes the current alignment setting on an internal stack and then optionally sets the new alignment.
  4. #pragma pack(pop) restores the alignment setting to the one saved at the top of the internal stack (and removes that stack entry). Note that #pragma pack([n]) does not influence this internal stack; thus it is possible to have #pragma pack(push) followed by multiple #pragma pack(n) instances and finalized by a single #pragma pack(pop).

Some targets, e.g. i386 and powerpc, support the ms_struct #pragma which lays out a structure as the documented __attribute__ ((ms_struct)).

  1. #pragma ms_struct on turns on the layout for structures declared.
  2. #pragma ms_struct off turns off the layout for structures declared.
  3. #pragma ms_struct reset goes back to the default layout.

How to export a CSV to Excel using Powershell

This topic really helped me, so I'd like to share my improvements. All credits go to the nixda, this is based on his answer.

For those who need to convert multiple csv's in a folder, just modify the directory. Outputfilenames will be identical to input, just with another extension.

Take care of the cleanup in the end, if you like to keep the original csv's you might not want to remove these.

Can be easily modifed to save the xlsx in another directory.

$workingdir = "C:\data\*.csv"
$csv = dir -path $workingdir
foreach($inputCSV in $csv){
$outputXLSX = $inputCSV.DirectoryName + "\" + $inputCSV.Basename + ".xlsx"
### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application 
$excel.DisplayAlerts = $False
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)

### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)

### Set the delimiter (, or ;) according to your regional settings
### $Excel.Application.International(3) = ,
### $Excel.Application.International(5) = ;
$query.TextFileOtherDelimiter = $Excel.Application.International(5)

### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType  = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

### Execute & delete the import query
$query.Refresh()
$query.Delete()

### Save & close the Workbook as XLSX. Change the output extension for Excel 2003
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()
}
## To exclude an item, use the '-exclude' parameter (wildcards if needed)
remove-item -path $workingdir -exclude *Crab4dq.csv

Is it possible to center text in select box?

That's for align right. Try it:

select{
    text-align-last:right;
    padding-right: 29px;
    direction: rtl;
}

the browser support for the text-align-last attribute can be found here: https://www.w3schools.com/cssref/css3_pr_text-align-last.asp It looks like only Safari is still not supporting it.

Get the position of a div/span tag

This function will tell you the x,y position of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.

function getPos(el) {
    // yay readability
    for (var lx=0, ly=0;
         el != null;
         lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
    return {x: lx,y: ly};
}

However, if you just wanted the x,y position of the element relative to its container, then all you need is:

var x = el.offsetLeft, y = el.offsetTop;

To put an element directly below this one, you'll also need to know its height. This is stored in the offsetHeight/offsetWidth property.

var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;

How can I disable notices and warnings in PHP within the .htaccess file?

I used ini_set('display_errors','off'); and it worked great.

Java: Convert a String (representing an IP) to InetAddress

From the documentation of InetAddress.getByName(String host):

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

So you can use it.

Serving favicon.ico in ASP.NET MVC

Placing favicon.ico in the root of your domain only really affects IE5, IIRC. For more modern browsers you should be able to include a link tag to point to another directory:

<link rel="SHORTCUT ICON" href="http://www.mydomain.com/content/favicon.ico"/>

You can also use non-ico files for browsers other than IE, for which I'd maybe use the following conditional statement to serve a PNG to FF,etc, and an ICO to IE:

<link rel="icon" type="image/png" href="http://www.mydomain.com/content/favicon.png" />
<!--[if IE]>
<link rel="shortcut icon" href="http://www.mydomain.com/content/favicon.ico" type="image/vnd.microsoft.icon" />
<![endif]-->

Line break in HTML with '\n'

You can use CSS white-space property for \n. You can also preserve the tabs as in \t.

For line break \n:

white-space: pre-line;

For line break \n and tabs \t:

white-space: pre-wrap;

_x000D_
_x000D_
document.getElementById('just-line-break').innerHTML = 'Testing 1\nTesting 2\n\tNo tab';_x000D_
_x000D_
document.getElementById('line-break-and-tab').innerHTML = 'Testing 1\nTesting 2\n\tWith tab';
_x000D_
#just-line-break {_x000D_
  white-space: pre-line;_x000D_
}_x000D_
_x000D_
#line-break-and-tab {_x000D_
  white-space: pre-wrap;_x000D_
}
_x000D_
<div id="just-line-break"></div>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<div id="line-break-and-tab"></div>
_x000D_
_x000D_
_x000D_

Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

Adding to @behzad.nouri 's answer - we can create a helper routine to handle this common scenario:

def csvDf(dat,**kwargs): 
  from numpy import array
  data = array(dat)
  if data is None or len(data)==0 or len(data[0])==0:
    return None
  else:
    return pd.DataFrame(data[1:,1:],index=data[1:,0],columns=data[0,1:],**kwargs)

Let's try it out:

data = [['','a','b','c'],['row1','row1cola','row1colb','row1colc'],
     ['row2','row2cola','row2colb','row2colc'],['row3','row3cola','row3colb','row3colc']]
csvDf(data)

In [61]: csvDf(data)
Out[61]:
             a         b         c
row1  row1cola  row1colb  row1colc
row2  row2cola  row2colb  row2colc
row3  row3cola  row3colb  row3colc

In Java, what is the best way to determine the size of an object?

Some years back Javaworld had an article on determining the size of composite and potentially nested Java objects, they basically walk through creating a sizeof() implementation in Java. The approach basically builds on other work where people experimentally identified the size of primitives and typical Java objects and then apply that knowledge to a method that recursively walks an object graph to tally the total size.

It is always going to be somewhat less accurate than a native C implementation simply because of the things going on behind the scenes of a class but it should be a good indicator.

Alternatively a SourceForge project appropriately called sizeof that offers a Java5 library with a sizeof() implementation.

P.S. Do not use the serialization approach, there is no correlation between the size of a serialized object and the amount of memory it consumes when live.

How can I convert a dictionary into a list of tuples?

[(k,v) for (k,v) in d.iteritems()]

and

[(v,k) for (k,v) in d.iteritems()]

Read file from aws s3 bucket using node fs

I had exactly the same issue when downloading from S3 very large files.

The example solution from AWS docs just does not work:

var file = fs.createWriteStream(options.filePath);
        file.on('close', function(){
            if(self.logger) self.logger.info("S3Dataset file download saved to %s", options.filePath );
            return callback(null,done);
        });
        s3.getObject({ Key:  documentKey }).createReadStream().on('error', function(err) {
            if(self.logger) self.logger.error("S3Dataset download error key:%s error:%@", options.fileName, error);
            return callback(error);
        }).pipe(file);

While this solution will work:

    var file = fs.createWriteStream(options.filePath);
    s3.getObject({ Bucket: this._options.s3.Bucket, Key: documentKey })
    .on('error', function(err) {
        if(self.logger) self.logger.error("S3Dataset download error key:%s error:%@", options.fileName, error);
        return callback(error);
    })
    .on('httpData', function(chunk) { file.write(chunk); })
    .on('httpDone', function() { 
        file.end(); 
        if(self.logger) self.logger.info("S3Dataset file download saved to %s", options.filePath );
        return callback(null,done);
    })
    .send();

The createReadStream attempt just does not fire the end, close or error callback for some reason. See here about this.

I'm using that solution also for writing down archives to gzip, since the first one (AWS example) does not work in this case either:

        var gunzip = zlib.createGunzip();
        var file = fs.createWriteStream( options.filePath );

        s3.getObject({ Bucket: this._options.s3.Bucket, Key: documentKey })
        .on('error', function (error) {
            if(self.logger) self.logger.error("%@",error);
            return callback(error);
        })
        .on('httpData', function (chunk) {
            file.write(chunk);
        })
        .on('httpDone', function () {

            file.end();

            if(self.logger) self.logger.info("downloadArchive downloaded %s", options.filePath);

            fs.createReadStream( options.filePath )
            .on('error', (error) => {
                return callback(error);
            })
            .on('end', () => {
                if(self.logger) self.logger.info("downloadArchive unarchived %s", options.fileDest);
                return callback(null, options.fileDest);
            })
            .pipe(gunzip)
            .pipe(fs.createWriteStream(options.fileDest))
        })
        .send();

How to clean old dependencies from maven repositories?

You need to copy the dependency you need for project. Having these in hand please clear all the <dependency> tag embedded into <dependencies> tag from POM.XML file in your project.

After saving the file you will not see Maven Dependencies in your Libraries. Then please paste those <dependency> you have copied earlier.

The required jars will be automatically downloaded by Maven, you can see that too in the generated Maven Dependencies Libraries after saving the file.

Thanks.

What do \t and \b do?

This behaviour is terminal-specific and specified by the terminal emulator you use (e.g. xterm) and the semantics of terminal that it provides. The terminal behaviour has been very stable for the last 20 years, and you can reasonably rely on the semantics of \b.

Redirect from a view to another view

Purpose of view is displaying model. You should use controller to redirect request before creating model and passing it to view. Use Controller.RedirectToAction method for this.

How to convert Map keys to array?

Not exactly best answer to question but this trick new Array(...someMap) saved me couple of times when I need both key and value to generate needed array. For example when there is need to create react components from Map object based on both key and value values.

  let map = new Map();
  map.set("1", 1);
  map.set("2", 2);
  console.log(new Array(...map).map(pairs => pairs[0])); -> ["1", "2"]

How do I do a bulk insert in mySQL using node.js

Bulk inserts are possible by using nested array, see the github page

Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')

You just insert a nested array of elements.

An example is given in here

var mysql = require('mysql');
var conn = mysql.createConnection({
    ...
});

var sql = "INSERT INTO Test (name, email, n) VALUES ?";
var values = [
    ['demian', '[email protected]', 1],
    ['john', '[email protected]', 2],
    ['mark', '[email protected]', 3],
    ['pete', '[email protected]', 4]
];
conn.query(sql, [values], function(err) {
    if (err) throw err;
    conn.end();
});

Note: values is an array of arrays wrapped in an array

[ [ [...], [...], [...] ] ]

There is also a totally different node-msql package for bulk insertion

Set cookies for cross origin requests

Pim's answer is very helpful. In my case, I have to use

Expires / Max-Age: "Session"

If it is a dateTime, even it is not expired, it still won't send the cookie to the backend:

Expires / Max-Age: "Thu, 21 May 2020 09:00:34 GMT"

Hope it is helpful for future people who may meet same issue.

CSS vertical-align: text-bottom;

Vertical align only works in some select cases. The easiest way to make it function is to set display: table in the parent element's CSS and display: table-cell; to the child element and then apply your vertical align attribute.

How to create a bash script to check the SSH connection?

https://onpyth.blogspot.com/2019/08/check-ping-connectivity-to-multiple-host.html

Above link is to create Python script for checking connectivity. You can use similar method and use:

ping -w 1 -c 1 "IP Address" 

Command to create bash script.

String split on new line, tab and some number of spaces

If you look at the documentation for str.split:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

In other words, if you're trying to figure out what to pass to split to get '\n\tName: Jane Smith' to ['Name:', 'Jane', 'Smith'], just pass nothing (or None).

This almost solves your whole problem. There are two parts left.

First, you've only got two fields, the second of which can contain spaces. So, you only want one split, not as many as possible. So:

s.split(None, 1)

Next, you've still got those pesky colons. But you don't need to split on them. At least given the data you've shown us, the colon always appears at the end of the first field, with no space before and always space after, so you can just remove it:

key, value = s.split(None, 1)
key = key[:-1]

There are a million other ways to do this, of course; this is just the one that seems closest to what you were already trying.

how to check for special characters php

<?php

$string = 'foo';

if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $string))
{
    // one or more of the 'special characters' found in $string
}

Accessing a value in a tuple that is in a list

OR you can use pandas:

>>> import pandas as pd
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> df=pd.DataFrame(L)
>>> df[1]
0    2
1    3
2    5
3    4
4    7
5    7
6    8
Name: 1, dtype: int64
>>> df[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>> 

Or numpy:

>>> import numpy as np
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> arr=np.array(L)
>>> arr.T[1]
array([2, 3, 5, 4, 7, 7, 8])
>>> arr.T[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>> 

How to decrease prod bundle size?

Use latest angular cli version and use command ng build --prod --build-optimizer It will definitely reduce the build size for prod env.

This is what the build optimizer does under the hood:

The build optimizer has two main jobs. First, we are able to mark parts of your application as pure,this improves the tree shaking provided by the existing tools, removing additional parts of your application that aren’t needed.

The second thing the build optimizer does is to remove Angular decorators from your application’s runtime code. Decorators are used by the compiler, and aren’t needed at runtime and can be removed. Each of these jobs decrease the size of your JavaScript bundles, and increase the boot speed of your application for your users.

Note : One update for Angular 5 and up, the ng build --prod automatically take care of above process :)

Remove all classes that begin with a certain string

Using 2nd signature of $.fn.removeClass :

// Considering:
var $el = $('<div class="  foo-1 a b foo-2 c foo"/>');

function makeRemoveClassHandler(regex) {
  return function (index, classes) {
    return classes.split(/\s+/).filter(function (el) {return regex.test(el);}).join(' ');
  }
}

$el.removeClass(makeRemoveClassHandler(/^foo-/));
//> [<div class=?"a b c foo">?</div>?]

Can I install the "app store" in an IOS simulator?

This is NOT possible

The Simulator does not run ARM code, ONLY x86 code. Unless you have the raw source code from Apple, you won't see the App Store on the Simulator.

The app you write you will be able to test in the Simulator by running it directly from Xcode even if you don't have a developer account. To test your app on an actual device, you will need to be apart of the Apple Developer program.

How to make div background color transparent in CSS

The problem with opacity is that it will also affect the content, when often you do not want this to happen.

If you just want your element to be transparent, it's really as easy as :

background-color: transparent;

But if you want it to be in colors, you can use:

background-color: rgba(255, 0, 0, 0.4);

Or define a background image (1px by 1px) saved with the right alpha.
(To do so, use Gimp, Paint.Net or any other image software that allows you to do that.
Just create a new image, delete the background and put a semi-transparent color in it, then save it in png.)

As said by René, the best thing to do would be to mix both, with the rgba first and the 1px by 1px image as a fallback if the browser doesn't support alpha :

background: url('img/red_transparent_background.png');
background: rgba(255, 0, 0, 0.4);

See also : http://www.w3schools.com/cssref/css_colors_legal.asp.

Demo : My JSFiddle

In AngularJS, what's the difference between ng-pristine and ng-dirty?

The ng-dirty class tells you that the form has been modified by the user, whereas the ng-pristine class tells you that the form has not been modified by the user. So ng-dirty and ng-pristine are two sides of the same story.

The classes are set on any field, while the form has two properties, $dirty and $pristine.

You can use the $scope.form.$setPristine() function to reset a form to pristine state (please note that this is an AngularJS 1.1.x feature).

If you want a $scope.form.$setPristine()-ish behavior even in 1.0.x branch of AngularJS, you need to roll your own solution (some pretty good ones can be found here). Basically, this means iterating over all form fields and setting their $dirty flag to false.

Hope this helps.

How to print bytes in hexadecimal using System.out.println?

System.out.println(Integer.toHexString(test[0]));

OR (pretty print)

System.out.printf("0x%02X", test[0]);

OR (pretty print)

System.out.println(String.format("0x%02X", test[0]));

How to create JSON string in JavaScript?

I think this way helps you...

var name=[];
var age=[];
name.push('sulfikar');
age.push('24');
var ent={};
for(var i=0;i<name.length;i++)
{
ent.name=name[i];
ent.age=age[i];
}
JSON.Stringify(ent);

Choosing line type and color in Gnuplot 4.0

You need to use linecolor instead of lc, like:

set style line 1 lt 1 lw 3 pt 3 linecolor rgb "red"

"help set style line" gives you more info.

How to replace NA values in a table for selected columns

We can solve it in data.table way with tidyr::repalce_na function and lapply

library(data.table)
library(tidyr)
setDT(df)
df[,c("a","b","c"):=lapply(.SD,function(x) replace_na(x,0)),.SDcols=c("a","b","c")]

In this way, we can also solve paste columns with NA string. First, we replace_na(x,""),then we can use stringr::str_c to combine columns!

time data does not match format

I had the exact same error but with slightly different format and root-cause, and since this is the first Q&A that pops up when you search for "time data does not match format", I thought I'd leave the mistake I made for future viewers:

My initial code:

start = datetime.strptime('05-SEP-19 00.00.00.000 AM', '%d-%b-%y %I.%M.%S.%f %p')

Where I used %I to parse the hours and %p to parse 'AM/PM'.

The error:

ValueError: time data '05-SEP-19 00.00.00.000000 AM' does not match format '%d-%b-%y %I.%M.%S.%f %p'

I was going through the datetime docs and finally realized in 12-hour format %I, there is no 00... once I changed 00.00.00 to 12.00.00, the problem was resolved.

So it's either 01-12 using %I with %p, or 00-23 using %H.

How can I INSERT data into two tables simultaneously in SQL Server?

Create table #temp1
(
 id int identity(1,1),
 name varchar(50),
 profession varchar(50)
)

Create table #temp2
(
 id int identity(1,1),
 name varchar(50),
 profession varchar(50)
)

-----main query ------

insert into #temp1(name,profession)

output inserted.name,inserted.profession into #temp2

select 'Shekhar','IT'

How to find path of active app.config file?

Make sure you click the properties on the file and set it to "copy always" or it will not be in the Debug\ folder with your happy lil dll's to configure where it needs to be and add more cowbell

Android Studio shortcuts like Eclipse

View > Quick Switch Scheme > Keymap > Eclipse
use this option for eclipse keymap or if u want to go with AndroidStudio keymap then follow below link

Click here for Official Android Studio Keymap Refference guide

you may find default keymap referrence in

AndroidStudio --> Help-->Default keymap refrence

What version of Python is on my Mac?

If you have both Python2 and Python3 installed on your Mac, you can use

python --version

to check the version of Python2, and

python3 --version

to check the version of Python3.

However, if only Python3 is installed, then your system might use python instead of python3 for Python3. In this case, you can just use

python --version

to check the version of Python3.

Android Overriding onBackPressed()

At first you must consider that if your activity which I called A extends another activity (B) and in both of

them you want to use onbackpressed function then every code you have in B runs in A too. So if you want to separate these you should separate them. It means that A should not extend B , then you can have onbackpressed separately for each of them.

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.

The HttpSession#setMaxInactiveInterval() doesn't change much here by the way. It does exactly the same as <session-timeout> in web.xml, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static method).


To play around and experience this yourself, try to set <session-timeout> to 1 minute and create a HttpSessionListener like follows:

@WebListener
public class HttpSessionChecker implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
    }

}

(if you're not on Servlet 3.0 yet and thus can't use @WebListener, then register in web.xml as follows):

<listener>
    <listener-class>com.example.HttpSessionChecker</listener-class>
</listener>

Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.

See also:

How to align iframe always in the center

You could easily use display:table to vertical-align content and text-align:center to horizontal align your iframe. http://jsfiddle.net/EnmD6/7/

html {
    display:table;
    height:100%;
    width:100%;
}
body {
    display:table-cell;
    vertical-align:middle;
}
#top-element {
    position:absolute;
    top:0;
    left:0;
    background:orange;
    width:100%;
}
#iframe-wrapper {
    text-align:center;
}

version with table-row http://jsfiddle.net/EnmD6/9/

html {
    height:100%;
    width:100%;
}
body {
    display:table;
    height:100%;
    width:100%;
    margin:0;
}
#top-element {
    display:table-row;
    background:orange;
    width:100%;
}
#iframe-wrapper {
    display:table-cell;
    height:100%;
    vertical-align:middle;
    text-align:center;
}

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

It worked to me only using a specific service.

For example instead of use:

compile 'com.google.android.gms:play-services:10.0.1'

I used:

com.google.android.gms:play-services-places:10.0.1

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

See http://blog.headius.com/2009/01/my-favorite-hotspot-jvm-flags.html

-Xms and -Xmx set the minimum and maximum sizes for the heap. Touted as a feature, Hotspot puts a cap on heap size to prevent it from blowing out your system. So once you figure out the max memory your app needs, you cap it to keep rogue code from impacting other apps. Use these flags like -Xmx512M, where the M stands for MB. If you don't include it, you're specifying bytes. Several flags use this format. You can also get a minor startup perf boost by setting minimum higher, since it doesn't have to grow the heap right away.

-XX:MaxPermSize=###M sets the maximum "permanent generation" size. Hotspot is unusual in that several types of data get stored in the "permanent generation", a separate area of the heap that is only rarely (or never) garbage-collected. The list of perm-gen hosted data is a little fuzzy, but it generally contains things like class metadata, bytecode, interned strings, and so on (and this certainly varies across Hotspot versions). Because this generation is rarely or never collected, you may need to increase its size (or turn on perm-gen sweeping with a couple other flags). In JRuby especially we generate a lot of adapter bytecode, which usually demands more perm gen space.

How to set -source 1.7 in Android Studio and Gradle

Java 7 support was added at build tools 19. You can now use features like the diamond operator, multi-catch, try-with-resources, strings in switches, etc. Add the following to your build.gradle.

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 19
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Gradle 1.7+, Android gradle plugin 0.6.+ are required.

Note, that only try with resources require minSdkVersion 19. Other features works on previous platforms.

Link to android gradle plugin user guide

Link to see how source vs target are different

Detecting a redirect in ajax request?

While the other folks who answered this question are (sadly) correct that this information is hidden from us by the browser, I thought I'd post a workaround I came up with:

I configured my server app to set a custom response header (X-Response-Url) containing the url that was requested. Whenever my ajax code receives a response, it checks if xhr.getResponseHeader("x-response-url") is defined, in which case it compares it to the url that it originally requested via $.ajax(). If the strings differ, I know there was a redirect, and additionally, what url we actually arrived at.

This does have the drawback of requiring some server-side help, and also may break down if the url gets munged (due to quoting/encoding issues etc) during the round trip... but for 99% of cases, this seems to get the job done.


On the server side, my specific case was a python application using the Pyramid web framework, and I used the following snippet:

import pyramid.events

@pyramid.events.subscriber(pyramid.events.NewResponse)
def set_response_header(event):
    request = event.request
    if request.is_xhr:
        event.response.headers['X-Response-URL'] = request.url

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed

Please make sure you are using latest jdbc connector as per the mysql. I was facing this problem and when I replaced my old jdbc connector with the latest one, the problem was solved.

You can download latest jdbc driver from https://dev.mysql.com/downloads/connector/j/

Select Operating System as Platform Independent. It will show you two options. One as tar and one as zip. Download the zip and extract it to get the jar file and replace it with your old connector.

This is not only for hibernate framework, it can be used with any platform which requires a jdbc connector.

Find current directory and file's directory

For question 1 use os.getcwd() # get working dir and os.chdir(r'D:\Steam\steamapps\common') # set working dir


I recommend using sys.argv[0] for question 2 because sys.argv is immutable and therefore always returns the current file (module object path) and not affected by os.chdir(). Also you can do like this:

import os
this_py_file = os.path.realpath(__file__)

# vvv Below comes your code vvv #

but that snippet and sys.argv[0] will not work or will work wierd when compiled by PyInstaller because magic properties are not set in __main__ level and sys.argv[0] is the way your exe was called (means that it becomes affected by the working dir).

Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Upgrade to PostgreSQL 9.5 or greater. If (not) exists was introduced in version 9.5.

Add jars to a Spark Job - spark-submit

ClassPath:

ClassPath is affected depending on what you provide. There are a couple of ways to set something on the classpath:

  • spark.driver.extraClassPath or it's alias --driver-class-path to set extra classpaths on the node running the driver.
  • spark.executor.extraClassPath to set extra class path on the Worker nodes.

If you want a certain JAR to be effected on both the Master and the Worker, you have to specify these separately in BOTH flags.

Separation character:

Following the same rules as the JVM:

  • Linux: A colon :
    • e.g: --conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar:/opt/prog/aws-java-sdk-1.10.50.jar"
  • Windows: A semicolon ;
    • e.g: --conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar;/opt/prog/aws-java-sdk-1.10.50.jar"

File distribution:

This depends on the mode which you're running your job under:

  1. Client mode - Spark fires up a Netty HTTP server which distributes the files on start up for each of the worker nodes. You can see that when you start your Spark job:

    16/05/08 17:29:12 INFO HttpFileServer: HTTP File server directory is /tmp/spark-48911afa-db63-4ffc-a298-015e8b96bc55/httpd-84ae312b-5863-4f4c-a1ea-537bfca2bc2b
    16/05/08 17:29:12 INFO HttpServer: Starting HTTP Server
    16/05/08 17:29:12 INFO Utils: Successfully started service 'HTTP file server' on port 58922.
    16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/foo.jar at http://***:58922/jars/com.mycode.jar with timestamp 1462728552732
    16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/aws-java-sdk-1.10.50.jar at http://***:58922/jars/aws-java-sdk-1.10.50.jar with timestamp 1462728552767
    
  2. Cluster mode - In cluster mode spark selected a leader Worker node to execute the Driver process on. This means the job isn't running directly from the Master node. Here, Spark will not set an HTTP server. You have to manually make your JARS available to all the worker node via HDFS/S3/Other sources which are available to all nodes.

Accepted URI's for files

In "Submitting Applications", the Spark documentation does a good job of explaining the accepted prefixes for files:

When using spark-submit, the application jar along with any jars included with the --jars option will be automatically transferred to the cluster. Spark uses the following URL scheme to allow different strategies for disseminating jars:

  • file: - Absolute paths and file:/ URIs are served by the driver’s HTTP file server, and every executor pulls the file from the driver HTTP server.
  • hdfs:, http:, https:, ftp: - these pull down files and JARs from the URI as expected
  • local: - a URI starting with local:/ is expected to exist as a local file on each worker node. This means that no network IO will be incurred, and works well for large files/JARs that are pushed to each worker, or shared via NFS, GlusterFS, etc.

Note that JARs and files are copied to the working directory for each SparkContext on the executor nodes.

As noted, JARs are copied to the working directory for each Worker node. Where exactly is that? It is usually under /var/run/spark/work, you'll see them like this:

drwxr-xr-x    3 spark spark   4096 May 15 06:16 app-20160515061614-0027
drwxr-xr-x    3 spark spark   4096 May 15 07:04 app-20160515070442-0028
drwxr-xr-x    3 spark spark   4096 May 15 07:18 app-20160515071819-0029
drwxr-xr-x    3 spark spark   4096 May 15 07:38 app-20160515073852-0030
drwxr-xr-x    3 spark spark   4096 May 15 08:13 app-20160515081350-0031
drwxr-xr-x    3 spark spark   4096 May 18 17:20 app-20160518172020-0032
drwxr-xr-x    3 spark spark   4096 May 18 17:20 app-20160518172045-0033

And when you look inside, you'll see all the JARs you deployed along:

[*@*]$ cd /var/run/spark/work/app-20160508173423-0014/1/
[*@*]$ ll
total 89988
-rwxr-xr-x 1 spark spark   801117 May  8 17:34 awscala_2.10-0.5.5.jar
-rwxr-xr-x 1 spark spark 29558264 May  8 17:34 aws-java-sdk-1.10.50.jar
-rwxr-xr-x 1 spark spark 59466931 May  8 17:34 com.mycode.code.jar
-rwxr-xr-x 1 spark spark  2308517 May  8 17:34 guava-19.0.jar
-rw-r--r-- 1 spark spark      457 May  8 17:34 stderr
-rw-r--r-- 1 spark spark        0 May  8 17:34 stdout

Affected options:

The most important thing to understand is priority. If you pass any property via code, it will take precedence over any option you specify via spark-submit. This is mentioned in the Spark documentation:

Any values specified as flags or in the properties file will be passed on to the application and merged with those specified through SparkConf. Properties set directly on the SparkConf take highest precedence, then flags passed to spark-submit or spark-shell, then options in the spark-defaults.conf file

So make sure you set those values in the proper places, so you won't be surprised when one takes priority over the other.

Lets analyze each option in question:

  • --jars vs SparkContext.addJar: These are identical, only one is set through spark submit and one via code. Choose the one which suites you better. One important thing to note is that using either of these options does not add the JAR to your driver/executor classpath, you'll need to explicitly add them using the extraClassPath config on both.
  • SparkContext.addJar vs SparkContext.addFile: Use the former when you have a dependency that needs to be used with your code. Use the latter when you simply want to pass an arbitrary file around to your worker nodes, which isn't a run-time dependency in your code.
  • --conf spark.driver.extraClassPath=... or --driver-class-path: These are aliases, doesn't matter which one you choose
  • --conf spark.driver.extraLibraryPath=..., or --driver-library-path ... Same as above, aliases.
  • --conf spark.executor.extraClassPath=...: Use this when you have a dependency which can't be included in an uber JAR (for example, because there are compile time conflicts between library versions) and which you need to load at runtime.
  • --conf spark.executor.extraLibraryPath=... This is passed as the java.library.path option for the JVM. Use this when you need a library path visible to the JVM.

Would it be safe to assume that for simplicity, I can add additional application jar files using the 3 main options at the same time:

You can safely assume this only for Client mode, not Cluster mode. As I've previously said. Also, the example you gave has some redundant arguments. For example, passing JARs to --driver-library-path is useless, you need to pass them to extraClassPath if you want them to be on your classpath. Ultimately, what you want to do when you deploy external JARs on both the driver and the worker is:

spark-submit --jars additional1.jar,additional2.jar \
  --driver-class-path additional1.jar:additional2.jar \
  --conf spark.executor.extraClassPath=additional1.jar:additional2.jar \
  --class MyClass main-application.jar

When should you use constexpr capability in C++11?

constexpr functions are really nice and a great addition to c++. However, you are right in that most of the problems it solves can be inelegantly worked around with macros.

However, one of the uses of constexpr has no C++03 equivalent, typed constants.

// This is bad for obvious reasons.
#define ONE 1;

// This works most of the time but isn't fully typed.
enum { TWO = 2 };

// This doesn't compile
enum { pi = 3.1415f };

// This is a file local lvalue masquerading as a global
// rvalue.  It works most of the time.  But May subtly break
// with static initialization order issues, eg pi = 0 for some files.
static const float pi = 3.1415f;

// This is a true constant rvalue
constexpr float pi = 3.1415f;

// Haven't you always wanted to do this?
// constexpr std::string awesome = "oh yeah!!!";
// UPDATE: sadly std::string lacks a constexpr ctor

struct A
{
   static const int four = 4;
   static const int five = 5;
   constexpr int six = 6;
};

int main()
{
   &A::four; // linker error
   &A::six; // compiler error

   // EXTREMELY subtle linker error
   int i = rand()? A::four: A::five;
   // It not safe use static const class variables with the ternary operator!
}

//Adding this to any cpp file would fix the linker error.
//int A::four;
//int A::six;

Changing the sign of a number in PHP?

function invertSign($value)
{
    return -$value;
}

Shared folder between MacOSX and Windows on Virtual Box

Yesterday, I am able to share the folders from my host OS Macbook (high Sierra) to Guest OS Windows 10

Original Answer

Because there isn't an official answer yet and I literally just did this for my OS X/WinXP install, here's what I did:

  1. VirtualBox Manager: Open the Shared Folders setting and click the '+' icon to add a new folder. Then, populate the Folder Path (or use the drop-down to navigate) with the folder you want shared and make sure "Auto-Mount" and "Make Permanent" are checked.
  2. Boot Windows
  3. Download the VBoxGuestAdditions_4.0.12.iso from http://download.virtualbox.org/virtualbox/4.0.12/
  4. Go to Devices > Optical drives > choose disk image.. choose the one downloaded in step 3
  5. Inside host guest OS (Windows 10, in my case) I could see: This PC > CD Drive (D:) Virtual Guest Additions

For now, right click on it, select Properties, the Compatibility tab, and select Windows 8 compatibility there. Much easier than using the compatibility troubleshooting I did initially.

enter image description here

  1. reboot the guest OS (Windows 10)
  2. Inside host guest OS, you could see the shared folder This PC> shared folder

It worked for me so I thought of sharing with everyone too.

Does Notepad++ show all hidden characters?

For non-printing characters, you can do the following:

  • if you could identify the character, where cursor takes 2 arrow keys to move, just select that character.
  • do Ctrl-F
  • now you can count or replace or even mark all such characters

Javascript document.getElementById("id").value returning null instead of empty string when the element is an empty text box

Please check this fiddle and let me know if you get an alert of null value. I have copied your code there and added a couple of alerts. Just like others, I also dont see a null being returned, I get an empty string. Which browser are you using?

Load a Bootstrap popover content with AJAX. Is this possible?

I tried the solution by Çagatay Gürtürk but got the same weirdness as Luke the Obscure. Then tried the solution by Asa Kusuma. This works, but I believe it does the Ajax read every time the popover is displayed. The call to unbind('hover') has no effect. That's because delegate is monitoring for events in a specific class -- but that class is unchanged.

Here's my solution, closely based on Asa Kusuma's. Changes:

  • Replaced delegate with on to match new JQuery libraries.
  • Remove 'withajaxpopover' class rather than unbinding hover event (which was never bound)
  • Add "trigger: hover" to the popover so that Bootstrap will handle it completely beginning with the second use.
  • My data loading function returns JSon, which makes it easy to specify both the title and the content for the popover.
    /*  Goal: Display a tooltip/popover where the content is fetched from the
              application the first time only.

        How:  Fetch the appropriate content and register the tooltip/popover the first time 
              the mouse enters a DOM element with class "withajaxpopover".  Remove the 
              class from the element so we don't do that the next time the mouse enters.
              However, that doesn't show the tooltip/popover for the first time
              (because the mouse is already entered when the tooltip is registered).
              So we have to show/hide it ourselves.
    */
    $(function() {
      $('body').on('hover', '.withajaxpopover', function(event){
          if (event.type === 'mouseenter') {
              var el=$(this);
              $.get(el.attr('data-load'),function(d){
                  el.removeClass('withajaxpopover')
                  el.popover({trigger: 'hover', 
                              title: d.title, 
                              content: d.content}).popover('show');
              });
          }  else {
              $(this).popover('hide');
          }
      });
    });

How to calculate cumulative normal distribution?

Taken from above:

from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435

For a two-tailed test:

Import numpy as np
z = 1.96
p_value = 2 * norm.cdf(-np.abs(z))
0.04999579029644087

How to install a specific version of a ruby gem?

Use the --version parameter (shortcut -v):

$ gem install rails -v 0.14.1

You can also use version comparators like >= or ~>

$ gem install rails -v '~> 0.14.0'

Or with newer versions of gem even:

$ gem install rails:0.14.4 rubyzip:'< 1'
…
Successfully installed rails-0.14.4
Successfully installed rubyzip-0.9.9

Convert String to Type in C#

You can only use just the name of the type (with its namespace, of course) if the type is in mscorlib or the calling assembly. Otherwise, you've got to include the assembly name as well:

Type type = Type.GetType("Namespace.MyClass, MyAssembly");

If the assembly is strongly named, you've got to include all that information too. See the documentation for Type.GetType(string) for more information.

Alternatively, if you have a reference to the assembly already (e.g. through a well-known type) you can use Assembly.GetType:

Assembly asm = typeof(SomeKnownType).Assembly;
Type type = asm.GetType(namespaceQualifiedTypeName);

PHP: HTTP or HTTPS?

$_SERVER['HTTPS']

This will contain a 'non-empty' value if the request was sent through HTTPS

PHP Server Variables

Press Enter to move to next control

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == (Keys.Enter))
        {
            SendKeys.Send("{TAB}");
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }

goto the design form and View-> tab(as like picture shows) Order then you ordered all the control[That's it] enter image description here

Push an associative item into an array in JavaScript

Another method for creating a JavaScript associative array

First create an array of objects,

 var arr = {'name': []};

Next, push the value to the object.

  var val = 2;
  arr['name'].push(val);

To read from it:

var val = arr.name[0];

using mailto to send email with an attachment

Nope, this is not possible at all. There is no provision for it in the mailto: protocol, and it would be a gaping security hole if it were possible.

The best idea to send a file, but have the client send the E-Mail that I can think of is:

  • Have the user choose a file
  • Upload the file to a server
  • Have the server return a random file name after upload
  • Build a mailto: link that contains the URL to the uploaded file in the message body