Programs & Examples On #Javascript

JavaScript (not to be confused with Java) is a high-level, dynamic, multi-paradigm, weakly-typed language used for both client-side and server-side scripting. Its primary use is in rendering and allowing manipulation of web pages. Use this tag for questions regarding ECMAScript and its various dialects/implementations (excluding ActionScript and Google-Apps-Script).

eslint: error Parsing error: The keyword 'const' is reserved

you also can add this inline instead of config, just add it to the same file before you add your own disable stuff

/* eslint-env es6 */
/* eslint-disable no-console */

my case was disable a file and eslint-disable were not working for me alone

/* eslint-env es6 */
/* eslint-disable */

Image resizing in React Native

This worked for me:

image: {
    flex: 1,
    aspectRatio: 1.5, 
    resizeMode: 'contain',

  }

aspectRatio is just width/height (my image is 45px wide x 30px high).

onClick not working on mobile (touch)

better to use touchstart event with .on() jQuery method:

$(window).load(function() { // better to use $(document).ready(function(){
    $('.List li').on('click touchstart', function() {
        $('.Div').slideDown('500');
    });
});

And i don't understand why you are using $(window).load() method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready() method which does not wait for each element on the page to be loaded first.

JavaScript: Create and save file

Tried this in the console, and it works.

var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
window.open(URL.createObjectURL(oMyBlob));

Iterate through Nested JavaScript Objects

var findObjectByLabel = function(objs, label) {
  if(objs.label === label) { 
    return objs; 
    }
  else{
    if(objs.subs){
      for(var i in objs.subs){
        let found = findObjectByLabel(objs.subs[i],label)
        if(found) return found
      }
    }
  }
};

findObjectByLabel(cars, "Ford");

How can I get an object's absolute position on the page in Javascript?

I would definitely suggest using element.getBoundingClientRect().

https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect

Summary

Returns a text rectangle object that encloses a group of text rectangles.

Syntax

var rectObject = object.getBoundingClientRect();

Returns

The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

Here's a browser compatibility table taken from the linked MDN site:

+---------------+--------+-----------------+-------------------+-------+--------+
|    Feature    | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
+---------------+--------+-----------------+-------------------+-------+--------+
| Basic support | 1.0    | 3.0 (1.9)       | 4.0               | (Yes) | 4.0    |
+---------------+--------+-----------------+-------------------+-------+--------+

It's widely supported, and is really easy to use, not to mention that it's really fast. Here's a related article from John Resig: http://ejohn.org/blog/getboundingclientrect-is-awesome/

You can use it like this:

var logo = document.getElementById('hlogo');
var logoTextRectangle = logo.getBoundingClientRect();

console.log("logo's left pos.:", logoTextRectangle.left);
console.log("logo's right pos.:", logoTextRectangle.right);

Here's a really simple example: http://jsbin.com/awisom/2 (you can view and edit the code by clicking "Edit in JS Bin" in the upper right corner).

Or here's another one using Chrome's console: Using element.getBoundingClientRect() in Chrome

Note:

I have to mention that the width and height attributes of the getBoundingClientRect() method's return value are undefined in Internet Explorer 8. It works in Chrome 26.x, Firefox 20.x and Opera 12.x though. Workaround in IE8: for width, you could subtract the return value's right and left attributes, and for height, you could subtract bottom and top attributes (like this).

How can I hide or encrypt JavaScript code?

JavaScript is a scripting language and therefore stays in human readable form until it is time for it to be interpreted and executed by the JavaScript runtime.

The only way to partially hide it, at least from the less technical minds, is to obfuscate.

Obfuscation makes it harder for humans to read it, but not impossible for the technically savvy.

how to set textbox value in jquery

I would like to point out to you that .val() also works with selects to select the current selected value.

Set a cookie to HttpOnly via Javascript

An HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly.

Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly by just XSS and still have access to the cookie via JS and thus make the HttpOnly on your cookie completely useless.

How to detect a mobile device with JavaScript?

So I did this. Thank you all!

<head>
<script type="text/javascript">
    function DetectTheThing()
    {
       var uagent = navigator.userAgent.toLowerCase();
       if (uagent.search("iphone") > -1 || uagent.search("ipad") > -1 
       || uagent.search("android") > -1 || uagent.search("blackberry") > -1
       || uagent.search("webos") > -1)
          window.location.href ="otherindex.html";
    }
</script>

</head>

<body onload="DetectTheThing()">
VIEW NORMAL SITE
</body>

</html>

How to serialize an Object into a list of URL query parameters?

Since I made such a big deal about a recursive function, here is my own version.

function objectParametize(obj, delimeter, q) {
    var str = new Array();
    if (!delimeter) delimeter = '&';
    for (var key in obj) {
        switch (typeof obj[key]) {
            case 'string':
            case 'number':
                str[str.length] = key + '=' + obj[key];
            break;
            case 'object':
                str[str.length] = objectParametize(obj[key], delimeter);
        }
    }
    return (q === true ? '?' : '') + str.join(delimeter);
}

http://jsfiddle.net/userdude/Kk3Lz/2/

"Submit is not a function" error in JavaScript

In fact, the solution is very easy...

Original:

    <form action="product.php" method="get" name="frmProduct" id="frmProduct"
enctype="multipart/form-data">
    <input onclick="submitAction()" id="submit_value" type="button" 
    name="submit_value" value="">
</form>
<script type="text/javascript">
    function submitAction()
    {
        document.frmProduct.submit();
    }
</script>

Solution:

    <form action="product.php" method="get" name="frmProduct" id="frmProduct" 
enctype="multipart/form-data">
</form>

<!-- Place the button here -->
<input onclick="submitAction()" id="submit_value" type="button" 
    name="submit_value" value="">

<script type="text/javascript">
    function submitAction()
    {
        document.frmProduct.submit();
    }
</script>

Cross domain POST request is not sending cookie Ajax Jquery

You cannot set or read cookies on CORS requests through JavaScript. Although CORS allows cross-origin requests, the cookies are still subject to the browser's same-origin policy, which means only pages from the same origin can read/write the cookie. withCredentials only means that any cookies set by the remote host are sent to that remote host. You will have to set the cookie from the remote server by using the Set-Cookie header.

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

This is my function for the clients timezone, it's lite weight and simple

  function getCurrentDateTimeMySql() {        
      var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
      var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, 19).replace('T', ' ');
      var mySqlDT = localISOTime;
      return mySqlDT;
  }

How can I get stock quotes using Google Finance API?

Edit: the api call has been removed by google. so it is no longer functioning.

Agree with Pareshkumar's answer. Now there is a python wrapper googlefinance for the url call.

Install googlefinance

$pip install googlefinance

It is easy to get current stock price:

>>> from googlefinance import getQuotes
>>> import json
>>> print json.dumps(getQuotes('AAPL'), indent=2)
[
  {
    "Index": "NASDAQ", 
    "LastTradeWithCurrency": "129.09", 
    "LastTradeDateTime": "2015-03-02T16:04:29Z", 
    "LastTradePrice": "129.09", 
    "Yield": "1.46", 
    "LastTradeTime": "4:04PM EST", 
    "LastTradeDateTimeLong": "Mar 2, 4:04PM EST", 
    "Dividend": "0.47", 
    "StockSymbol": "AAPL", 
    "ID": "22144"
  }
]

Google finance is a source that provides real-time stock data. There are also other APIs from yahoo, such as yahoo-finance, but they are delayed by 15min for NYSE and NASDAQ stocks.

Enable/disable buttons with Angular

    <div class="col-md-12">
      <p style="color: #28a745; font-weight: bold; font-size:25px; text-align: right " >Total Productos a pagar= {{ getTotal() }} {{ getResult() | currency }}
      <button class="btn btn-success" type="submit" [disabled]="!getResult()" (click)="onSubmit()">
        Ver Pedido
      </button>
     </p>
    </div>

Is there a "null coalescing" operator in JavaScript?

Need to support old browser and have a object hierarchy

body.head.eyes[0]  //body, head, eyes  may be null 

may use this,

(((body||{}) .head||{}) .eyes||[])[0] ||'left eye'

How to use bootstrap datepicker

You should include bootstrap-datepicker.js after bootstrap.js and you should bind the datepicker to your control.

$(function(){
   $('.datepicker').datepicker({
      format: 'mm-dd-yyyy'
    });
});

Sum of two input value by jquery

use parseInt as a = parseInt($('input[name=service_price]').val())

How do I check that a number is float or integer?

to check the number is Int or not and apply 2 decimal format, you can use the formula below in React-Native.

isInt = (n) => {
        return n % 1 === 0;
     }

    show = (x) => {
        if(x) {
           if (this.isInt(x)) {
               return ${x} 
           }
           else {
            return ${x.toFixed(2)}
           }
        }
    }

Make view 80% width of parent in React Native

As of React Native 0.42 height: and width: accept percentages.

Use width: 80% in your stylesheets and it just works.

  • Screenshot

  • Live Example
    Child Width/Height as Proportion of Parent

  • Code

    import React from 'react';
    import { Text, View, StyleSheet } from 'react-native';
    
    const width_proportion = '80%';
    const height_proportion = '40%';
    
    const styles = StyleSheet.create({
      screen: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#5A9BD4',
      },
      box: {
        width: width_proportion,
        height: height_proportion,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#B8D2EC',
      },
      text: {
        fontSize: 18,
      },
    });
    
    export default () => (
      <View style={styles.screen}>
        <View style={styles.box}>
          <Text style={styles.text}>
            {width_proportion} of width{'\n'}
            {height_proportion} of height
          </Text>
        </View>
      </View>
    );
    

JavaScript: What are .extend and .prototype used for?

Javascript inheritance seems to be like an open debate everywhere. It can be called "The curious case of Javascript language".

The idea is that there is a base class and then you extend the base class to get an inheritance-like feature (not completely, but still).

The whole idea is to get what prototype really means. I did not get it until I saw John Resig's code (close to what jQuery.extend does) wrote a code chunk that does it and he claims that base2 and prototype libraries were the source of inspiration.

Here is the code.

    /* Simple JavaScript Inheritance
     * By John Resig http://ejohn.org/
     * MIT Licensed.
     */  
     // Inspired by base2 and Prototype
    (function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);        
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.prototype.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();

There are three parts which are doing the job. First, you loop through the properties and add them to the instance. After that, you create a constructor for later to be added to the object.Now, the key lines are:

// Populate our constructed prototype object
Class.prototype = prototype;

// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;

You first point the Class.prototype to the desired prototype. Now, the whole object has changed meaning that you need to force the layout back to its own one.

And the usage example:

var Car = Class.Extend({
  setColor: function(clr){
    color = clr;
  }
});

var volvo = Car.Extend({
   getColor: function () {
      return color;
   }
});

Read more about it here at Javascript Inheritance by John Resig 's post.

$(...).datepicker is not a function - JQuery - Bootstrap

Need to include jquery-ui too:

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

Check if an image is loaded (no errors) with jQuery

I had a lot of problems with the complete load of a image and the EventListener.

Whatever I tried, the results was not reliable.

But then I found the solution. It is technically not a nice one, but now I never had a failed image load.

What I did:

                    document.getElementById(currentImgID).addEventListener("load", loadListener1);
                    document.getElementById(currentImgID).addEventListener("load", loadListener2);

                function loadListener1()
                    {
                    // Load again
                    }

                function loadListener2()
                {
                    var btn = document.getElementById("addForm_WithImage"); btn.disabled = false;
                    alert("Image loaded");
                }

Instead of loading the image one time, I just load it a second time direct after the first time and both run trough the eventhandler.

All my headaches are gone!


By the way: You guys from stackoverflow helped me already more then hundred times. For this a very big Thank you!

What does "export default" do in JSX?

export default is used to export a single class, function or primitive from a script file.

The export can also be written as

export default class HelloWorld extends React.Component {
  render() {
    return <p>Hello, world!</p>;
  }
}

You could also write this as a function component like

export default const HelloWorld = () => (<p>Hello, world!</p>);

This is used to import this function in another script file

import HelloWorld from './HelloWorld';

You don't necessarily import it as HelloWorld you can give it any name as it's a default export

A little about export

As the name says, it's used to export functions, objects, classes or expressions from script files or modules

Utiliites.js

export function cube(x) {
  return x * x * x;
}
export const foo = Math.PI + Math.SQRT2;

This can be imported and used as

App.js

import { cube, foo } from 'Utilities';
console.log(cube(3)); // 27
console.log(foo);    // 4.555806215962888

Or

import * as utilities from 'Utilities';
console.log(utilities.cube(3)); // 27
console.log(utilities.foo);    // 4.555806215962888

When export default is used, this is much simpler. Script files just exports one thing. cube.js

export default function cube(x) {
  return x * x * x;
};

and used as App.js

import Cube from 'cube';
console.log(Cube(3)); // 27

JavaScript variable number of arguments to function

Although I generally agree that the named arguments approach is useful and flexible (unless you care about the order, in which case arguments is easiest), I do have concerns about the cost of the mbeasley approach (using defaults and extends). This is an extreme amount of cost to take for pulling default values. First, the defaults are defined inside the function, so they are repopulated on every call. Second, you can easily read out the named values and set the defaults at the same time using ||. There is no need to create and merge yet another new object to get this information.

function load(context) {
   var parameter1 = context.parameter1 || defaultValue1,
       parameter2 = context.parameter2 || defaultValue2;

   // do stuff
}

This is roughly the same amount of code (maybe slightly more), but should be a fraction of the runtime cost.

Instagram: Share photo from webpage

Uploading on Instagram is possible. Their API provides a media upload endpoint, even if it's not documented.

POST https://instagram.com/api/v1/media/upload/

Check this code for example https://code.google.com/p/twitubas/source/browse/common/instagram.php

bootstrap datepicker today as default

I used this a little example and it worked.

$('#date').datetimepicker({
    defaultDate: new Date()
});

demo : http://jsfiddle.net/m2fjw57b/1/

It says that TypeError: document.getElementById(...) is null

Make sure the script is placed in the bottom of the BODY element of the document you're trying to manipulate, not in the HEAD element or placed before any of the elements you want to "get".

It does not matter if you import the script or if it's inline, the important thing is the placing. You don't have to put the command inside a function either; while it's good practice you can just call it directly, it works just fine.

Way to ng-repeat defined number of times instead of repeating over array?

This is really UGLY, but it works without a controller for either an integer or variable:

integer:

<span ng-repeat="_ in ((_ = []) && (_.length=33) && _) track by $index">{{$index}}</span>

variable:

<span ng-repeat="_ in ((_ = []) && (_.length=myVar) && _) track by $index">{{$index}}</span>

Textarea onchange detection

You can listen to event on change of textarea and do the changes as per you want. Here is one example.

_x000D_
_x000D_
const textArea = document.getElementById('my_text_area');
textArea.addEventListener('input', () => {
    var textLn =  textArea.value.length;
    if(textLn >= 100) {
        textArea.style.fontSize = '10pt';
    }
})
_x000D_
<html>
    <textarea id='my_text_area' rows="4" cols="50" style="font-size:40pt">
This text will change font after 100.
    </textarea>
</html>
_x000D_
_x000D_
_x000D_

How to download fetch response in react as file

I managed to download the file generated by the rest API URL much easier with this kind of code which worked just fine on my local:

    import React, {Component} from "react";
    import {saveAs} from "file-saver";

    class MyForm extends Component {

    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(event) {
        event.preventDefault();
        const form = event.target;
        let queryParam = buildQueryParams(form.elements);

        let url = 'http://localhost:8080/...whatever?' + queryParam;

        fetch(url, {
            method: 'GET',
            headers: {
                // whatever
            },
        })
            .then(function (response) {
                    return response.blob();
                }
            )
            .then(function(blob) {
                saveAs(blob, "yourFilename.xlsx");
            })
            .catch(error => {
                //whatever
            })
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit} id="whateverFormId">
                <table>
                    <tbody>
                    <tr>
                        <td>
                            <input type="text" key="myText" name="myText" id="myText"/>
                        </td>
                        <td><input key="startDate" name="from" id="startDate" type="date"/></td>
                        <td><input key="endDate" name="to" id="endDate" type="date"/></td>
                    </tr>
                    <tr>
                        <td colSpan="3" align="right">
                            <button>Export</button>
                        </td>
                    </tr>

                    </tbody>
                </table>
            </form>
        );
    }
}

function buildQueryParams(formElements) {
    let queryParam = "";

    //do code here
    
    return queryParam;
}

export default MyForm;

Node.js Port 3000 already in use but it actually isn't?

In package.json scripts inlcude:

"start": "nodemon app.js --delay 1500ms"

I believe the issue was for me the time that the old port was not shutting down in time by nodemon for the restart. I experienced the issue using multer.

React js onClick can't pass value to method

Theres' a very easy way.

 onClick={this.toggleStart('xyz')} . 
  toggleStart= (data) => (e) =>{
     console.log('value is'+data);  
 }

getElementById in React

import React, { useState } from 'react';

function App() {
  const [apes , setap] = useState('yo');
  const handleClick = () =>{
    setap(document.getElementById('name').value)
  };
  return (
    <div>
      <input id='name' />
      <h2> {apes} </h2>
      <button onClick={handleClick} />
  </div>
  );
}

export default App;

Merge two array of objects based on a key

You can do it like this -

_x000D_
_x000D_
let arr1 = [_x000D_
    { id: "abdc4051", date: "2017-01-24" },_x000D_
    { id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
_x000D_
let arr2 = [_x000D_
    { id: "abdc4051", name: "ab" },_x000D_
    { id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i]));_x000D_
_x000D_
console.log(arr3);
_x000D_
_x000D_
_x000D_


Use below code if arr1 and arr2 are in a different order:

_x000D_
_x000D_
let arr1 = [_x000D_
  { id: "abdc4051", date: "2017-01-24" }, _x000D_
  { id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
_x000D_
let arr2 = [_x000D_
  { id: "abdc4051", name: "ab" },_x000D_
  { id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
let merged = [];_x000D_
_x000D_
for(let i=0; i<arr1.length; i++) {_x000D_
  merged.push({_x000D_
   ...arr1[i], _x000D_
   ...(arr2.find((itmInner) => itmInner.id === arr1[i].id))}_x000D_
  );_x000D_
}_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

Use this if arr1 and arr2 are in a same order

_x000D_
_x000D_
let arr1 = [_x000D_
  { id: "abdc4051", date: "2017-01-24" }, _x000D_
  { id: "abdc4052", date: "2017-01-22" }_x000D_
];_x000D_
_x000D_
let arr2 = [_x000D_
  { id: "abdc4051", name: "ab" },_x000D_
  { id: "abdc4052", name: "abc" }_x000D_
];_x000D_
_x000D_
let merged = [];_x000D_
_x000D_
for(let i=0; i<arr1.length; i++) {_x000D_
  merged.push({_x000D_
   ...arr1[i], _x000D_
   ...arr2[i]_x000D_
  });_x000D_
}_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

How do I convert an existing callback API to promises?

From the future

A simple generic function I normally use.

const promisify = (fn, ...args) => {
  return new Promise((resolve, reject) => {
    fn(...args, (err, data) => {
      if (err) {
        return reject(err);
      }
      resolve(data);
    });
  });
};

How to use it

   promisify(fn, arg1, arg2)

You are probably not looking to this answer, but this will help understand the inner workings of the available utils

In javascript, how do you search an array for a substring match

I've created a simple to use library (ss-search) which is designed to handle objects, but could also work in your case:

search(windowArray.map(x => ({ key: x }), ["key"], "SEARCH_TEXT").map(x => x.key)

The advantage of using this search function is that it will normalize the text before executing the search to return more accurate results.

How to write data to a JSON file using Javascript

Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.

For example: in some browser like a Chrome we have today this possibility and we can write with FileSystemFileEntry.createWriter() with client side call, but according to the docu:

This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.


For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.

If you want update your JSON file cross-browser you have to use server and client side together.

The client side script

On client side you can make a request to the server and then you have to read the response from server. Or you could read a file with FileReader too. For the cross-browser writing to the file you have to have some server (see below on server part).

var xhr = new XMLHttpRequest(),
    jsonArr,
    method = "GET",
    jsonRequestURL = "SOME_PATH/jsonFile/";

xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
    if(xhr.readyState == 4 && xhr.status == 200)
    {
        // we convert your JSON into JavaScript object
        jsonArr = JSON.parse(xhr.responseText);

        // we add new value:
        jsonArr.push({"nissan": "sentra", "color": "green"});

        // we send with new request the updated JSON file to the server:
        xhr.open("POST", jsonRequestURL, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        // if you want to handle the POST response write (in this case you do not need it):
        // xhr.onreadystatechange = function(){ /* handle POST response */ };
        xhr.send("jsonTxt="+JSON.stringify(jsonArr));
        // but on this place you have to have a server for write updated JSON to the file
    }
};
xhr.send(null);

Server side scripts

You can use a lot of different servers, but I would like to write about PHP and Node.js servers.

By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.com and for Node.js I would recommend to see and to read this list.

PHP server side script solution

The PHP script for reading and writing from JSON file:

<?php

// This PHP script must be in "SOME_PATH/jsonFile/index.php"

$file = 'jsonFile.txt';

if($_SERVER['REQUEST_METHOD'] === 'POST')
// or if(!empty($_POST))
{
    file_put_contents($file, $_POST["jsonTxt"]);
    //may be some error handeling if you want
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
// or else if(!empty($_GET))
{
    echo file_get_contents($file);
    //may be some error handeling if you want
}
?>

Node.js server side script solution

I think that Node.js is a little bit complex for beginner. This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:

The Node.js script for reading and writing from JSON file:

var http = require("http"),
    fs = require("fs"),
    port = 8080,
    pathToJSONFile = '/SOME_PATH/jsonFile.txt';

http.createServer(function(request, response)
{
    if(request.method == 'GET')
    {
        response.writeHead(200, {"Content-Type": "application/json"});
        response.write(fs.readFile(pathToJSONFile, 'utf8'));
        response.end();
    }
    else if(request.method == 'POST')
    {
        var body = [];

        request.on('data', function(chunk)
        {
            body.push(chunk);
        });

        request.on('end', function()
        {
            body = Buffer.concat(body).toString();
            var myJSONdata = body.split("=")[1];
            fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
        });
    }
}).listen(port);

Related links for Node.js:

How to make an HTML back link?

history.go(-1) doesn't work if you click around in the 2nd domain or if the referrer is empty.

So we have to store the historyCount on arriving to this domain and go back the number of navigations in this side minus 1.


// if referrer is different from this site
if (!document.referrer.includes(window.location.host)) {
  // store current history length
  localStorage.setItem('historyLength', `${history.length}`);
}

// Return to stored referrer on logo click
document.querySelector('header .logo').addEventListener('click', 
  () =>
   history.go(Number(localStorage.getItem('historyLength')) - history.length -1)
);

Get decimal portion of a number with JavaScript

Although I am very late to answer this, please have a look at the code.

let floatValue = 3.267848;
let decimalDigits = floatValue.toString().split('.')[1];
let decimalPlaces = decimalDigits.length;
let decimalDivider = Math.pow(10, decimalPlaces);
let fractionValue = decimalDigits/decimalDivider;
let integerValue = floatValue - fractionValue;

console.log("Float value: "+floatValue);
console.log("Integer value: "+integerValue);
console.log("Fraction value: "+fractionValue)

What is the javascript filename naming convention?

The question in the link you gave talks about naming of JavaScript variables, not about file naming, so forget about that for the context in which you ask your question.

As to file naming, it is purely a matter of preference and taste. I prefer naming files with hyphens because then I don't have to reach for the shift key, as I do when dealing with camelCase file names; and because I don't have to worry about differences between Windows and Linux file names (Windows file names are case-insensitive, at least through XP).

So the answer, like so many, is "it depends" or "it's up to you."

The one rule you should follow is to be consistent in the convention you choose.

Compress images on client side before uploading

You might be able to resize the image with canvas and export it using dataURI. Not sure about compression, though.

Take a look at this: Resizing an image in an HTML5 canvas

How to linebreak an svg text within javascript?

use HTML instead of javascript

_x000D_
_x000D_
<html>_x000D_
  <head><style> * { margin: 0; padding: 0; } </style></head>_x000D_
  <body>_x000D_
    <h1>svg foreignObject to embed html</h1>_x000D_
_x000D_
    <svg_x000D_
      xmlns="http://www.w3.org/2000/svg"_x000D_
      viewBox="0 0 300 300"_x000D_
      x="0" y="0" height="300" width="300"_x000D_
    >_x000D_
_x000D_
      <circle_x000D_
        r="142" cx="150" cy="150"_x000D_
        fill="none" stroke="#000000" stroke-width="2"_x000D_
      />_x000D_
_x000D_
      <foreignObject_x000D_
        x="50" y="50" width="200" height="200"_x000D_
      >_x000D_
        <div_x000D_
          xmlns="http://www.w3.org/1999/xhtml"_x000D_
          style="_x000D_
            width: 196px; height: 196px;_x000D_
            border: solid 2px #000000;_x000D_
            font-size: 32px;_x000D_
            overflow: auto; /* scroll */_x000D_
          "_x000D_
        >_x000D_
          <p>this is html in svg 1</p>_x000D_
          <p>this is html in svg 2</p>_x000D_
          <p>this is html in svg 3</p>_x000D_
          <p>this is html in svg 4</p>_x000D_
        </div>_x000D_
      </foreignObject>_x000D_
_x000D_
    </svg>_x000D_
_x000D_
</body></html>
_x000D_
_x000D_
_x000D_

Jquery: how to sleep or delay?

If you can't use the delay method as Robert Harvey suggested, you can use setTimeout.

Eg.

setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one

jquery beforeunload when closing (not leaving) the page?

Try javascript into your Ajax

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

Reference link

Example 2:

document.getElementsByClassName('eStore_buy_now_button')[0].onclick = function(){
    window.btn_clicked = true;
};
window.onbeforeunload = function(){
    if(!window.btn_clicked){
        return 'You must click "Buy Now" to make payment and finish your order. If you leave now your order will be canceled.';
    }
};

Here it will alert the user every time he leaves the page, until he clicks on the button.

DEMO: http://jsfiddle.net/DerekL/GSWbB/show/

Retrieve data from a ReadableStream object?

res.json() returns a promise. Try ...

res.json().then(body => console.log(body));

How to create a toggle button in Bootstrap

In case someone is still looking for a nice switch/toggle button, I followed Rick's suggestion and created a simple angular directive around it, angular-switch. Besides preferring a Windows styled switch, the total download is also much smaller (2kb vs 23kb minified css+js) compared to angular-bootstrap-switch and bootstrap-switch mentioned above together.

You would use it as follows. First include the required js and css file:

<script src="./bower_components/angular-switch/dist/switch.js"></script>
<link rel="stylesheet" href="./bower_components/angular-switch/dist/switch.css"></link>

And enable it in your angular app:

angular.module('yourModule', ['csComp'
    // other dependencies
]);

Now you are ready to use it as follows:

<switch state="vm.isSelected" 
    textlabel="Switch" 
    changed="vm.changed()"
    isdisabled="{{isDisabled}}">
</switch>

enter image description here

Difference between DOM parentNode and parentElement

Just like with nextSibling and nextElementSibling, just remember that, properties with "element" in their name always returns Element or null. Properties without can return any other kind of node.

console.log(document.body.parentNode, "is body's parent node");    // returns <html>
console.log(document.body.parentElement, "is body's parent element"); // returns <html>

var html = document.body.parentElement;
console.log(html.parentNode, "is html's parent node"); // returns document
console.log(html.parentElement, "is html's parent element"); // returns null

Create table with jQuery - append

To add multiple columns and rows, we can also do a string concatenation. Not the best way, but it sure works.

             var resultstring='<table>';
      for(var j=0;j<arr.length;j++){
              //array arr contains the field names in this case
          resultstring+= '<th>'+ arr[j] + '</th>';
      }
      $(resultset).each(function(i, result) {
          // resultset is in json format
          resultstring+='<tr>';
          for(var j=0;j<arr.length;j++){
              resultstring+='<td>'+ result[arr[j]]+ '</td>';
          }
          resultstring+='</tr>';
      });
      resultstring+='</table>';
          $('#resultdisplay').html(resultstring);

This also allows you to add rows and columns to the table dynamically, without hardcoding the fieldnames.

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function

The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts

  • Talk to the server developer for more info. You can't get more info directly.
  • Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process should not die and should return you a better code, but bugs happen there also.
  • Could be intermittent, like if the server database goes down. May be worth trying at another time.

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

CORS - How do 'preflight' an httprequest?

During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.

For example, suppose the browser makes a request with the following headers:

Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header

Your server should then respond with the following headers:

Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header

Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.

Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/

JavaScript open in a new window, not tab

OK, after making a lot of test, here my concluson:

When you perform:

     window.open('www.yourdomain.tld','_blank');
     window.open('www.yourdomain.tld','myWindow');

or whatever you put in the destination field, this will change nothing: the new page will be opened in a new tab (so depend on user preference)

If you want the page to be opened in a new "real" window, you must put extra parameter. Like:

window.open('www.yourdomain.tld', 'mywindow','location=1,status=1,scrollbars=1, resizable=1, directories=1, toolbar=1, titlebar=1');

After testing, it seems the extra parameter you use, dont' really matter: this is not the fact you put "this parameter" or "this other one" which create the new "real window" but the fact there is new parameter(s).

But something is confused and may explain a lot of wrong answers:

This:

 win1 = window.open('myurl1', 'ID_WIN');
 win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');

And this:

 win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');
 win1 = window.open('myurl1', 'ID_WIN');

will NOT give the same result.

In the first case, as you first open a page without extra parameter, it will open in a new tab. And in this case, the second call will be also opened in this tab because of the name you give.

In second case, as your first call is made with extra parameter, the page will be opened in a new "real window". And in that case, even if the second call is made without the extra parameter, it will also be opened in this new "real window"... but same tab!

This mean the first call is important as it decided where to put the page.

jQuery get html of container including the container itself

var x = $('#container').get(0).outerHTML;

UPDATE : This is now supported by Firefox as of FireFox 11 (March 2012)

As others have pointed out, this will not work in FireFox. If you need it to work in FireFox, then you might want to take a look at the answer to this question : In jQuery, are there any function that similar to html() or text() but return the whole content of matched component?

How to parse float with two decimal places in javascript?

@sd Short Answer: There is no way in JS to have Number datatype value with trailing zeros after a decimal.

Long Answer: Its the property of toFixed or toPrecision function of JavaScript, to return the String. The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype. So to achieve the above in JS we have 2 options

  1. Either use data as a string or
  2. Agree to have truncated value with case '0' at the end ex 2.50 -> 2.5. Number Cannot have trailing zeros after decimal

How to search in array of object in mongodb

The right way is:

db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})

$elemMatch allows you to match more than one component within the same array element.

Without $elemMatch mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.

See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.

Checking if jquery is loaded using Javascript

You can just type window.jQuery in Console . If it return a function(e,n) ... Then it is confirmed that the jquery is loaded and working successfully.

How to add image to canvas

You have to use .onload

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d"); 

const drawImage = (url) => {
    const image = new Image();
    image.src = url;
    image.onload = () => {
       ctx.drawImage(image, 0, 0)
    }
}

Here's Why

If you are loading the image first after the canvas has already been created then the canvas won't be able to pass all the image data to draw the image. So you need to first load all the data that came with the image and then you can use drawImage()

What’s the best way to reload / refresh an iframe?

If you tried all of the other suggestions, and couldn't get any of them to work (like I couldn't), here's something you can try that may be useful.

HTML

<a class="refresh-this-frame" rel="#iframe-id-0">Refresh</a>
<iframe src="" id="iframe-id-0"></iframe>

JS

$('.refresh-this-frame').click(function() {
    var thisIframe = $(this).attr('rel');
    var currentState = $(thisIframe).attr('src');
    function removeSrc() {
        $(thisIframe).attr('src', '');
    }
    setTimeout (removeSrc, 100);
    function replaceSrc() {
        $(thisIframe).attr('src', currentState);
    }
    setTimeout (replaceSrc, 200);
});

I initially set out to try and save some time with RWD and cross-browser testing. I wanted to create a quick page that housed a bunch of iframes, organized into groups that I would show/hide at will. Logically you'd want to be able to easily and quickly refresh any given frame.

I should note that the project I am working on currently, the one in use in this test-bed, is a one-page site with indexed locations (e.g. index.html#home). That may have had something to do with why I couldn't get any of the other solutions to refresh my particular frame.

Having said that, I know it's not the cleanest thing in the world, but it works for my purposes. Hope this helps someone. Now if only I could figure out how to keep the iframe from scrolling the parent page each time there's animation inside iframe...

EDIT: I realized that this doesn't "refresh" the iframe like I'd hoped it would. It will reload the iframe's initial source though. Still can't figure out why I couldn't get any of the other options to work..

UPDATE: The reason I couldn't get any of the other methods to work is because I was testing them in Chrome, and Chrome won't allow you to access an iframe's content (Explanation: Is it likely that future releases of Chrome support contentWindow/contentDocument when iFrame loads a local html file from local html file?) if it doesn't originate from the same location (so far as I understand it). Upon further testing, I can't access contentWindow in FF either.

AMENDED JS

$('.refresh-this-frame').click(function() {
    var targetID = $(this).attr('rel');
    var targetSrc = $(targetID).attr('src');
    var cleanID = targetID.replace("#","");     
    var chromeTest = ( navigator.userAgent.match(/Chrome/g) ? true : false );
    var FFTest = ( navigator.userAgent.match(/Firefox/g) ? true : false );      
    if (chromeTest == true) {
        function removeSrc() {
            $(targetID).attr('src', '');
        }
        setTimeout (removeSrc, 100);
        function replaceSrc() {
            $(targetID).attr('src', targetSrc);
        }
        setTimeout (replaceSrc, 200);
    }
    if (FFTest == true) {
        function removeSrc() {
            $(targetID).attr('src', '');
        }
        setTimeout (removeSrc, 100);
        function replaceSrc() {
            $(targetID).attr('src', targetSrc);
        }
        setTimeout (replaceSrc, 200);
    }       
    if (chromeTest == false && FFTest == false) {
        var targetLoc = (document.getElementById(cleanID).contentWindow.location).toString();
        function removeSrc() {
            $(targetID).attr('src', '');
        }
        setTimeout (removeSrc, 100);
        function replaceSrc2() {
            $(targetID).attr('src', targetLoc);
        }
        setTimeout (replaceSrc2, 200);
    }
});

How to play only the audio of a Youtube video using HTML 5?

You can parse Youtube meta file for all streams available for this particular video id using this link: https://www.youtube.com/get_video_info?video_id={VID} and extract audio only streams.

Here is an example with public Google Image proxy (but you can use any free or your own CORS proxy):

_x000D_
_x000D_
var vid = "3r_Z5AYJJd4",_x000D_
    audio_streams = {},_x000D_
    audio_tag = document.getElementById('youtube');_x000D_
_x000D_
fetch("https://"+vid+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=https%3A%2F%2Fwww.youtube.com%2Fget_video_info%3Fvideo_id%3D" + vid).then(response => {_x000D_
    if (response.ok) {_x000D_
        response.text().then(data => {_x000D_
_x000D_
            var data = parse_str(data),_x000D_
                streams = (data.url_encoded_fmt_stream_map + ',' + data.adaptive_fmts).split(',');_x000D_
_x000D_
            streams.forEach(function(s, n) {_x000D_
                var stream = parse_str(s),_x000D_
                    itag = stream.itag * 1,_x000D_
                    quality = false;_x000D_
                console.log(stream);_x000D_
                switch (itag) {_x000D_
                    case 139:_x000D_
                        quality = "48kbps";_x000D_
                        break;_x000D_
                    case 140:_x000D_
                        quality = "128kbps";_x000D_
                        break;_x000D_
                    case 141:_x000D_
                        quality = "256kbps";_x000D_
                        break;_x000D_
                }_x000D_
                if (quality) audio_streams[quality] = stream.url;_x000D_
            });_x000D_
_x000D_
            console.log(audio_streams);_x000D_
_x000D_
            audio_tag.src = audio_streams['128kbps'];_x000D_
            audio_tag.play();_x000D_
        })_x000D_
    }_x000D_
});_x000D_
_x000D_
function parse_str(str) {_x000D_
    return str.split('&').reduce(function(params, param) {_x000D_
        var paramSplit = param.split('=').map(function(value) {_x000D_
            return decodeURIComponent(value.replace('+', ' '));_x000D_
        });_x000D_
        params[paramSplit[0]] = paramSplit[1];_x000D_
        return params;_x000D_
    }, {});_x000D_
}
_x000D_
<audio id="youtube" autoplay controls loop></audio>
_x000D_
_x000D_
_x000D_

Doesn't work for all videos, very depends on monetization settings or something like that.

javascript filter array of objects

_x000D_
_x000D_
var names = [{_x000D_
        name: "Joe",_x000D_
        age: 20,_x000D_
        email: "[email protected]"_x000D_
    },_x000D_
    {_x000D_
        name: "Mike",_x000D_
        age: 50,_x000D_
        email: "[email protected]"_x000D_
    },_x000D_
    {_x000D_
        name: "Joe",_x000D_
        age: 45,_x000D_
        email: "[email protected]"_x000D_
    }_x000D_
];_x000D_
const res = _.filter(names, (name) => {_x000D_
    return name.name == "Joe" && name.age < 30;_x000D_
_x000D_
});_x000D_
console.log(res);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
_x000D_
_x000D_
_x000D_

JQuery .hasClass for multiple values in an if statement

For anyone wondering about some of the different performance aspects with all of these different options, I've created a jsperf case here: jsperf

In short, using element.hasClass('class') is the fastest.

Next best bet is using elem.hasClass('classA') || elem.hasClass('classB'). A note on this one: order matters! If the class 'classA' is more likely to be found, list it first! OR condition statements return as soon as one of them is met.

The worst performance by far was using element.is('.class').

Also listed in the jsperf is CyberMonk's function, and Kolja's solution.

Array.push() if does not exist?

It is quite easy to do using the Array.findIndex function, which takes a function as an argument:

var arrayObj = [{name:"bull", text: "sour"},
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]
var index = arrayObj.findIndex(x => x.name=="bob"); 
// here you can check specific property for an object whether it exist in your array or not

index === -1 ? arrayObj.push({your_object}) : console.log("object already exists")
 

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin ('null')

To check whether the frame have been loaded, use onload function. Or put your main function in load: I recommend to use load when creating the iframe by js

 $('<iframe />', {
   src: url,
   id:  'receiver',
   frameborder: 1,
   load:function(){
     //put your code here, so that those code can be make sure to be run after the frame loaded
   }
   }).appendTo('body');

How to require a controller in an angularjs directive

There is a good stackoverflow answer here by Mark Rajcok:

AngularJS directive controllers requiring parent directive controllers?

with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/

<div ng-controller="MyCtrl">
    <div screen>
        <div component>
            <div widget>
                <button ng-click="widgetIt()">Woo Hoo</button>
            </div>
        </div>
    </div>
</div>

JavaScript

var myApp = angular.module('myApp',[])

.directive('screen', function() {
    return {
        scope: true,
        controller: function() {
            this.doSomethingScreeny = function() {
                alert("screeny!");
            }
        }
    }
})

.directive('component', function() {
    return {
        scope: true,
        require: '^screen',
        controller: function($scope) {
            this.componentFunction = function() {
                $scope.screenCtrl.doSomethingScreeny();
            }
        },
        link: function(scope, element, attrs, screenCtrl) {
            scope.screenCtrl = screenCtrl
        }
    }
})

.directive('widget', function() {
    return {
        scope: true,
        require: "^component",
        link: function(scope, element, attrs, componentCtrl) {
            scope.widgetIt = function() {
                componentCtrl.componentFunction();
            };
        }
    }
})


//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
}

Why is using the JavaScript eval function a bad idea?

eval isn't always evil. There are times where it's perfectly appropriate.

However, eval is currently and historically massively over-used by people who don't know what they're doing. That includes people writing JavaScript tutorials, unfortunately, and in some cases this can indeed have security consequences - or, more often, simple bugs. So the more we can do to throw a question mark over eval, the better. Any time you use eval you need to sanity-check what you're doing, because chances are you could be doing it a better, safer, cleaner way.

To give an all-too-typical example, to set the colour of an element with an id stored in the variable 'potato':

eval('document.' + potato + '.style.color = "red"');

If the authors of the kind of code above had a clue about the basics of how JavaScript objects work, they'd have realised that square brackets can be used instead of literal dot-names, obviating the need for eval:

document[potato].style.color = 'red';

...which is much easier to read as well as less potentially buggy.

(But then, someone who /really/ knew what they were doing would say:

document.getElementById(potato).style.color = 'red';

which is more reliable than the dodgy old trick of accessing DOM elements straight out of the document object.)

turn typescript object into json string

Be careful when using these JSON.(parse/stringify) methods. I did the same with complex objects and it turned out that an embedded array with some more objects had the same values for all other entities in the object tree I was serializing.

const temp = [];
const t = {
    name: "name",
    etc: [
        {
            a: 0,
        },
    ],
};
for (let i = 0; i < 3; i++) {
    const bla = Object.assign({}, t);
    bla.name = bla.name + i;
    bla.etc[0].a = i;
    temp.push(bla);
}

console.log(JSON.stringify(temp));

How do I create JavaScript array (JSON format) dynamically?

Our array of objects

var someData = [
   {firstName: "Max", lastName: "Mustermann", age: 40},
   {firstName: "Hagbard", lastName: "Celine", age: 44},
   {firstName: "Karl", lastName: "Koch", age: 42},
];

with for...in

var employees = {
    accounting: []
};

for(var i in someData) {    

    var item = someData[i];   

    employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

or with Array.prototype.map(), which is much cleaner:

var employees = {
    accounting: []
};

someData.map(function(item) {        
   employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

Detecting when a div's height changes using jQuery

This is how I recently handled this problem:

$('#your-resizing-div').bind('getheight', function() {
    $('#your-resizing-div').height();
});

function your_function_to_load_content() {
    /*whatever your thing does*/
    $('#your-resizing-div').trigger('getheight');
}

I know I'm a few years late to the party, just think my answer may help some people in the future, without having to download any plugins.

how to automatically scroll down a html page?

here is the example using Pure JavaScript

_x000D_
_x000D_
function scrollpage() {  _x000D_
 function f() _x000D_
 {_x000D_
  window.scrollTo(0,i);_x000D_
  if(status==0) {_x000D_
      i=i+40;_x000D_
   if(i>=Height){ status=1; } _x000D_
  } else {_x000D_
   i=i-40;_x000D_
   if(i<=1){ status=0; }  // if you don't want continue scroll then remove this line_x000D_
  }_x000D_
 setTimeout( f, 0.01 );_x000D_
 }f();_x000D_
}_x000D_
var Height=document.documentElement.scrollHeight;_x000D_
var i=1,j=Height,status=0;_x000D_
scrollpage();_x000D_
</script>
_x000D_
<style type="text/css">_x000D_
_x000D_
 #top { border: 1px solid black;  height: 20000px; }_x000D_
 #bottom { border: 1px solid red; }_x000D_
_x000D_
</style>
_x000D_
<div id="top">top</div>_x000D_
<div id="bottom">bottom</div>
_x000D_
_x000D_
_x000D_

How can I mock an ES6 module import using Jest?

I've been able to solve this by using a hack involving import *. It even works for both named and default exports!

For a named export:

// dependency.js
export const doSomething = (y) => console.log(y)

// myModule.js
import { doSomething } from './dependency';

export default (x) => {
  doSomething(x * 2);
}

// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    dependency.doSomething = jest.fn(); // Mutate the named export

    myModule(2);

    expect(dependency.doSomething).toBeCalledWith(4);
  });
});

Or for a default export:

// dependency.js
export default (y) => console.log(y)

// myModule.js
import dependency from './dependency'; // Note lack of curlies

export default (x) => {
  dependency(x * 2);
}

// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    dependency.default = jest.fn(); // Mutate the default export

    myModule(2);

    expect(dependency.default).toBeCalledWith(4); // Assert against the default
  });
});

As Mihai Damian quite rightly pointed out below, this is mutating the module object of dependency, and so it will 'leak' across to other tests. So if you use this approach you should store the original value and then set it back again after each test.

To do this easily with Jest, use the spyOn() method instead of jest.fn(), because it supports easily restoring its original value, therefore avoiding before mentioned 'leaking'.

Obtain form input fields using jQuery?

I hope this is helpful, as well as easiest one.

 $("#form").submit(function (e) { 
    e.preventDefault();
    input_values =  $(this).serializeArray();
  });

How to disable submit button once it has been clicked?

You need to disable the button in the onsubmit event of the <form>:

<form action='/' method='POST' onsubmit='disableButton()'>
    <input name='txt' type='text' required />
    <button id='btn' type='submit'>Post</button>
</form>

<script>
    function disableButton() {
        var btn = document.getElementById('btn');
        btn.disabled = true;
        btn.innerText = 'Posting...'
    }
</script>

Note: this way if you have a form element which has the required attribute will work.

Run JavaScript code on window close or page refresh?

The event is called beforeunload, so you can assign a function to window.onbeforeunload.

Render Content Dynamically from an array map function in React Native

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })
}

You forgot to return the map. this code will resolve the issue.

querySelector, wildcard element match?

[id^='someId'] will match all ids starting with someId.

[id$='someId'] will match all ids ending with someId.

[id*='someId'] will match all ids containing someId.

If you're looking for the name attribute just substitute id with name.

If you're talking about the tag name of the element I don't believe there is a way using querySelector

How to get unique values in an array

One Liner, Pure JavaScript

With ES6 syntax

list = list.filter((x, i, a) => a.indexOf(x) === i)

x --> item in array
i --> index of item
a --> array reference, (in this case "list")

enter image description here

With ES5 syntax

list = list.filter(function (x, i, a) { 
    return a.indexOf(x) === i; 
});

Browser Compatibility: IE9+

Scroll Automatically to the Bottom of the Page

You can use this function wherever you need to call it:

function scroll_to(div){
   if (div.scrollTop < div.scrollHeight - div.clientHeight)
        div.scrollTop += 10; // move down

}

jquery.com: ScrollTo

Add key value pair to all objects in array

I would be a little cautious with some of the answers presented in here, the following examples outputs differently according with the approach:

const list = [ { a : 'a', b : 'b' } , { a : 'a2' , b : 'b2' }]

console.log(list.map(item => item.c = 'c'))
// [ 'c', 'c' ]

console.log(list.map(item => {item.c = 'c'; return item;}))
// [ { a: 'a', b: 'b', c: 'c' }, { a: 'a2', b: 'b2', c: 'c' } ]

console.log(list.map(item => Object.assign({}, item, { c : 'c'})))
// [ { a: 'a', b: 'b', c: 'c' }, { a: 'a2', b: 'b2', c: 'c' } ]

I have used node v8.10.0 to test the above pieces of code.

Remove Object from Array using JavaScript

Use splice function on arrays. Specify the position of the start element and the length of the subsequence you want to remove.

someArray.splice(pos, 1);

Missing .map resource?

jQuery recently started using source maps.

For example, let's look at the minified jQuery 2.0.3 file's first few lines.

/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/

Excerpt from Introduction to JavaScript Source Maps:

Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.

emphasis mine

It's incredibly useful, and will only download if the user opens dev tools.

Solution

Remove the source mapping line, or do nothing. It isn't really a problem.


Side note: your server should return 404, not 500. It could point to a security problem if this happens in production.

How do I get the width and height of a HTML5 canvas?

I had a problem because my canvas was inside of a container without ID so I used this jquery code below

$('.cropArea canvas').width()

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

Just wishing to avoid the console error, I solved this using a similar approach to Artur's earlier answer, following these steps:

  1. Downloaded the YouTube Iframe API (from https://www.youtube.com/iframe_api) to a local yt-api.js file.
  2. Removed the code which inserted the www-widgetapi.js script.
  3. Downloaded the www-widgetapi.js script (from https://s.ytimg.com/yts/jsbin/www-widgetapi-vfl7VfO1r/www-widgetapi.js) to a local www-widgetapi.js file.
  4. Replaced the targetOrigin argument in the postMessage call which was causing the error in the console, with a "*" (indicating no preference - see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage).
  5. Appended the modified www-widgetapi.js script to the end of the yt-api.js script.

This is not the greatest solution (patched local script to maintain, losing control of where messages are sent) but it solved my issue.

Please see the security warning about removing the targetOrigin URI stated here before using this solution - https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Patched yt-api.js example

Pass value to iframe from a window

We can use "postMessage" concept for sending data to an underlying iframe from main window.

you can checkout more about postMessage using this link add the below code inside main window page

// main window code
window.frames['myFrame'].contentWindow.postMessage("Hello World!");

we will pass "Hello World!" message to an iframe contentWindow with iframe id="myFrame".

now add the below code inside iframe source code

// iframe document code
function receive(event) {
    console.log("Received Message : " + event.data);
}
window.addEventListener('message', receive);

in iframe webpage we will attach an event listener to receive event and in 'receive' callback we will print the data to console

What's the difference between event.stopPropagation and event.preventDefault?

TL;DR
event.preventDefault()
Prevents the browsers default behaviour (such as opening a link), but does not stop the event from bubbling up the DOM.

event.stopPropagation()
Prevents the event from bubbling up the DOM, but does not stop the browsers default behaviour.

return false;
Usually seen in jQuery code, it Prevents the browsers default behaviour, Prevents the event from bubbling up the DOM, and immediately Returns from any callback.

One should checkout this really nice & easy 4 min read with examples from where the above piece was copied from.

Javascript Get Values from Multiple Select Option Box

The for loop is getting one extra run. Change

for (x=0;x<=InvForm.SelBranch.length;x++)

to

for (x=0; x < InvForm.SelBranch.length; x++)

Select values of checkbox group with jQuery

You can have a javascript variable which stores the number of checkboxes that are emitted, i.e in the <head> of the page:

<script type="text/javascript">
var num_cboxes=<?php echo $number_of_checkboxes;?>;
</script>

So if there are 10 checkboxes, starting from user_group-1 to user_group-10, in the javascript code you would get their value in this way:

var values=new Array();
for (x=1; x<=num_cboxes; x++)
{
   values[x]=$("#user_group-" + x).val();
}

How to get the anchor from the URL using jQuery?

Use

window.location.hash

to retrieve everything beyond and including the #

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

You're using the wrong post parameters:

    var dataString = 'name='+ name + '&email=' + email + '&text=' + text;
                      ^^^^-$_POST['name']
                                       ^^^^--$_POST['name']
                                      etc....

The javascript/html IDs are irrelevant to the actual POST, especially when you're building your own data string and don't use those same IDs.

How to check for an empty object in an AngularJS view

I have met a similar problem when checking emptiness in a component. In this case, the controller must define a method that actually performs the test and the view uses it:

function FormNumericFieldController(/*$scope, $element, $attrs*/ ) {
    var ctrl = this;

    ctrl.isEmptyObject = function(object) {
        return angular.equals(object, {});
    }
}

<!-- any validation error will trigger an error highlight -->
<span ng-class="{'has-error': !$ctrl.isEmptyObject($ctrl.formFieldErrorRef) }">
    <!-- validated control here -->
</span>

'console' is undefined error for Internet Explorer

You can use console.log(...) directly in Firefox but not in IEs. In IEs you have to use window.console.

How to fire an event when v-model changes?

Just to add to the correct answer above, in Vue.JS v1.0 you can write

<a v-on:click="doSomething">

So in this example it would be

 v-on:change="foo"

See: http://v1.vuejs.org/guide/syntax.html#Arguments

How do I return the response from an asynchronous call?

Here are some approaches to work with asynchronous requests:

  1. Browser Promise object
  2. Q - A promise library for JavaScript
  3. A+ Promises.js
  4. jQuery deferred
  5. XMLHttpRequest API
  6. Using callback concept - As implementation in first answer

Example: jQuery deferred implementation to work with multiple requests

_x000D_
_x000D_
var App = App || {};

App = {
    getDataFromServer: function(){

      var self = this,
                 deferred = $.Deferred(),
                 requests = [];

      requests.push($.getJSON('request/ajax/url/1'));
      requests.push($.getJSON('request/ajax/url/2'));

      $.when.apply(jQuery, requests).done(function(xhrResponse) {
        return deferred.resolve(xhrResponse.result);
      });
      return deferred;
    },

    init: function(){

        this.getDataFromServer().done(_.bind(function(resp1, resp2) {

           // Do the operations which you wanted to do when you
           // get a response from Ajax, for example, log response.
        }, this));
    }
};
App.init();
_x000D_
_x000D_
_x000D_

How to break/exit from a each() function in JQuery?

Return false from the anonymous function:

$(xml).find("strengths").each(function() {
  // Code
  // To escape from this block based on a condition:
  if (something) return false;
});

From the documentation of the each method:

Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).

Calling a JSON API with Node.js

Another solution is to user axios:

npm install axios

Code will be like:

const url = `${this.env.someMicroservice.address}/v1/my-end-point`;

const { data } = await axios.get<MyInterface>(url, {
  auth: {
    username: this.env.auth.user,
    password: this.env.auth.pass
  }
});

return data;

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

Basically, yes. You write alert('<?php echo($phpvariable); ?>');

There are sure other ways to interoperate, but none of which i can think of being as simple (or better) as the above.

How do you get the length of a string?

It's not jquery you need, it's JS:

alert(str.length);

HTML Mobile -forcing the soft keyboard to hide

For further readers/searchers:

As Rene Pot points out on this topic,

By adding the attribute readonly (or readonly="readonly") to the input field you should prevent anyone typing anything in it, but still be able to launch a click event on it.

With this method, you can avoid popping up the "soft" Keyboard and still launch click events / fill the input by any on-screen keyboard.

This solution also works fine with date-time-pickers which generally already implement controls.

How do I send a file in Android from a mobile device to server using http?

the most effective method is to use android-async-http

You can use this code to upload a file:

// gather your request parameters
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
    params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}

// send request
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
        // handle success response
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) {
        // handle failure response
    }
});

Note that you can put this code directly into your main Activity, no need to create a background Task explicitly. AsyncHttp will take care of that for you!

Select unique or distinct values from a list in UNIX shell script

For larger data sets where sorting may not be desirable, you can also use the following perl script:

./yourscript.ksh | perl -ne 'if (!defined $x{$_}) { print $_; $x{$_} = 1; }'

This basically just remembers every line output so that it doesn't output it again.

It has the advantage over the "sort | uniq" solution in that there's no sorting required up front.

Remove category & tag base from WordPress url - without a plugin

WordPress 5.0.2:

To remove category slug from existing posts, do this :

  1. Navigate to Settings > Permalinks and change Custom Structure from /%category%/%postname%/ to: /%postname%/
  2. Keep Category and Tag bases empty (which is the default also)
  3. Save

All posts can now be directly accessed via domain.com/%postname%/ and all categories can be accessed via domain.com/category/xyz/. WordPress will automatically add all the 301 redirects for the old urls. So, if someone accesses domain.com/%category%/%postname%/, they will automatically get redirected to domain.com/%postname%/.

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

This issue happened in my project because of an ajax GET call with a long xml string as a parameter value. Solved by the following approach: Making it as ajax post call to Java Spring MVC controller class method like this.

$.ajax({
    url: "controller_Method_Name.html?variable_name="+variable_value,
    type: "POST",
    data:{ 
            "xmlMetaData": xmlMetaData // This variable contains a long xml string
    },
    success: function(response)
    {
        console.log(response);
    }
  });

Inside Spring MVC Controller class method:

@RequestMapping(value="/controller_Method_Name")
  public void controller_Method_Name(@RequestParam("xmlMetaData") String metaDataXML, HttpServletRequest request)
{
   System.out.println(metaDataXML);
}

Create file path from variables

You can also use an object-oriented path with pathlib (available as a standard library as of Python 3.4):

from pathlib import Path

start_path = Path('/my/root/directory')
final_path = start_path / 'in' / 'here'

Java string to date conversion

Ah yes the Java Date discussion, again. To deal with date manipulation we use Date, Calendar, GregorianCalendar, and SimpleDateFormat. For example using your January date as input:

Calendar mydate = new GregorianCalendar();
String mystring = "January 2, 2010";
Date thedate = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(mystring);
mydate.setTime(thedate);
//breakdown
System.out.println("mydate -> "+mydate);
System.out.println("year   -> "+mydate.get(Calendar.YEAR));
System.out.println("month  -> "+mydate.get(Calendar.MONTH));
System.out.println("dom    -> "+mydate.get(Calendar.DAY_OF_MONTH));
System.out.println("dow    -> "+mydate.get(Calendar.DAY_OF_WEEK));
System.out.println("hour   -> "+mydate.get(Calendar.HOUR));
System.out.println("minute -> "+mydate.get(Calendar.MINUTE));
System.out.println("second -> "+mydate.get(Calendar.SECOND));
System.out.println("milli  -> "+mydate.get(Calendar.MILLISECOND));
System.out.println("ampm   -> "+mydate.get(Calendar.AM_PM));
System.out.println("hod    -> "+mydate.get(Calendar.HOUR_OF_DAY));

Then you can manipulate that with something like:

Calendar now = Calendar.getInstance();
mydate.set(Calendar.YEAR,2009);
mydate.set(Calendar.MONTH,Calendar.FEBRUARY);
mydate.set(Calendar.DAY_OF_MONTH,25);
mydate.set(Calendar.HOUR_OF_DAY,now.get(Calendar.HOUR_OF_DAY));
mydate.set(Calendar.MINUTE,now.get(Calendar.MINUTE));
mydate.set(Calendar.SECOND,now.get(Calendar.SECOND));
// or with one statement
//mydate.set(2009, Calendar.FEBRUARY, 25, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND));
System.out.println("mydate -> "+mydate);
System.out.println("year   -> "+mydate.get(Calendar.YEAR));
System.out.println("month  -> "+mydate.get(Calendar.MONTH));
System.out.println("dom    -> "+mydate.get(Calendar.DAY_OF_MONTH));
System.out.println("dow    -> "+mydate.get(Calendar.DAY_OF_WEEK));
System.out.println("hour   -> "+mydate.get(Calendar.HOUR));
System.out.println("minute -> "+mydate.get(Calendar.MINUTE));
System.out.println("second -> "+mydate.get(Calendar.SECOND));
System.out.println("milli  -> "+mydate.get(Calendar.MILLISECOND));
System.out.println("ampm   -> "+mydate.get(Calendar.AM_PM));
System.out.println("hod    -> "+mydate.get(Calendar.HOUR_OF_DAY));

How to trigger a build only if changes happen on particular set of files

If you are using a declarative syntax of Jenkinsfile to describe your building pipeline, you can use changeset condition to limit stage execution only to the case when specific files are changed. This is now a standard feature of Jenkins and does not require any additional configruation/software.

stages {
    stage('Nginx') {
        when { changeset "nginx/*"}
        steps {
            sh "make build-nginx"
            sh "make start-nginx"
        }
    }
}

You can combine multiple conditions using anyOf or allOf keywords for OR or AND behaviour accordingly:

when {
    anyOf {
        changeset "nginx/**"
        changeset "fluent-bit/**"
    }
}
steps {
    sh "make build-nginx"
    sh "make start-nginx"
}

How to limit google autocomplete results to City and Country only

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<style type="text/css">_x000D_
   body {_x000D_
         font-family: sans-serif;_x000D_
         font-size: 14px;_x000D_
   }_x000D_
</style>_x000D_
_x000D_
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places" type="text/javascript"></script>_x000D_
<script type="text/javascript">_x000D_
   function initialize() {_x000D_
      var input = document.getElementById('searchTextField');_x000D_
      var options = {_x000D_
        types: ['geocode'] //this should work !_x000D_
      };_x000D_
      var autocomplete = new google.maps.places.Autocomplete(input, options);_x000D_
   }_x000D_
   google.maps.event.addDomListener(window, 'load', initialize);_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
   <div>_x000D_
      <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">_x000D_
   </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

var options = {
  types: ['geocode'] //this should work !
};
var autocomplete = new google.maps.places.Autocomplete(input, options);

reference to other types: http://code.google.com/apis/maps/documentation/places/supported_types.html#table2

Fixing Segmentation faults in C++

I don't know of any methodology to use to fix things like this. I don't think it would be possible to come up with one either for the very issue at hand is that your program's behavior is undefined (I don't know of any case when SEGFAULT hasn't been caused by some sort of UB).

There are all kinds of "methodologies" to avoid the issue before it arises. One important one is RAII.

Besides that, you just have to throw your best psychic energies at it.

Storing money in a decimal column - what precision and scale?

We recently implemented a system that needs to handle values in multiple currencies and convert between them, and figured out a few things the hard way.

NEVER USE FLOATING POINT NUMBERS FOR MONEY

Floating point arithmetic introduces inaccuracies that may not be noticed until they've screwed something up. All values should be stored as either integers or fixed-decimal types, and if you choose to use a fixed-decimal type then make sure you understand exactly what that type does under the hood (ie, does it internally use an integer or floating point type).

When you do need to do calculations or conversions:

  1. Convert values to floating point
  2. Calculate new value
  3. Round the number and convert it back to an integer

When converting a floating point number back to an integer in step 3, don't just cast it - use a math function to round it first. This will usually be round, though in special cases it could be floor or ceil. Know the difference and choose carefully.

Store the type of a number alongside the value

This may not be as important for you if you're only handling one currency, but it was important for us in handling multiple currencies. We used the 3-character code for a currency, such as USD, GBP, JPY, EUR, etc.

Depending on the situation, it may also be helpful to store:

  • Whether the number is before or after tax (and what the tax rate was)
  • Whether the number is the result of a conversion (and what it was converted from)

Know the accuracy bounds of the numbers you're dealing with

For real values, you want to be as precise as the smallest unit of the currency. This means you have no values smaller than a cent, a penny, a yen, a fen, etc. Don't store values with higher accuracy than that for no reason.

Internally, you may choose to deal with smaller values, in which case that's a different type of currency value. Make sure your code knows which is which and doesn't get them mixed up. Avoid using floating point values even here.


Adding all those rules together, we decided on the following rules. In running code, currencies are stored using an integer for the smallest unit.

class Currency {
   String code;       //  eg "USD"
   int value;         //  eg 2500
   boolean converted;
}

class Price {
   Currency grossValue;
   Currency netValue;
   Tax taxRate;
}

In the database, the values are stored as a string in the following format:

USD:2500

That stores the value of $25.00. We were able to do that only because the code that deals with currencies doesn't need to be within the database layer itself, so all values can be converted into memory first. Other situations will no doubt lend themselves to other solutions.


And in case I didn't make it clear earlier, don't use float!

Calling Objective-C method from C++ member function?

The easiest solution is to simply tell Xcode to compile everything as Objective C++.

Set your project or target settings for Compile Sources As to Objective C++ and recompile.

Then you can use C++ or Objective C everywhere, for example:

void CPPObject::Function( ObjectiveCObject* context, NSView* view )
{
   [context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)view.layer]
}

This has the same affect as renaming all your source files from .cpp or .m to .mm.

There are two minor downsides to this: clang cannot analyse C++ source code; some relatively weird C code does not compile under C++.

How to cast List<Object> to List<MyClass>

You can't because List<Object> and List<Customer> are not in the same inheritance tree.

You could add a new constructor to your List<Customer> class that takes a List<Object> and then iterate through the list casting each Object to a Customer and adding it to your collection. Be aware that an invalid cast exception can occur if the caller's List<Object> contains something that isn't a Customer.

The point of generic lists is to constrain them to certain types. You're trying to take a list that can have anything in it (Orders, Products, etc.) and squeeze it into a list that can only take Customers.

HTML5 input type range show range value

Shortest version without form, min or external JavaScript.

_x000D_
_x000D_
<input type="range" value="0" max="10" oninput="num.value = this.value">
<output id="num">0</output>
_x000D_
_x000D_
_x000D_

Explanation

If you wanna retrieve the value from the output you commonly use an id that can be linked from the oninput instead of using this.nextElementSibling.value (we take advantage of something that we are already using)

Compare the example above with this valid but a little more complex and long answer:

<input id="num" type="range" value="0" max="100" oninput="this.nextElementSibling.value = this.value">
<output>0</output>

With the shortest answer:

  • We avoid the use of this, something weird in JS for newcomers
  • We avoid new concept about connecting siblings in the DOM
  • We avoid too much attributes in the input placing the id in the output

Notes

  • In both examples we don't need to add the min value when equal to 0
  • Removing JavaScript’s this keyword makes it a better language

How to replace a character by a newline in Vim

You need to use:

:%s/,/^M/g

To get the ^M character, press Ctrl + v followed by Enter.

What is it exactly a BLOB in a DBMS context

This may seem like a silly question, but what do you actually want to use a RDBMS for ?

If you just want to store files, then the operating system's filesystem is generally adequate. An RDBMS is generally used for structured data and (except for embedded ones like SQLite) handling concurrent manipulation of that data (locking etc). Other useful features are security (handling access to the data) and backup/recovery. In the latter, the primary advantage over a regular filesystem backup is being able to recover to a point in time between backups by applying some form of log files.

BLOBs are, as far as the database concerned, unstructured and opaque. Oracle does have some specific ORDSYS types for multi-media objects (eg images) that also have a bunch of metadata attached, and have associated methods (eg rescaling or recolouring an image).

Parsing a JSON array using Json.Net

You can get at the data values like this:

string json = @"
[ 
    { ""General"" : ""At this time we do not have any frequent support requests."" },
    { ""Support"" : ""For support inquires, please see our support page."" }
]";

JArray a = JArray.Parse(json);

foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = (string)p.Value;
        Console.WriteLine(name + " -- " + value);
    }
}

Fiddle: https://dotnetfiddle.net/uox4Vt

Stripping everything but alphanumeric chars from a string in Python

>>> import re
>>> string = "Kl13@£$%[};'\""
>>> pattern = re.compile('\W')
>>> string = re.sub(pattern, '', string)
>>> print string
Kl13

What does the colon (:) operator do?

There are several places colon is used in Java code:

1) Jump-out label (Tutorial):

label: for (int i = 0; i < x; i++) {
    for (int j = 0; j < i; j++) {
        if (something(i, j)) break label; // jumps out of the i loop
    }
} 
// i.e. jumps to here

2) Ternary condition (Tutorial):

int a = (b < 4)? 7: 8; // if b < 4, set a to 7, else set a to 8

3) For-each loop (Tutorial):

String[] ss = {"hi", "there"}
for (String s: ss) {
    print(s); // output "hi" , and "there" on the next iteration
}

4) Assertion (Guide):

int a = factorial(b);
assert a >= 0: "factorial may not be less than 0"; // throws an AssertionError with the message if the condition evaluates to false

5) Case in switch statement (Tutorial):

switch (type) {
    case WHITESPACE:
    case RETURN:
        break;
    case NUMBER:
        print("got number: " + value);
        break;
    default:
        print("syntax error");
}

6) Method references (Tutorial)

class Person {
   public static int compareByAge(Person a, Person b) {
       return a.birthday.compareTo(b.birthday);
   }}
}

Arrays.sort(persons, Person::compareByAge);

"unrecognized import path" with go get

Because GFW forbidden you to access golang.org ! And when i use the proxy , it can work well.

you can look at the information using command go get -v -u golang.org/x/oauth2

Check if a specific value exists at a specific key in any subarray of a multidimensional array

As in your question, which is actually a simple 2-D array wouldn't it be better? Have a look-

Let say your 2-D array name $my_array and value to find is $id

function idExists($needle='', $haystack=array()){
    //now go through each internal array
    foreach ($haystack as $item) {
        if ($item['id']===$needle) {
            return true;
        }
    }
    return false;
}

and to call it:

idExists($id, $my_array);

As you can see, it actually only check if any internal index with key_name 'id' only, have your $value. Some other answers here might also result true if key_name 'name' also has $value

CSS to select/style first word

Sadly even with the likes of CSS 3 we still do not have the likes of :first-word :last-word etc using pure CSS. Thankfully there's almost a JavaScript nowadays for everything which brings me to my recommendation. Using nthEverything and jQuery you can expand from the traditional Pseudo elements.

Currently the valid Pseudos are:

  • :first-child
  • :first-of-type
  • :only-child
  • :last-child
  • :last-of-type
  • :only-of-type
  • :nth-child
  • :nth-of-type
  • :nth-last-child
  • :nth-last-of-type

And using nth Everything we can expand this to:

  • ::first-letter
  • ::first-line
  • ::first-word
  • ::last-letter
  • ::last-line
  • ::last-word
  • ::nth-letter
  • ::nth-line
  • ::nth-word
  • ::nth-last-letter
  • ::nth-last-line
  • ::nth-last-word

How to get the last character of a string in a shell?

Per @perreal, quoting variables is important, but because I read this post like 5 times before finding a simpler approach to the question at hand in the comments...

str='abcd/'
echo "${str: -1}"

Output: /

str='abcd*'
echo "${str: -1}"

Output: *

Thanks to everyone who participated in this above; I've appropriately added +1's throughout the thread!

How do I print to the debug output window in a Win32 app?

You can also use WriteConsole method to print on console.

AllocConsole();
LPSTR lpBuff = "Hello Win32 API";
DWORD dwSize = 0;
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), lpBuff, lstrlen(lpBuff), &dwSize, NULL);

Convert a character digit to the corresponding integer in C

If it's just a single character 0-9 in ASCII, then subtracting the the value of the ASCII zero character from ASCII value should work fine.

If you want to convert larger numbers then the following will do:

char *string = "24";

int value;

int assigned = sscanf(string, "%d", &value);

** don't forget to check the status (which should be 1 if it worked in the above case).

Paul.

How do I read a text file of about 2 GB?

WordPad will open any text file no matter the size. However, it has limited capabilities as compared to a text editor.

Auto-center map with multiple markers in Google Maps API v3

I've tryied all answers of this topic, but just this below worked fine on my project.

Angular 7 and AGM Core 1.0.0-beta.7

<agm-map [latitude]="lat" [longitude]="long" [zoom]="zoom" [fitBounds]="true">
  <agm-marker latitude="{{localizacao.latitude}}" longitude="{{localizacao.longitude}}" [agmFitBounds]="true"
    *ngFor="let localizacao of localizacoesTec">
  </agm-marker>
</agm-map>

The properties [agmFitBounds]="true" at agm-marker and [fitBounds]="true" at agm-map does the job

_tkinter.TclError: no display name and no $DISPLAY environment variable

To add up on the answer, I used this at the beginning of the needed script. So it runs smoothly on different environments.

import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
    print('no display found. Using non-interactive Agg backend')
    mpl.use('Agg')
import matplotlib.pyplot as plt

Because I didn't want it to be alsways using the 'Agg' backend, only when it would go through Travis CI for example.

JavaFX FXML controller - constructor vs initialize method

In Addition to the above answers, there probably should be noted that there is a legacy way to implement the initialization. There is an interface called Initializable from the fxml library.

import javafx.fxml.Initializable;

class MyController implements Initializable {
    @FXML private TableView<MyModel> tableView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        tableView.getItems().addAll(getDataFromSource());
    }
}

Parameters:

location - The location used to resolve relative paths for the root object, or null if the location is not known.
resources - The resources used to localize the root object, or null if the root object was not localized. 

And the note of the docs why the simple way of using @FXML public void initialize() works:

NOTE This interface has been superseded by automatic injection of location and resources properties into the controller. FXMLLoader will now automatically call any suitably annotated no-arg initialize() method defined by the controller. It is recommended that the injection approach be used whenever possible.

Continue For loop

For the case you do not use "DO": this is my solution for a FOR EACH with nested If conditional statements:

For Each line In lines
    If <1st condition> Then
        <code if 1st condition>
        If <2nd condition> Then
            If <3rd condition> Then
                GoTo ContinueForEach
            Else
                <code else 3rd condition>
            End If
        Else
            <code else 2nd condition>
        End If
    Else
        <code else 1st condition>
    End If
ContinueForEach:
Next

Detect if value is number in MySQL

Still missing this simple version:

SELECT * FROM myTable WHERE `col1` + 0 = `col1`

(addition should be faster as multiplication)

Or slowest version for further playing:

SELECT *, 
CASE WHEN `col1` + 0 = `col1` THEN 1 ELSE 0 END AS `IS_NUMERIC` 
FROM `myTable`
HAVING `IS_NUMERIC` = 1

Keystore type: which one to use?

If you are using Java 8 or newer you should definitely choose PKCS12, the default since Java 9 (JEP 229).

The advantages compared to JKS and JCEKS are:

  • Secret keys, private keys and certificates can be stored
  • PKCS12 is a standard format, it can be read by other programs and libraries1
  • Improved security: JKS and JCEKS are pretty insecure. This can be seen by the number of tools for brute forcing passwords of these keystore types, especially popular among Android developers.2, 3

1 There is JDK-8202837, which has been fixed in Java 11

2 The iteration count for PBE used by all keystore types (including PKCS12) used to be rather weak (CVE-2017-10356), however this has been fixed in 9.0.1, 8u151, 7u161, and 6u171

3 For further reading:

How to convert date format to milliseconds?

date.setTime(milliseconds);

this is for set milliseconds in date

long milli = date.getTime();

This is for get time in milliseconds.

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT

Python circular importing?

For those of you who, like me, come to this issue from Django, you should know that the docs provide a solution: https://docs.djangoproject.com/en/1.10/ref/models/fields/#foreignkey

"...To refer to models defined in another application, you can explicitly specify a model with the full application label. For example, if the Manufacturer model above is defined in another application called production, you’d need to use:

class Car(models.Model):
    manufacturer = models.ForeignKey(
        'production.Manufacturer',
        on_delete=models.CASCADE,
)

This sort of reference can be useful when resolving circular import dependencies between two applications...."

How to insert image in mysql database(table)?

If I use the following query,

INSERT INTO xx_BLOB(ID,IMAGE) 
VALUES(1,LOAD_FILE('E:/Images/xxx.png'));

Error: no such function: LOAD_FILE

Deleting queues in RabbitMQ

Another option would be to enable the management_plugin and connect to it over a browser. You can see all queues and information about them. It is possible and simple to delete queues from this interface.

Completely Remove MySQL Ubuntu 14.04 LTS

I experienced a similar issue on Ubuntu 14.04 LTS after a MySQL update.

I started getting error: "Fatal error: Can't open and lock privilege tables: Incorrect file format 'user'" in /var/log/mysql/error.log

MySQL could not start.

I resolved it by removing the following directory: /var/lib/mysql/mysql

sudo rm -rf /var/lib/mysql/mysql

This leaves your other DB related files in place, only removing the mysql related files.

After running these:

sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean

Then reinstalling mysql:

sudo apt-get install mysql-server

It worked perfectly.

Checking for empty queryset in Django

Since version 1.2, Django has QuerySet.exists() method which is the most efficient:

if orgs.exists():
    # Do this...
else:
    # Do that...

But if you are going to evaluate QuerySet anyway it's better to use:

if orgs:
   ...

For more information read QuerySet.exists() documentation.

How do I determine height and scrolling position of window in jQuery?

If you need to scroll to a point of an element. You can use Jquery function to scroll it up/down.

$('html, body').animate({
                scrollTop: $("#div1").offset().top
            }, 'slow');

Find TODO tags in Eclipse

In adition to the other answers mentioning the Tasks view:

It is also possible to filter the Tasks that are listed to only show the TODOs that contain the text // TODO Auto-generated method stub.

To achieve this you can click on the Filters... button in the top right of the Tasks View and define custom filters like this:

enter image description here

This way it's a bit easier and faster to find only some of the TODOs in the project in the Tasks View, and you don't have to search for the text in all files using the eclipse search tool (which can take quite some time).

How do you count the lines of code in a Visual Studio solution?

I used Ctrl+Shift+F. Next, put a \n in the search box and enable regular expressions box. Then in the find results, in the end of the screen are the number of files searched and lines of code found.

You can use [^\n\s]\r\n to skip blank and space-only lines (credits to Zach in the comments).

IntelliJ show JavaDocs tooltip on mouse over

On mac in IntelliJ Ultimate (trial) 14 I have mine under Settings > Editor > General > Code completion. The tooltip short is F1 on my laptop.

It's called "Autopopup documentation in (ms):"

enter image description here

Change auto increment starting number?

You can use ALTER TABLE to change the auto_increment initial value:

ALTER TABLE tbl AUTO_INCREMENT = 5;

See the MySQL reference for more details.

Directory-tree listing in Python

A recursive implementation

import os

def scan_dir(dir):
    for name in os.listdir(dir):
        path = os.path.join(dir, name)
        if os.path.isfile(path):
            print path
        else:
            scan_dir(path)

How do I update Homebrew?

  • cd /usr/local
  • git status
  • Discard all the changes (unless you actually want to try to commit to Homebrew - you probably don't)
  • git status til it's clean
  • brew update

Automatically create requirements.txt

If you use virtual environment, pip freeze > requirements.txt just fine. IF NOT, pigar will be a good choice for you.

By the way, I do not ensure it will work with 2.6.

UPDATE:

Pipenv or other tools is recommended for improving your development flow.

For Python 3 use below

pip3 freeze > requirements.txt

Using async/await with a forEach loop

Here are some forEachAsync prototypes. Note you'll need to await them:

Array.prototype.forEachAsync = async function (fn) {
    for (let t of this) { await fn(t) }
}

Array.prototype.forEachAsyncParallel = async function (fn) {
    await Promise.all(this.map(fn));
}

Note while you may include this in your own code, you should not include this in libraries you distribute to others (to avoid polluting their globals).

How can you use php in a javascript function

despite some comments, at some cases it's really necessary to access PHP functions at Javascript (e.g. the AJAX cases).

At these cases you can use the mwsX library to use your PHP functions at Javascript.

mwsX library: https://github.com/loureirorg/mwsx

Flex-box: Align last row to grid

A possible solution is to use justify-content: flex-start; on the .grid container, size restrictions on its children, and margins on the appropriate child elements -- depending on the desired number of columns.

For a 3-column grid, the basic CSS would look like this:

.grid {
    display: flex;
    flex-flow: row wrap;
    justify-content: flex-start;
}

.grid > * {
    flex: 0 0 32%;
    margin: 1% 0;
}

.grid > :nth-child(3n-1) {
    margin-left: 2%;
    margin-right: 2%;
}

It's another imperfect solution, but it works.

http://codepen.io/tuxsudo/pen/VYERQJ

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

SQL left join vs multiple tables on FROM line?

Basically, when your FROM clause lists tables like so:

SELECT * FROM
  tableA, tableB, tableC

the result is a cross product of all the rows in tables A, B, C. Then you apply the restriction WHERE tableA.id = tableB.a_id which will throw away a huge number of rows, then further ... AND tableB.id = tableC.b_id and you should then get only those rows you are really interested in.

DBMSs know how to optimise this SQL so that the performance difference to writing this using JOINs is negligible (if any). Using the JOIN notation makes the SQL statement more readable (IMHO, not using joins turns the statement into a mess). Using the cross product, you need to provide join criteria in the WHERE clause, and that's the problem with the notation. You are crowding your WHERE clause with stuff like

    tableA.id = tableB.a_id 
AND tableB.id = tableC.b_id 

which is only used to restrict the cross product. WHERE clause should only contain RESTRICTIONS to the resultset. If you mix table join criteria with resultset restrictions, you (and others) will find your query harder to read. You should definitely use JOINs and keep the FROM clause a FROM clause, and the WHERE clause a WHERE clause.

Android Shared preferences for creating one time activity (example)

Write to Shared Preferences

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
 editor.commit(); 

Read from Shared Preferences

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

Auto-fit TextView for Android

Thanks to MartinH's simple fix here, this code also takes care of android:drawableLeft, android:drawableRight, android:drawableTop and android:drawableBottom tags.


My answer here should make you happy Auto Scale TextView Text to Fit within Bounds

I have modified your test case:

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final ViewGroup container = (ViewGroup) findViewById(R.id.container);
    findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            container.removeAllViews();
            final int maxWidth = container.getWidth();
            final int maxHeight = container.getHeight();
            final AutoResizeTextView fontFitTextView = new AutoResizeTextView(MainActivity.this);
            final int width = _random.nextInt(maxWidth) + 1;
            final int height = _random.nextInt(maxHeight) + 1;
            fontFitTextView.setLayoutParams(new FrameLayout.LayoutParams(
                    width, height));
            int maxLines = _random.nextInt(4) + 1;
            fontFitTextView.setMaxLines(maxLines);
            fontFitTextView.setTextSize(500);// max size
            fontFitTextView.enableSizeCache(false);
            fontFitTextView.setBackgroundColor(0xff00ff00);
            final String text = getRandomText();
            fontFitTextView.setText(text);
            container.addView(fontFitTextView);
            Log.d("DEBUG", "width:" + width + " height:" + height
                    + " text:" + text + " maxLines:" + maxLines);
        }
    });
}

I am posting code here at per android developer's request:

Final effect:

Enter image description here

Sample Layout file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp" >

<com.vj.widgets.AutoResizeTextView
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:ellipsize="none"
    android:maxLines="2"
    android:text="Auto Resized Text, max 2 lines"
    android:textSize="100sp" /> <!-- maximum size -->

<com.vj.widgets.AutoResizeTextView
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:ellipsize="none"
    android:gravity="center"
    android:maxLines="1"
    android:text="Auto Resized Text, max 1 line"
    android:textSize="100sp" /> <!-- maximum size -->

<com.vj.widgets.AutoResizeTextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Auto Resized Text"
    android:textSize="500sp" /> <!-- maximum size -->

</LinearLayout>

And the Java code:

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.RectF;
import android.os.Build;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.SparseIntArray;
import android.util.TypedValue;
import android.widget.TextView;

public class AutoResizeTextView extends TextView {
    private interface SizeTester {
        /**
         *
         * @param suggestedSize
         *            Size of text to be tested
         * @param availableSpace
         *            available space in which text must fit
         * @return an integer < 0 if after applying {@code suggestedSize} to
         *         text, it takes less space than {@code availableSpace}, > 0
         *         otherwise
         */
        public int onTestSize(int suggestedSize, RectF availableSpace);
    }

    private RectF mTextRect = new RectF();

    private RectF mAvailableSpaceRect;

    private SparseIntArray mTextCachedSizes;

    private TextPaint mPaint;

    private float mMaxTextSize;

    private float mSpacingMult = 1.0f;

    private float mSpacingAdd = 0.0f;

    private float mMinTextSize = 20;

    private int mWidthLimit;

    private static final int NO_LINE_LIMIT = -1;
    private int mMaxLines;

    private boolean mEnableSizeCache = true;
    private boolean mInitializedDimens;

    public AutoResizeTextView(Context context) {
        super(context);
        initialize();
    }

    public AutoResizeTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    public AutoResizeTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initialize();
    }

    private void initialize() {
        mPaint = new TextPaint(getPaint());
        mMaxTextSize = getTextSize();
        mAvailableSpaceRect = new RectF();
        mTextCachedSizes = new SparseIntArray();
        if (mMaxLines == 0) {
            // no value was assigned during construction
            mMaxLines = NO_LINE_LIMIT;
        }
    }

    @Override
    public void setTextSize(float size) {
        mMaxTextSize = size;
        mTextCachedSizes.clear();
        adjustTextSize();
    }

    @Override
    public void setMaxLines(int maxlines) {
        super.setMaxLines(maxlines);
        mMaxLines = maxlines;
        adjustTextSize();
    }

    public int getMaxLines() {
        return mMaxLines;
    }

    @Override
    public void setSingleLine() {
        super.setSingleLine();
        mMaxLines = 1;
        adjustTextSize();
    }

    @Override
    public void setSingleLine(boolean singleLine) {
        super.setSingleLine(singleLine);
        if (singleLine) {
            mMaxLines = 1;
        } else {
            mMaxLines = NO_LINE_LIMIT;
        }
        adjustTextSize();
    }

    @Override
    public void setLines(int lines) {
        super.setLines(lines);
        mMaxLines = lines;
        adjustTextSize();
    }

    @Override
    public void setTextSize(int unit, float size) {
        Context c = getContext();
        Resources r;

        if (c == null)
            r = Resources.getSystem();
        else
            r = c.getResources();
        mMaxTextSize = TypedValue.applyDimension(unit, size,
                r.getDisplayMetrics());
        mTextCachedSizes.clear();
        adjustTextSize();
    }

    @Override
    public void setLineSpacing(float add, float mult) {
        super.setLineSpacing(add, mult);
        mSpacingMult = mult;
        mSpacingAdd = add;
    }

    /**
     * Set the lower text size limit and invalidate the view
     *
     * @param minTextSize
     */
    public void setMinTextSize(float minTextSize) {
        mMinTextSize = minTextSize;
        adjustTextSize();
    }

    private void adjustTextSize() {
        if (!mInitializedDimens) {
            return;
        }
        int startSize = (int) mMinTextSize;
        int heightLimit = getMeasuredHeight() - getCompoundPaddingBottom()
                - getCompoundPaddingTop();
        mWidthLimit = getMeasuredWidth() - getCompoundPaddingLeft()
                - getCompoundPaddingRight();
        mAvailableSpaceRect.right = mWidthLimit;
        mAvailableSpaceRect.bottom = heightLimit;
        super.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                efficientTextSizeSearch(startSize, (int) mMaxTextSize,
                        mSizeTester, mAvailableSpaceRect));
    }

    private final SizeTester mSizeTester = new SizeTester() {
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public int onTestSize(int suggestedSize, RectF availableSPace) {
            mPaint.setTextSize(suggestedSize);
            String text = getText().toString();
            boolean singleline = getMaxLines() == 1;
            if (singleline) {
                mTextRect.bottom = mPaint.getFontSpacing();
                mTextRect.right = mPaint.measureText(text);
            } else {
                StaticLayout layout = new StaticLayout(text, mPaint,
                        mWidthLimit, Alignment.ALIGN_NORMAL, mSpacingMult,
                        mSpacingAdd, true);

                // Return early if we have more lines
                if (getMaxLines() != NO_LINE_LIMIT
                        && layout.getLineCount() > getMaxLines()) {
                    return 1;
                }
                mTextRect.bottom = layout.getHeight();
                int maxWidth = -1;
                for (int i = 0; i < layout.getLineCount(); i++) {
                    if (maxWidth < layout.getLineWidth(i)) {
                        maxWidth = (int) layout.getLineWidth(i);
                    }
                }
                mTextRect.right = maxWidth;
            }

            mTextRect.offsetTo(0, 0);
            if (availableSPace.contains(mTextRect)) {

                // May be too small, don't worry we will find the best match
                return -1;
            } else {
                // too big
                return 1;
            }
        }
    };

    /**
     * Enables or disables size caching, enabling it will improve performance
     * where you are animating a value inside TextView. This stores the font
     * size against getText().length() Be careful though while enabling it as 0
     * takes more space than 1 on some fonts and so on.
     *
     * @param enable
     *            Enable font size caching
     */
    public void enableSizeCache(boolean enable) {
        mEnableSizeCache = enable;
        mTextCachedSizes.clear();
        adjustTextSize(getText().toString());
    }

    private int efficientTextSizeSearch(int start, int end,
            SizeTester sizeTester, RectF availableSpace) {
        if (!mEnableSizeCache) {
            return binarySearch(start, end, sizeTester, availableSpace);
        }
        int key = getText().toString().length();
        int size = mTextCachedSizes.get(key);
        if (size != 0) {
            return size;
        }
        size = binarySearch(start, end, sizeTester, availableSpace);
        mTextCachedSizes.put(key, size);
        return size;
    }

    private static int binarySearch(int start, int end, SizeTester sizeTester,
            RectF availableSpace) {
        int lastBest = start;
        int lo = start;
        int hi = end - 1;
        int mid = 0;
        while (lo <= hi) {
            mid = (lo + hi) >>> 1;
            int midValCmp = sizeTester.onTestSize(mid, availableSpace);
            if (midValCmp < 0) {
                lastBest = lo;
                lo = mid + 1;
            } else if (midValCmp > 0) {
                hi = mid - 1;
                lastBest = hi;
            } else {
                return mid;
            }
        }
        // Make sure to return the last best.
        // This is what should always be returned.
        return lastBest;

    }

    @Override
    protected void onTextChanged(final CharSequence text, final int start,
            final int before, final int after) {
        super.onTextChanged(text, start, before, after);
        adjustTextSize();
    }

    @Override
    protected void onSizeChanged(int width, int height, int oldwidth,
            int oldheight) {
        mInitializedDimens = true;
        mTextCachedSizes.clear();
        super.onSizeChanged(width, height, oldwidth, oldheight);
        if (width != oldwidth || height != oldheight) {
            adjustTextSize();
        }
    }
}

Warning:

Beware of this resolved bug in Android 3.1 (Honeycomb) though.

Delete item from state array in react

Here is a minor variation on Aleksandr Petrov's response using ES6

removePeople(e) {
    let filteredArray = this.state.people.filter(item => item !== e.target.value)
    this.setState({people: filteredArray});
}

Java Try Catch Finally blocks without Catch

The inner finally is executed prior to throwing the exception to the outer block.

public class TryCatchFinally {

  public static void main(String[] args) throws Exception {

    try{
        System.out.println('A');
        try{
            System.out.println('B');
            throw new Exception("threw exception in B");
        }
        finally
        {
            System.out.println('X');
        }
        //any code here in the first try block 
        //is unreachable if an exception occurs in the second try block
    }
    catch(Exception e)
    {
        System.out.println('Y');
    }
    finally
    {
        System.out.println('Z');
    }
  }
}

Results in

A
B
X
Y
Z

How to change value of process.env.PORT in node.js?

use the below command to set the port number in node process while running node JS programme:

set PORT =3000 && node file_name.js

The set port can be accessed in the code as

process.env.PORT 

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

Actually the "Remote" option in Configuration Menu for Plug-In works by me (Win7 64, ie8 with all updates), however:

  1. You need administrator rights
  2. The plug-in should be disabled before pressing the remove button
  3. You need restart internet-explorer to see the changes.

Also the previous comment about browsing-history->view objects was also useful if plug-in was installed right now.

Regards!

How can I determine if a date is between two dates in Java?

If you don't know the order of the min/max values

Date a, b;   // assume these are set to something
Date d;      // the date in question

return a.compareTo(d) * d.compareTo(b) > 0;

If you want the range to be inclusive

return a.compareTo(d) * d.compareTo(b) >= 0;

How to get the second column from command output?

#!/usr/bin/python
import sys 

col = int(sys.argv[1]) - 1

for line in sys.stdin:
    columns = line.split()

    try:
        print(columns[col])
    except IndexError:
        # ignore
        pass

Then, supposing you name the script as co, say, do something like this to get the sizes of files (the example assumes you're using Linux, but the script itself is OS-independent) :-

ls -lh | co 5

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

Replace Multiple String Elements in C#

There is one thing that may be optimized in the suggested solutions. Having many calls to Replace() makes the code to do multiple passes over the same string. With very long strings the solutions may be slow because of CPU cache capacity misses. May be one should consider replacing multiple strings in a single pass.

How to serialize a JObject without the formatting?

You can also do the following;

string json = myJObject.ToString(Newtonsoft.Json.Formatting.None);

to remove first and last element in array

This can be done with lodash _.tail and _.dropRight:

_x000D_
_x000D_
var fruits = ["Banana", "Orange", "Apple", "Mango"];_x000D_
console.log(_.dropRight(_.tail(fruits)));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

THE ANSWER: The problem was all of the posts for such an issue were related to older kerberos and IIS issues where proxy credentials or AllowNTLM properties were helping. My case was different. What I have discovered after hours of picking worms from the ground was that somewhat IIS installation did not include Negotiate provider under IIS Windows authentication providers list. So I had to add it and move up. My WCF service started to authenticate as expected. Here is the screenshot how it should look if you are using Windows authentication with Anonymous auth OFF.

You need to right click on Windows authentication and choose providers menu item.

enter image description here

Hope this helps to save some time.

Form content type for a json HTTP POST?

I have wondered the same thing. Basically it appears that the html spec has different content types for html and form data. Json only has a single content type.

According to the spec, a POST of json data should have the content-type:
application/json

Relevant portion of the HTML spec

6.7 Content types (MIME types)
...
Examples of content types include "text/html", "image/png", "image/gif", "video/mpeg", "text/css", and "audio/basic".

17.13.4 Form content types
...
application/x-www-form-urlencoded
This is the default content type. Forms submitted with this content type must be encoded as follows

Relevant portion of the JSON spec

  1. IANA Considerations
    The MIME media type for JSON text is application/json.

SVG fill color transparency / alpha?

To make a fill completely transparent, fill="transparent" seems to work in modern browsers. But it didn't work in Microsoft Word (for Mac), I had to use fill-opacity="0".

How to Logout of an Application Where I Used OAuth2 To Login With Google?

If any one want it in Java, Here is my Answer, For this you have to call Another Thread.

What exactly is RESTful programming?

An architectural style called REST (Representational State Transfer) advocates that web applications should use HTTP as it was originally envisioned. Lookups should use GET requests. PUT, POST, and DELETE requests should be used for mutation, creation, and deletion respectively.

REST proponents tend to favor URLs, such as

http://myserver.com/catalog/item/1729

but the REST architecture does not require these "pretty URLs". A GET request with a parameter

http://myserver.com/catalog?item=1729

is every bit as RESTful.

Keep in mind that GET requests should never be used for updating information. For example, a GET request for adding an item to a cart

http://myserver.com/addToCart?cart=314159&item=1729

would not be appropriate. GET requests should be idempotent. That is, issuing a request twice should be no different from issuing it once. That's what makes the requests cacheable. An "add to cart" request is not idempotent—issuing it twice adds two copies of the item to the cart. A POST request is clearly appropriate in this context. Thus, even a RESTful web application needs its share of POST requests.

This is taken from the excellent book Core JavaServer faces book by David M. Geary.

How get all values in a column using PHP?

PHP 5 >= 5.5.0, PHP 7

Use array_column on the result array

$column = array_column($result, 'names');

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

I was getting this when the app deployed. In my case, I chose "This is a full trust application" on the project security tab, and that fixed it.

Vue.js—Difference between v-model and v-bind

v-model
it is two way data binding, it is used to bind html input element when you change input value then bounded data will be change.

v-model is used only for HTML input elements

ex: <input type="text" v-model="name" > 

v-bind
it is one way data binding,means you can only bind data to input element but can't change bounded data changing input element. v-bind is used to bind html attribute
ex:
<input type="text" v-bind:class="abc" v-bind:value="">

<a v-bind:href="home/abc" > click me </a>

How to remove "index.php" in codeigniter's path

This will help you paste this code in application folder in .htacess file

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]  

<Files "index.php">
AcceptPathInfo On
</Files>
<IfModule mod_php5.c>
  php_value short_open_tag 1
</IfModule>

How to upload files to server using JSP/Servlet?

You need the common-io.1.4.jar file to be included in your lib directory, or if you're working in any editor, like NetBeans, then you need to go to project properties and just add the JAR file and you will be done.

To get the common.io.jar file just google it or just go to the Apache Tomcat website where you get the option for a free download of this file. But remember one thing: download the binary ZIP file if you're a Windows user.

Regular expression for exact match of a string

if you have a the input password in a variable and you want to match exactly 123456 then anchors will help you:

/^123456$/

in perl the test for matching the password would be something like

print "MATCH_OK" if ($input_pass=~/^123456$/);

EDIT:

bart kiers is right tho, why don't you use a strcmp() for this? every language has it in its own way

as a second thought, you may want to consider a safer authentication mechanism :)

Creating and appending text to txt file in VB.NET

Try it this way:

Dim filePath As String = 
  String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))

if File.Exists(filePath) then

Using writer As New StreamWriter(filePath, True)
writer.WriteLine("Error Message in  Occured at-- " & DateTime.Now)

Else
writer.WriteLine("Start Error Log for today")
End Using

end if

Shell script : How to cut part of a string

Assuming input of

{Anything}id={ID}{space}{Anything} 
{Anything}id={ID}{space}{Anything}

--

#! /bin/sh
while read s; do
   rhs=${s##*id=}
   id=${rhs%% *}
   echo $id # Do what you will with $id here
done <so.txt 

Or if it's always the 7th field

#! /bin/sh
while read f1 f2 f3 f4 f5 f6 f7 rest
do
echo ${f7##id=}
done <so.txt

See Also

Shell Parameter Expansion

Default keystore file does not exist?

In macOS, open the Terminal and type below command

~/.android

It will navigate to the folder that containing Keystore file (You can confirm it with 'ls' command)

In my case, there is a file named 'debug.keystore'. Then type below command in the terminal from the ~/.android directory.

keytool -list -v -keystore debug.keystore

You will get the expected output.

Select a random sample of results from a query result

We were given and assignment to select only two records from the list of agents..i.e 2 random records for each agent over the span of a week etc.... and below is what we got and it works

with summary as (
Select Dbms_Random.Random As Ran_Number,
             colmn1,
             colm2,
             colm3
             Row_Number() Over(Partition By col2 Order By Dbms_Random.Random) As Rank
    From table1, table2
 Where Table1.Id = Table2.Id
 Order By Dbms_Random.Random Asc)
Select tab1.col2,
             tab1.col4,
             tab1.col5,
    From Summary s
 Where s.Rank <= 2;

How do I make an asynchronous GET request in PHP?

Try:

//Your Code here
$pid = pcntl_fork();
if ($pid == -1) {
     die('could not fork');
}
else if ($pid)
{
echo("Bye")  
}
else
{
     //Do Post Processing
}

This will NOT work as an apache module, you need to be using CGI.

Use SELECT inside an UPDATE query

Does this work? Untested but should get the point across.

UPDATE FUNCTIONS
SET Func_TaxRef = 
(
  SELECT Min(TAX.Tax_Code) AS MinOfTax_Code
  FROM TAX, FUNCTIONS F1
  WHERE F1.Func_Pure <= [Tax_ToPrice]
    AND F1.Func_Year=[Tax_Year]
    AND F1.Func_ID = FUNCTIONS.Func_ID
  GROUP BY F1.Func_ID;
)

Basically for each row in FUNCTIONS, the subquery determines the minimum current tax code and sets FUNCTIONS.Func_TaxRef to that value. This is assuming that FUNCTIONS.Func_ID is a Primary or Unique key.

Listview Scroll to the end of the list after updating the list

The transcript mode is what you want and is used by Google Talk and the SMS/MMS application. Are you correctly calling notifyDatasetChanged() on your adapter when you add items?

Python: How to increase/reduce the fontsize of x and y tick labels?

One shouldn't use set_yticklabels to change the fontsize, since this will also set the labels (i.e. it will replace any automatic formatter by a FixedFormatter), which is usually undesired. The easiest is to set the respective tick_params:

ax.tick_params(axis="x", labelsize=8)
ax.tick_params(axis="y", labelsize=20)

or

ax.tick_params(labelsize=8)

in case both axes shall have the same size.

Of course using the rcParams as in @tmdavison's answer is possible as well.

.NET console application as Windows service

Firstly I embed the console application solution into the windows service solution and reference it.

Then I make the console application Program class public

/// <summary>
/// Hybrid service/console application
/// </summary>
public class Program
{
}

I then create two functions within the console application

    /// <summary>
    /// Used to start as a service
    /// </summary>
    public void Start()
    {
        Main();
    }

    /// <summary>
    /// Used to stop the service
    /// </summary>
    public void Stop()
    {
       if (Application.MessageLoop)
            Application.Exit();   //windows app
        else
            Environment.Exit(1);  //console app
    }

Then within the windows service itself I instantiate the Program and call the Start and Stop functions added within the OnStart and OnStop. See below

class WinService : ServiceBase
{
    readonly Program _application = new Program();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        ServiceBase[] servicesToRun = { new WinService() };
        Run(servicesToRun);
    }

    /// <summary>
    /// Set things in motion so your service can do its work.
    /// </summary>
    protected override void OnStart(string[] args)
    {
        Thread thread = new Thread(() => _application.Start());
        thread.Start();
    }

    /// <summary>
    /// Stop this service.
    /// </summary>
    protected override void OnStop()
    {
        Thread thread = new Thread(() => _application.Stop());
        thread.Start();
    }
}

This approach can also be used for a windows application / windows service hybrid

gcc-arm-linux-gnueabi command not found

CodeSourcery convention is to use prefix arm-none-linux-gnueabi- for all executables, not gcc-arm-linux-gnueabi that you mention. So, standard name for CodeSourcery gcc would be arm-none-linux-gnueabi-gcc.

After you have installed CodeSourcery G++, you need to add CodeSourcery directory into your PATH.

Typically, I prefer to install CodeSourcery into directory like /opt/arm-2010q1 or something like that. If you don't know where you have installed it, you can find it using locate arm-none-linux-gnueabi-gcc, however you may need to force to update your locate db using sudo updatedb before locate will work properly.

After you have identified where your CodeSourcery is installed, add it your PATH by editing ~/.bashrc like this:

PATH=/opt/arm-2010q1/bin:$PATH

Also, it is customary and very convenient to define

CROSS_COMPILE=arm-none-linux-gnueabi-

in your .bashrc, because with CROSS_COMPILE defined, most tools will automatically use proper compiler for ARM compilation without you doing anything.

How to set selected value on select using selectpicker plugin from bootstrap

use this and it's gonna work:

 $('select[name=selValue]').selectpicker('val', 1);

how to install python distutils

I know this is an old question, but I just come across the same issue using Python 3.6 in Ubuntu, and I am able to solve it using the following command:

sudo apt-get install python3-distutils

Extracting double-digit months and days from a Python date

Look at the types of those properties:

In [1]: import datetime

In [2]: d = datetime.date.today()

In [3]: type(d.month)
Out[3]: <type 'int'>

In [4]: type(d.day)
Out[4]: <type 'int'>

Both are integers. So there is no automatic way to do what you want. So in the narrow sense, the answer to your question is no.

If you want leading zeroes, you'll have to format them one way or another. For that you have several options:

In [5]: '{:02d}'.format(d.month)
Out[5]: '03'

In [6]: '%02d' % d.month
Out[6]: '03'

In [7]: d.strftime('%m')
Out[7]: '03'

In [8]: f'{d.month:02d}'
Out[8]: '03'

How to get current PHP page name

You can use basename() and $_SERVER['PHP_SELF'] to get current page file name

echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */

How do I include a path to libraries in g++

To specify a directory to search for (binary) libraries, you just use -L:

-L/data[...]/lib

To specify the actual library name, you use -l:

-lfoo  # (links libfoo.a or libfoo.so)

To specify a directory to search for include files (different from libraries!) you use -I:

-I/data[...]/lib

So I think what you want is something like

g++ -g -Wall -I/data[...]/lib testing.cpp fileparameters.cpp main.cpp -o test

These compiler flags (amongst others) can also be found at the GNU GCC Command Options manual:

css ellipsis on second line

a pure css method base on -webkit-line-clamp, which works on webkit:

_x000D_
_x000D_
@-webkit-keyframes ellipsis {/*for test*/_x000D_
    0% { width: 622px }_x000D_
    50% { width: 311px }_x000D_
    100% { width: 622px }_x000D_
}_x000D_
.ellipsis {_x000D_
    max-height: 40px;/* h*n */_x000D_
    overflow: hidden;_x000D_
    background: #eee;_x000D_
_x000D_
    -webkit-animation: ellipsis ease 5s infinite;/*for test*/_x000D_
    /**_x000D_
    overflow: visible;_x000D_
    /**/_x000D_
}_x000D_
.ellipsis .content {_x000D_
    position: relative;_x000D_
    display: -webkit-box;_x000D_
    -webkit-box-orient: vertical;_x000D_
    -webkit-box-pack: center;_x000D_
    font-size: 50px;/* w */_x000D_
    line-height: 20px;/* line-height h */_x000D_
    color: transparent;_x000D_
    -webkit-line-clamp: 2;/* max row number n */_x000D_
    vertical-align: top;_x000D_
}_x000D_
.ellipsis .text {_x000D_
    display: inline;_x000D_
    vertical-align: top;_x000D_
    font-size: 14px;_x000D_
    color: #000;_x000D_
}_x000D_
.ellipsis .overlay {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 50%;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    overflow: hidden;_x000D_
_x000D_
    /**_x000D_
    overflow: visible;_x000D_
    left: 0;_x000D_
    background: rgba(0,0,0,.5);_x000D_
    /**/_x000D_
}_x000D_
.ellipsis .overlay:before {_x000D_
    content: "";_x000D_
    display: block;_x000D_
    float: left;_x000D_
    width: 50%;_x000D_
    height: 100%;_x000D_
_x000D_
    /**_x000D_
    background: lightgreen;_x000D_
    /**/_x000D_
}_x000D_
.ellipsis .placeholder {_x000D_
    float: left;_x000D_
    width: 50%;_x000D_
    height: 40px;/* h*n */_x000D_
_x000D_
    /**_x000D_
    background: lightblue;_x000D_
    /**/_x000D_
}_x000D_
.ellipsis .more {_x000D_
    position: relative;_x000D_
    top: -20px;/* -h */_x000D_
    left: -50px;/* -w */_x000D_
    float: left;_x000D_
    color: #000;_x000D_
    width: 50px;/* width of the .more w */_x000D_
    height: 20px;/* h */_x000D_
    font-size: 14px;_x000D_
_x000D_
    /**_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    background: orange;_x000D_
    /**/_x000D_
}
_x000D_
<div class='ellipsis'>_x000D_
    <div class='content'>_x000D_
        <div class='text'>text text text text text text text text text text text text text text text text text text text text text </div>_x000D_
        <div class='overlay'>_x000D_
            <div class='placeholder'></div>_x000D_
            <div class='more'>...more</div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Include another HTML file in a HTML file

html5rocks.com has a very good tutorial on this stuff, and this might be a little late, but I myself didn't know this existed. w3schools also has a way to do this using their new library called w3.js. The thing is, this requires the use of a web server and and HTTPRequest object. You can't actually load these locally and test them on your machine. What you can do though, is use polyfills provided on the html5rocks link at the top, or follow their tutorial. With a little JS magic, you can do something like this:

 var link = document.createElement('link');
 if('import' in link){
     //Run import code
     link.setAttribute('rel','import');
     link.setAttribute('href',importPath);
     document.getElementsByTagName('head')[0].appendChild(link);
     //Create a phantom element to append the import document text to
     link = document.querySelector('link[rel="import"]');
     var docText = document.createElement('div');
     docText.innerHTML = link.import;
     element.appendChild(docText.cloneNode(true));
 } else {
     //Imports aren't supported, so call polyfill
     importPolyfill(importPath);
 }

This will make the link (Can change to be the wanted link element if already set), set the import (unless you already have it), and then append it. It will then from there take that and parse the file in HTML, and then append it to the desired element under a div. This can all be changed to fit your needs from the appending element to the link you are using. I hope this helped, it may irrelevant now if newer, faster ways have come out without using libraries and frameworks such as jQuery or W3.js.

UPDATE: This will throw an error saying that the local import has been blocked by CORS policy. Might need access to the deep web to be able to use this because of the properties of the deep web. (Meaning no practical use)

C++ floating point to integer type conversions

One thing I want to add. Sometimes, there can be precision loss. You may want to add some epsilon value first before converting. Not sure why that works... but it work.

int someint = (somedouble+epsilon);

How do I create an HTML table with a fixed/frozen left column and a scrollable body?

If you're in Webdevelopper hell and need to make this work for IE6, here's a sample code I used:

<html>
<head>
<style type="text/css">
.fixme {
    position: relative;
    left: expression( ( 20 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px' );
    background-color: #FFFFFF;
}
</style>
</head>
<body>
<table width="1500px" border="2">
    <tr>
        <td class="fixme" style="width: 200px;">loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet</td>
        <td>loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
        <td>loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
        <td>loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
    </tr>
    <tr>
        <td class="fixme" style="width: 200px;">loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
        <td>loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
        <td>loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
        <td>loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
    </tr>
    <tr>
        <td class="fixme" style="width: 200px;">loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
        <td>loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
        <td>loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
        <td>loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
    </tr>
    <tr>
        <td class="fixme" style="width: 200px;">loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
        <td>loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
        <td>loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
        <td>loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet loremp ispum dolor sit amet </td>
    </tr>
</table>
</body>
</html>

This will work probably ONLY for IE6, so use conditional comments for the CSS.

Using onBlur with JSX and React

There are a few problems here.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2: you need a place to render the error.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

Better way to find control in ASP.NET

https://blog.codinghorror.com/recursive-pagefindcontrol/

Page.FindControl("DataList1:_ctl0:TextBox3");

OR

private Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
    {
        return root;
    }
    foreach (Control c in root.Controls)
    {
        Control t = FindControlRecursive(c, id);
        if (t != null)
        {
            return t;
        }
    }
    return null;
}

You don't have permission to access / on this server

Set SELinux in Permissive Mode using the command below:

setenforce 0;

How to convert password into md5 in jquery?

jQuery doesnt have a method to provide the md5 of a string. So you need to use some external script. There is a plugin called jQuery MD5. and it gives you number of methods to achieve md5. Few of those are

Create (hex-encoded) MD5 hash of a given string value:

var md5 = $.md5('value');

Create (hex-encoded) HMAC-MD5 hash of a given string value and key:

var md5 = $.md5('value', 'key');

Create raw MD5 hash of a given string value:

var md5 = $.md5('value', null, true);

Create raw HMAC-MD5 hash of a given string value and key:

var md5 = $.md5('value', 'key', true);

This might do what you want... Check the snippet here. jQuery MD5

encrypt and decrypt md5

This question is tagged with PHP. But many people are using Laravel framework now. It might help somebody in future. That's why I answering for Laravel. It's more easy to encrypt and decrypt with internal functions.

$string = 'c4ca4238a0b923820dcc';
$encrypted = \Illuminate\Support\Facades\Crypt::encrypt($string);
$decrypted_string = \Illuminate\Support\Facades\Crypt::decrypt($encrypted);

var_dump($string);
var_dump($encrypted);
var_dump($decrypted_string);

Note: Be sure to set a 16, 24, or 32 character random string in the key option of the config/app.php file. Otherwise, encrypted values will not be secure.

But you should not use encrypt and decrypt for authentication. Rather you should use hash make and check.

To store password in database, make hash of password and then save.

$password = Input::get('password_from_user'); 
$hashed = Hash::make($password); // save $hashed value

To verify password, get password stored of account from database

// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
  // Password is not matching 
} else {
  // Password is matching 
}

For each row in an R dataframe

you can do something for a list object,

data("mtcars")
rownames(mtcars)
data <- list(mtcars ,mtcars, mtcars, mtcars);data

out1 <- NULL 
for(i in seq_along(data)) { 
  out1[[i]] <- data[[i]][rownames(data[[i]]) != "Volvo 142E", ] } 
out1

Or a data frame,

data("mtcars")
df <- mtcars
out1 <- NULL 
for(i in 1:nrow(df)) {
  row <- rownames(df[i,])
  # do stuff with row
  out1 <- df[rownames(df) != "Volvo 142E",]
  
}
out1 

How to uninstall mini conda? python

your have to comment that line in ~/.bashrc:

#export PATH=/home/jolth/miniconda3/bin:$PATH

and run:

source ~/.bashrc

How to update each dependency in package.json to the latest version?

If you use yarn, the following command updates all packages to their latest version:

yarn upgrade --latest

From their docs:

The upgrade --latest command upgrades packages the same as the upgrade command, but ignores the version range specified in package.json. Instead, the version specified by the latest tag will be used (potentially upgrading the packages across major versions).

Exit from app when click button in android phonegap?

There are different ways to close the app, depending on:

if (navigator.app) {
    navigator.app.exitApp();
} else if (navigator.device) {
    navigator.device.exitApp();
} else {
    window.close();
}

Batchfile to create backup and rename with timestamp

See if this is what you want to do:

@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%

set stamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%

copy "F:\Folder\File 1.xlsx" "F:\Folder\Archive\File 1 - %stamp%.xlsx"

Split a string into an array of strings based on a delimiter

interface

uses
  Classes;

type
  TStringArray = array of string;

  TUtilStr = class
    class function Split(const AValue: string; const ADelimiter: Char = ';'; const AQuoteChar: Char = '"'): TStringArray; static;
  end;


implementation

{ TUtilStr }

class function TUtilStr.Split(const AValue: string; const ADelimiter: Char; const AQuoteChar: Char): TStringArray;
var
  LSplited: TStringList;
  LText: string;
  LIndex: Integer;
begin
  LSplited := TStringList.Create;
  try
    LSplited.StrictDelimiter := True;
    LSplited.Delimiter := ADelimiter;
    LSplited.QuoteChar := AQuoteChar;
    LSplited.DelimitedText := AValue;

    SetLength(Result, LSplited.Count);
    for LIndex := 0 to LSplited.Count - 1 do
    begin
      Result[LIndex] := LSplited[LIndex];
    end;
  finally
    LSplited.Free;
  end;
end;

end.

Best way to check if object exists in Entity Framework?

I know this is a very old thread but just incase someone like myself needs this solution but in VB.NET here's what I used base on the answers above.

Private Function ValidateUniquePayroll(PropertyToCheck As String) As Boolean
    // Return true if Username is Unique
    Dim rtnValue = False
    Dim context = New CPMModel.CPMEntities
    If (context.Employees.Any()) Then ' Check if there are "any" records in the Employee table
        Dim employee = From c In context.Employees Select c.PayrollNumber ' Select just the PayrollNumber column to work with
        For Each item As Object In employee ' Loop through each employee in the Employees entity
            If (item = PropertyToCheck) Then ' Check if PayrollNumber in current row matches PropertyToCheck
                // Found a match, throw exception and return False
                rtnValue = False
                Exit For
            Else
                // No matches, return True (Unique)
                rtnValue = True
            End If
        Next
    Else
        // The is currently no employees in the person entity so return True (Unqiue)
        rtnValue = True
    End If
    Return rtnValue
End Function

error code 1292 incorrect date value mysql

With mysql 5.7, date value like 0000-00-00 00:00:00 is not allowed.

If you want to allow it, you have to update your my.cnf like:

sudo nano /etc/mysql/my.cnf

find

[mysqld]

Add after:

sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Restart mysql service:

sudo service mysql restart

Done!

Print a div using javascript in angularJS single page application

Two conditional functions are needed: one for Google Chrome, and a second for the remaining browsers.

$scope.printDiv = function (divName) {

    var printContents = document.getElementById(divName).innerHTML; 

    if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
        var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
        popupWin.window.focus();
        popupWin.document.write('<!DOCTYPE html><html><head>' +
            '<link rel="stylesheet" type="text/css" href="style.css" />' +
            '</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div></body></html>');
        popupWin.onbeforeunload = function (event) {
            popupWin.close();
            return '.\n';
        };
        popupWin.onabort = function (event) {
            popupWin.document.close();
            popupWin.close();
        }
    } else {
        var popupWin = window.open('', '_blank', 'width=800,height=600');
        popupWin.document.open();
        popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
        popupWin.document.close();
    }
    popupWin.document.close();

    return true;
}

Renaming column names of a DataFrame in Spark Scala

Sometime we have the column name is below format in SQLServer or MySQL table

Ex  : Account Number,customer number

But Hive tables do not support column name containing spaces, so please use below solution to rename your old column names.

Solution:

val renamedColumns = df.columns.map(c => df(c).as(c.replaceAll(" ", "_").toLowerCase()))
df = df.select(renamedColumns: _*)

How to skip to next iteration in jQuery.each() util?

What they mean by non-false is:

return true;

So this code:

_x000D_
_x000D_
var arr = ["one", "two", "three", "four", "five"];_x000D_
$.each(arr, function(i) {_x000D_
  if (arr[i] == 'three') {_x000D_
    return true;_x000D_
  }_x000D_
  console.log(arr[i]);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

will log one, two, four, five.

Getting the text that follows after the regex match

You need to use the group(int) of your matcher - group(0) is the entire match, and group(1) is the first group you marked. In the example you specify, group(1) is what comes after "sentence".

node.js shell command execution

I had a similar problem and I ended up writing a node extension for this. You can check out the git repository. It's open source and free and all that good stuff !

https://github.com/aponxi/npm-execxi

ExecXI is a node extension written in C++ to execute shell commands one by one, outputting the command's output to the console in real-time. Optional chained, and unchained ways are present; meaning that you can choose to stop the script after a command fails (chained), or you can continue as if nothing has happened !

Usage instructions are in the ReadMe file. Feel free to make pull requests or submit issues!

I thought it was worth to mention it.

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)

In Django, how do I check if a user is in a certain group?

If a user belongs to a certain group or not, can be checked in django templates using:

{% if group in request.user.groups.all %} "some action" {% endif %}

How does the enhanced for statement work for arrays, and how to get an iterator for an array?

How does the above for-each loop work?

Like many other array features, the JSL mentions arrays explicitly and gives them magical properties. JLS 7 14.14.2:

EnhancedForStatement:

    for ( FormalParameter : Expression ) Statement

[...]

If the type of Expression is a subtype of Iterable, then the translation is as follows

[...]

Otherwise, the Expression necessarily has an array type, T[]. [[ MAGIC! ]]

Let L1 ... Lm be the (possibly empty) sequence of labels immediately preceding the enhanced for statement.

The enhanced for statement is equivalent to a basic for statement of the form:

T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
    VariableModifiersopt TargetType Identifier = #a[#i];
    Statement
}

#a and #i are automatically generated identifiers that are distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the enhanced for statement occurs.

Is the array converted to a list to get the iterator?

Let's javap it up:

public class ArrayForLoop {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        for (int i : arr)
            System.out.println(i);
    }
}

then:

javac ArrayForLoop.java
javap -v ArrayForLoop

main method with a bit of editing to make it easier to read:

 0: iconst_3
 1: newarray       int
 3: dup
 4: iconst_0
 5: iconst_1
 6: iastore
 7: dup
 8: iconst_1
 9: iconst_2
10: iastore
11: dup
12: iconst_2
13: iconst_3
14: iastore

15: astore_1
16: aload_1
17: astore_2
18: aload_2
19: arraylength
20: istore_3
21: iconst_0
22: istore        4

24: iload         4
26: iload_3
27: if_icmpge     50
30: aload_2
31: iload         4
33: iaload
34: istore        5
36: getstatic     #2    // Field java/lang/System.out:Ljava/io/PrintStream;
39: iload         5
41: invokevirtual #3    // Method java/io/PrintStream.println:(I)V
44: iinc          4, 1
47: goto          24
50: return

Breakdown:

  • 0 to 14: create the array
  • 15 to 22: prepare for the for loop. At 22, store integer 0 from stack into local position 4. THAT is the loop variable.
  • 24 to 47: the loop. The loop variable is retrieved at 31, and incremented at 44. When it equals the array length which is stored in local variable 3 on the check at 27, the loop ends.

Conclusion: it is the same as doing an explicit for loop with an index variable, no itereators involved.

How to give a Linux user sudo access?

You need run visudo and in the editor that it opens write:

igor    ALL=(ALL) ALL

That line grants all permissions to user igor.

If you want permit to run only some commands, you need to list them in the line:

igor    ALL=(ALL) /bin/kill, /bin/ps

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

I was using a custom downloader middleware, but wasn't very happy with it, as I didn't manage to make the cache work with it.

A better approach was to implement a custom download handler.

There is a working example here. It looks like this:

# encoding: utf-8
from __future__ import unicode_literals

from scrapy import signals
from scrapy.signalmanager import SignalManager
from scrapy.responsetypes import responsetypes
from scrapy.xlib.pydispatch import dispatcher
from selenium import webdriver
from six.moves import queue
from twisted.internet import defer, threads
from twisted.python.failure import Failure


class PhantomJSDownloadHandler(object):

    def __init__(self, settings):
        self.options = settings.get('PHANTOMJS_OPTIONS', {})

        max_run = settings.get('PHANTOMJS_MAXRUN', 10)
        self.sem = defer.DeferredSemaphore(max_run)
        self.queue = queue.LifoQueue(max_run)

        SignalManager(dispatcher.Any).connect(self._close, signal=signals.spider_closed)

    def download_request(self, request, spider):
        """use semaphore to guard a phantomjs pool"""
        return self.sem.run(self._wait_request, request, spider)

    def _wait_request(self, request, spider):
        try:
            driver = self.queue.get_nowait()
        except queue.Empty:
            driver = webdriver.PhantomJS(**self.options)

        driver.get(request.url)
        # ghostdriver won't response when switch window until page is loaded
        dfd = threads.deferToThread(lambda: driver.switch_to.window(driver.current_window_handle))
        dfd.addCallback(self._response, driver, spider)
        return dfd

    def _response(self, _, driver, spider):
        body = driver.execute_script("return document.documentElement.innerHTML")
        if body.startswith("<head></head>"):  # cannot access response header in Selenium
            body = driver.execute_script("return document.documentElement.textContent")
        url = driver.current_url
        respcls = responsetypes.from_args(url=url, body=body[:100].encode('utf8'))
        resp = respcls(url=url, body=body, encoding="utf-8")

        response_failed = getattr(spider, "response_failed", None)
        if response_failed and callable(response_failed) and response_failed(resp, driver):
            driver.close()
            return defer.fail(Failure())
        else:
            self.queue.put(driver)
            return defer.succeed(resp)

    def _close(self):
        while not self.queue.empty():
            driver = self.queue.get_nowait()
            driver.close()

Suppose your scraper is called "scraper". If you put the mentioned code inside a file called handlers.py on the root of the "scraper" folder, then you could add to your settings.py:

DOWNLOAD_HANDLERS = {
    'http': 'scraper.handlers.PhantomJSDownloadHandler',
    'https': 'scraper.handlers.PhantomJSDownloadHandler',
}

And voilà, the JS parsed DOM, with scrapy cache, retries, etc.

Creating a Jenkins environment variable using Groovy

For me, the following also worked in Jenkins 2 (2.73.3)

Replace

def pa = new ParametersAction([new StringParameterValue("FOO", foo)])
build.addAction(pa)

with

def pa = new ParametersAction([new StringParameterValue("FOO", foo)], ["FOO"])
build.addAction(pa)

ParametersAction seems to have a second constructor which allows to pass in "additionalSafeParameters" https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/model/ParametersAction.java

Unix - copy contents of one directory to another

Try this:

cp Folder1/* Folder2/

How to deploy a war file in Tomcat 7

1.Generate a war file from your application
2. open tomcat manager, go down the page
3. Click on browse to deploy the war.
4. choose your war file. There you go!

How can I get the active screen dimensions?

I needed to set the maximum size of my window application. This one could changed accordingly the application is is been showed in the primary screen or in the secondary. To overcome this problem e created a simple method that i show you next:

/// <summary>
/// Set the max size of the application window taking into account the current monitor
/// </summary>
public static void SetMaxSizeWindow(ioConnect _receiver)
{
    Point absoluteScreenPos = _receiver.PointToScreen(Mouse.GetPosition(_receiver));

    if (System.Windows.SystemParameters.VirtualScreenLeft == System.Windows.SystemParameters.WorkArea.Left)
    {
        //Primary Monitor is on the Left
        if (absoluteScreenPos.X <= System.Windows.SystemParameters.PrimaryScreenWidth)
        {
            //Primary monitor
            _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.WorkArea.Width;
            _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;
        }
        else
        {
            //Secondary monitor
            _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.VirtualScreenWidth - System.Windows.SystemParameters.WorkArea.Width;
            _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.VirtualScreenHeight;
        }
    }

    if (System.Windows.SystemParameters.VirtualScreenLeft < 0)
    {
        //Primary Monitor is on the Right
        if (absoluteScreenPos.X > 0)
        {
            //Primary monitor
            _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.WorkArea.Width;
            _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;
        }
        else
        {
            //Secondary monitor
            _receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.VirtualScreenWidth - System.Windows.SystemParameters.WorkArea.Width;
            _receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.VirtualScreenHeight;
        }
    }
}

Logical operators ("and", "or") in DOS batch

If you have interested to write an if+AND/OR in one statement, then there is no any of it. But, you can still group if with &&/|| and (/) statements to achieve that you want in one line w/o any additional variables and w/o if-else block duplication (single echo command for TRUE and FALSE code sections):

@echo off

setlocal

set "A=1" & set "B=2" & call :IF_AND
set "A=1" & set "B=3" & call :IF_AND
set "A=2" & set "B=2" & call :IF_AND
set "A=2" & set "B=3" & call :IF_AND

echo.

set "A=1" & set "B=2" & call :IF_OR
set "A=1" & set "B=3" & call :IF_OR
set "A=2" & set "B=2" & call :IF_OR
set "A=2" & set "B=3" & call :IF_OR

exit /b 0

:IF_OR
( ( if %A% EQU 1 ( type nul>nul ) else type 2>nul ) || ( if %B% EQU 2 ( type nul>nul ) else type 2>nul ) || ( echo.FALSE-& type 2>nul ) ) && echo TRUE+

exit /b 0

:IF_AND
( ( if %A% EQU 1 ( type nul>nul ) else type 2>nul ) && ( if %B% EQU 2 ( type nul>nul ) else type 2>nul ) && echo.TRUE+ ) || echo.FALSE-


exit /b 0

Output:

TRUE+
FALSE-
FALSE-
FALSE-

TRUE+
TRUE+
TRUE+
FALSE-

The trick is in the type command which drops/sets the errorlevel and so handles the way to the next command.

How do I reference the input of an HTML <textarea> control in codebehind?

You are not using a .NET control for your text area. Either add runat="server" to the HTML TextArea control or use a .NET control:

Try this:

<asp:TextBox id="TextArea1" TextMode="multiline" Columns="50" Rows="5" runat="server" />

Then reference it in your codebehind:

message.Body = TextArea1.Text;

Find what 2 numbers add to something and multiply to something

Come on guys, there is no need to loop, just use simple math to solve this equation system:

a*b = i;

a+b = j;

a = j/b;

a = i-b;

j/b = i-b; so:

b + j/b + i = 0

b^2 + i*b + j = 0

From here, its a quadratic equation, and it's trivial to find b (just implement the quadratic equation formula) and from there get the value for a.

EDIT:

There you go:

function finder($add,$product)
{

 $inside_root = $add*$add - 4*$product;

 if($inside_root >=0)
 {

     $b = ($add + sqrt($inside_root))/2;
     $a = $add - $b;

     echo "$a+$b = $add and $a*$b=$product\n";

 }else
 {
   echo "No real solution\n";
 }
}

Real live action:

http://codepad.org/JBxMgHBd

How to remove a field completely from a MongoDB document?

Starting Mongo 4.2, it's also possible to use a slightly different syntax:

// { name: "book", tags: { words: ["abc", "123"], lat: 33, long: 22 } }
db.collection.update({}, [{ $unset: ["tags.words"] }], { many: true })
// { name: "book", tags: { lat: 33, long: 22 } }

The update method can also accept an aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline).

This means the $unset operator being used is the aggregation one (as opposed to the "query" one), whose syntax takes an array of fields.

How to pass the button value into my onclick event function?

You can get value by using id for that element in onclick function

function dosomething(){
     var buttonValue = document.getElementById('buttonId').value;
}

What does the CSS rule "clear: both" do?

CSS float and clear

Sample Fiddle

Just try to remove clear:both property from the div with class sample and see how it follows floating divs.

How do you run a Python script as a service in Windows?

Although I upvoted the chosen answer a couple of weeks back, in the meantime I struggled a lot more with this topic. It feels like having a special Python installation and using special modules to run a script as a service is simply the wrong way. What about portability and such?

I stumbled across the wonderful Non-sucking Service Manager, which made it really simple and sane to deal with Windows Services. I figured since I could pass options to an installed service, I could just as well select my Python executable and pass my script as an option.

I have not yet tried this solution, but I will do so right now and update this post along the process. I am also interested in using virtualenvs on Windows, so I might come up with a tutorial sooner or later and link to it here.

What is "Advanced" SQL?

Check out SQL For Smarties. I thought I was pretty good with SQL too, until I read that book... Goes into tons of depth, talks about things I've not seen elsewhere (I.E. difference between 3'rd and 4'th normal form, Boyce Codd Normal Form, etc)...

How can I quickly sum all numbers in a file?

I prefer to use R for this:

$ R -e 'sum(scan("filename"))'

Date Comparison using Java

If you're set on using Java Dates rather than, say, JodaTime, use a java.text.DateFormat to convert the string to a Date, then compare the two using .equals:

I almost forgot: You need to zero out the hours, minutes, seconds, and milliseconds on the current date before comparing them. I used a Calendar object below to do it.

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

// Other code here
    String toDate;
    //toDate = "05/11/2010";

    // Value assigned to toDate somewhere in here

    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
    Calendar currDtCal = Calendar.getInstance();

    // Zero out the hour, minute, second, and millisecond
    currDtCal.set(Calendar.HOUR_OF_DAY, 0);
    currDtCal.set(Calendar.MINUTE, 0);
    currDtCal.set(Calendar.SECOND, 0);
    currDtCal.set(Calendar.MILLISECOND, 0);

    Date currDt = currDtCal.getTime();

    Date toDt;
    try {
        toDt = df.parse(toDate);
    } catch (ParseException e) {
        toDt = null;
        // Print some error message back to the user
    }

    if (currDt.equals(toDt)) {
        // They're the same date
    }

Changing Placeholder Text Color with Swift

Just write below code into Appdelegate's didFinishLaunchingWithOptions method use this if you want to change in the whole app written in Swift 4.2

UILabel.appearance(whenContainedInInstancesOf: [UITextField.self]).textColor = UIColor.white

How to give a pandas/matplotlib bar graph custom colors

I found the easiest way is to use the colormap parameter in .plot() with one of the preset color gradients:

df.plot(kind='bar', stacked=True, colormap='Paired')

enter image description here

You can find a large list of preset colormaps here.

colormaps

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

I was able to achieve this result using the Jenkins Dynamic Parameter Plug-in. I used the Dynamic Choice Parameter option and, for the choices script, I used the following:

proc1 = ['/bin/bash', '-c', "/usr/bin/git ls-remote -h ssh://[email protected]/path/to/repo.git"].execute()
proc2 = ['/bin/bash', '-c', "awk '{print \$2}'"].execute()
proc3 = ['/bin/bash', '-c', "sed s%^refs/heads%origin%"].execute()

all = proc1 | proc2 | proc3
String result = all.text

String filename = "/tmp/branches.txt"
boolean success = new File(filename).write(result) 

def multiline = "cat /tmp/branches.txt".execute().text
def list = multiline.readLines()

SSRS chart does not show all labels on Horizontal axis

image: reporting services line chart horizontal axis properties

To see all dates on the report; Set Axis Type to Scalar, Set Interval to 1 -Jump Labels section Set disable auto-fit set label rotation angle as you desire.

These would help.

How to select data from 30 days?

Short version for easy use:

SELECT * 
FROM [TableName] t
WHERE t.[DateColumnName] >= DATEADD(month, -1, GETDATE())

DATEADD and GETDATE are available in SQL Server starting with 2008 version. MSDN documentation: GETDATE and DATEADD.

Auto Generate Database Diagram MySQL

The "Reverse Engineer Database" mode in Workbench is only part of the paid version, not the free one.

How to show "Done" button on iPhone number pad

Here's the simplest solution I have come across. I have learnt this from Beginning iOS 5 Development book.

Assuming the number field is called numberField.

  1. In ViewController, add the following method:

    -(IBAction)closeKeyboard:(id)sender;
    
  2. In ViewController.m, add the following code:

    -(IBAction)closeKeyboard:(id)sender
    {
    
         [numberField resignFirstResponder];
    
    }
    
  3. Go back to nib file.

  4. Open Utilities pan.
  5. Open the Identity inspector under Utilities pan.
  6. Click on the View (in nib file) once. Make sure you have not clicked on any of the items in the view. For the sake of clarification, you should see UIView under Class in Identity inspector.
  7. Change the class from UIView to UIControl.
  8. Open Connection Inspector.
  9. Click and drag Touch Down and drop the arrow on File Owner icon. (FYI... File Owner icon is displayed on the left of View and appears as a hollow cube with yellow frame.)
  10. Select the method: closeKeyboard.
  11. Run the program.

Now when you click anywhere on background of View, you should be able to dismiss the keyboard.

Hope this helps you solve your problem. :-)

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

Following @Michelle Tilley solution, apparently it didn't work for me at first. Not sure why, maybe I am using chrome and different version of node. After did some minor tweaks, it is working for me now.

app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

In case someone facing similar issue as mine, this might be helpful.

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

How to Bold entire row 10 example:

workSheet.Cells[10, 1].EntireRow.Font.Bold = true;    

More formally:

Microsoft.Office.Interop.Excel.Range rng = workSheet.Cells[10, 1] as Xl.Range;
rng.EntireRow.Font.Bold = true;

How to Bold Specific Cell 'A10' for example:

workSheet.Cells[10, 1].Font.Bold = true;

Little more formal:

int row = 1;
int column = 1;  /// 1 = 'A' in Excel

Microsoft.Office.Interop.Excel.Range rng = workSheet.Cells[row, column] as Xl.Range;
rng.Font.Bold = true;

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

Get cart item name, quantity all details woocommerce

Try this :

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id()); 
            echo "<b>".$_product->get_title().'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
        } 
?>

To get Product Image and Regular & Sale Price:

<?php
    global $woocommerce;
    $items = $woocommerce->cart->get_cart();

        foreach($items as $item => $values) { 
            $_product =  wc_get_product( $values['data']->get_id() );
            //product image
            $getProductDetail = wc_get_product( $values['product_id'] );
            echo $getProductDetail->get_image(); // accepts 2 arguments ( size, attr )

            echo "<b>".$_product->get_title() .'</b>  <br> Quantity: '.$values['quantity'].'<br>'; 
            $price = get_post_meta($values['product_id'] , '_price', true);
            echo "  Price: ".$price."<br>";
            /*Regular Price and Sale Price*/
            echo "Regular Price: ".get_post_meta($values['product_id'] , '_regular_price', true)."<br>";
            echo "Sale Price: ".get_post_meta($values['product_id'] , '_sale_price', true)."<br>";
        }
?>

When to use in vs ref vs out

You should use out unless you need ref.

It makes a big difference when the data needs to be marshalled e.g. to another process, which can be costly. So you want to avoid marshalling the initial value when the method doesn't make use of it.

Beyond that, it also shows the reader of the declaration or the call whether the initial value is relevant (and potentially preserved), or thrown away.

As a minor difference, an out parameter needs not be initialized.

Example for out:

string a, b;
person.GetBothNames(out a, out b);

where GetBothNames is a method to retrieve two values atomically, the method won't change behavior whatever a and b are. If the call goes to a server in Hawaii, copying the initial values from here to Hawaii is a waste of bandwidth. A similar snippet using ref:

string a = String.Empty, b = String.Empty;
person.GetBothNames(ref a, ref b);

could confuse readers, because it looks like the initial values of a and b are relevant (though the method name would indicate they are not).

Example for ref:

string name = textbox.Text;
bool didModify = validator.SuggestValidName(ref name);

Here the initial value is relevant to the method.

TortoiseSVN icons overlay not showing after updating to Windows 10

Had same issue, and was solved by running regedit, erasing some entries in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\ShellIconOverlayIdentifiers and restarting. Deleting OneDrive1... enties was not permited, but I had some from Google Drive. You can also make a bakup by double-clicking in the registry directory and doing an "Export" to a file.

On Windows 10, most of the entries are used by OneDrive and you won't have permission to remove them. In order to do so, right click on the entry (Example: "OneDrive1", then click "Advanced", then click the link labled "Change" at the very top next to "Owner". This lets you change the owner. Type in your username and hit OK. Now give yourself "Full Control" and then apply it. Now you should be able to delete or rename it.

Build android release apk on Phonegap 3.x CLI

i got this to work by copy pasting the signed app in the same dir as zipalign. It seems that aapt.exe could not find the source file even when given the path. i.e. this did not work zipalign -f -v 4 C:...\CordovaApp-release-unsigned.apk C:...\destination.apk it reached aapt.exeCordovaApp-release-unsigned.apk , froze and upon hitting return 'aapt.exeCordovaApp-release-unsigned.apk' is not recognized as an internal or external command, operable program or batch file. And this did zipalign -f -v 4 CordovaApp-release-unsigned.apk myappname.apk

"git checkout <commit id>" is changing branch to "no branch"

If you checkout a commit sha directly, it puts you into a "detached head" state, which basically just means that the current sha that your working copy has checked out, doesn't have a branch pointing at it.

If you haven't made any commits yet, you can leave detached head state by simply checking out whichever branch you were on before checking out the commit sha:

git checkout <branch>

If you did make commits while you were in the detached head state, you can save your work by simply attaching a branch before or while you leave detached head state:

# Checkout a new branch at current detached head state:
git checkout -b newBranch

You can read more about detached head state at the official Linux Kernel Git docs for checkout.

Oracle PL/SQL - How to create a simple array variable?

You can use VARRAY for a fixed-size array:

declare
   type array_t is varray(3) of varchar2(10);
   array array_t := array_t('Matt', 'Joanne', 'Robert');
begin
   for i in 1..array.count loop
       dbms_output.put_line(array(i));
   end loop;
end;

Or TABLE for an unbounded array:

...
   type array_t is table of varchar2(10);
...

The word "table" here has nothing to do with database tables, confusingly. Both methods create in-memory arrays.

With either of these you need to both initialise and extend the collection before adding elements:

declare
   type array_t is varray(3) of varchar2(10);
   array array_t := array_t(); -- Initialise it
begin
   for i in 1..3 loop
      array.extend(); -- Extend it
      array(i) := 'x';
   end loop;
end;

The first index is 1 not 0.

Map a network drive to be used by a service

You'll either need to modify the service, or wrap it inside a helper process: apart from session/drive access issues, persistent drive mappings are only restored on an interactive logon, which services typically don't perform.

The helper process approach can be pretty simple: just create a new service that maps the drive and starts the 'real' service. The only things that are not entirely trivial about this are:

  • The helper service will need to pass on all appropriate SCM commands (start/stop, etc.) to the real service. If the real service accepts custom SCM commands, remember to pass those on as well (I don't expect a service that considers UNC paths exotic to use such commands, though...)

  • Things may get a bit tricky credential-wise. If the real service runs under a normal user account, you can run the helper service under that account as well, and all should be OK as long as the account has appropriate access to the network share. If the real service will only work when run as LOCALSYSTEM or somesuch, things get more interesting, as it either won't be able to 'see' the network drive at all, or require some credential juggling to get things to work.

Maven – Always download sources and javadocs

I am using Maven 3.3.3 and cannot get the default profile to work in a user or global settings.xml file.

As a workaround, you may also add an additional build plugin to your pom.xml file.

<properties>
    <maven-dependency-plugin.version>2.10</maven-dependency-plugin.version>
</properties>
<build>
    <plugins>
        <!-- Download Java source JARs. -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>${maven-dependency-plugin.version}</version>
            <executions>
                <execution>
                    <goals>
                        <goal>sources</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

How to find the path of Flutter SDK

Download flutter from FLUTTER

or clone from master git clone -b master https://github.com/flutter/flutter.git

So, the flutter sdk path is where you copied or cloned the code till the C:\whateverDrive\flutter inside bin there is a file flutter so when coming to choosing SDK, please select the folder till flutter and add the same in env variable in your windows. remember to add the path till bin that is enough.

configuring the flutter sdk in android studio follow this carefully. This explains everything. ;)

HRESULT: 0x800A03EC on Worksheet.range

I received this error code 0x800A03EC when trying to save an Excel file created within my .Net application in VS 2017. I changed the Excel.Application object property Visible=True and let it run until the point of failure. Tried to finish the steps manually in Excel and then discovered I could not save the file because of missing folder permissions. I added the Write permission to the folder, and the error went away.

TypeError: p.easing[this.easing] is not a function

I have found the problem: Don't use CDN (this is causing the problem!), instead save the jquery file locally on your server and then the problem is away.

Regular expression to match URLs in Java

((http?|https|ftp|file)://)?((W|w){3}.)?[a-zA-Z0-9]+\.[a-zA-Z]+

check here:- https://www.freeformatter.com/java-regex-tester.html#ad-output

It sorts out theses entries correctly

SVN "Already Locked Error"

I am not using AnkhSVN but got a similar problem after cancelling a Tortoise SVN update. It left two directories "already locked". Similar to Roman C's solution. Use Get lock to to lock one file in each directory that is "already locked" and then release those locks, then do a cleanup on the highest directory. That seemed to fix the problem.

BeautifulSoup Grab Visible Webpage Text

The simplest way to handle this case is by using getattr(). You can adapt this example to your needs:

from bs4 import BeautifulSoup

source_html = """
<span class="ratingsDisplay">
    <a class="ratingNumber" href="https://www.youtube.com/watch?v=oHg5SJYRHA0" target="_blank" rel="noopener">
        <span class="ratingsContent">3.7</span>
    </a>
</span>
"""

soup = BeautifulSoup(source_html, "lxml")
my_ratings = getattr(soup.find('span', {"class": "ratingsContent"}), "text", None)
print(my_ratings)

This will find the text element,"3.7", within the tag object <span class="ratingsContent">3.7</span> when it exists, however, default to NoneType when it does not.

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise, AttributeError is raised.

YouTube embedded video: set different thumbnail

This tool gave me following results which helps me achieve the task as following code.

<div onclick="play();" id="vidwrap" style="height:315px;width:560px;background: black url('http://example.com/image.jpg') no-repeat center;overflow:hidden;cursor:pointer;"></div>
<script type="text/javascript">
    function play(){
        document.getElementById('vidwrap').innerHTML = '<iframe width="560" height="315" src="http://www.youtube.com/embed/xxxxxxxxx?autoplay=1" frameborder="0"></iframe>';
    }
</script>

Why does Python code use len() function instead of a length method?

Jim's answer to this question may help; I copy it here. Quoting Guido van Rossum:

First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much later). There are two intertwined reasons actually, both HCI:

(a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into xa + xb to the clumsiness of doing the same thing using a raw OO notation.

(b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method.

Saying the same thing in another way, I see ‘len‘ as a built-in operation. I’d hate to lose that. /…/

How to list all files in a directory and its subdirectories in hadoop hdfs

If you are using hadoop 2.* API there are more elegant solutions:

    Configuration conf = getConf();
    Job job = Job.getInstance(conf);
    FileSystem fs = FileSystem.get(conf);

    //the second boolean parameter here sets the recursion to true
    RemoteIterator<LocatedFileStatus> fileStatusListIterator = fs.listFiles(
            new Path("path/to/lib"), true);
    while(fileStatusListIterator.hasNext()){
        LocatedFileStatus fileStatus = fileStatusListIterator.next();
        //do stuff with the file like ...
        job.addFileToClassPath(fileStatus.getPath());
    }

creating a random number using MYSQL

Additional to this answer, create a function like

CREATE FUNCTION myrandom(
    pmin INTEGER,
    pmax INTEGER
)
RETURNS INTEGER(11)
DETERMINISTIC
NO SQL
SQL SECURITY DEFINER
BEGIN
  RETURN floor(pmin+RAND()*(pmax-pmin));
END; 

and call like

SELECT myrandom(100,300);

This gives you random number between 100 and 300

Git on Mac OS X v10.7 (Lion)

There are a couple of points to this answer.

Firstly, you don't need to install Xcode. The Git installer works perfectly well. However, if you want to use Git from within Xcode - it expects to find an installation under /usr/local/bin. If you have your own Git installed elsewhere - I've got a script that fixes this.

Second is to do with the path. My Git path used to be kept under /etc/paths.d/ However, a Mac OS X v10.7 (Lion) install overwrites the contents of this folder and the /etc/paths file as well. That's what happened to me and I got the same error. Recreating the path file fixed the problem.

What is the difference between print and puts?

print outputs each argument, followed by $,, to $stdout, followed by $\. It is equivalent to args.join($,) + $\

puts sets both $, and $\ to "\n" and then does the same thing as print. The key difference being that each argument is a new line with puts.

You can require 'english' to access those global variables with user-friendly names.

How do I execute a command and get the output of the command within C++ using POSIX?

Getting both stdout and stderr (and also writing to stdin, not shown here) is easy peasy with my pstreams header, which defines iostream classes that work like popen:

#include <pstream.h>
#include <string>
#include <iostream>

int main()
{
  // run a process and create a streambuf that reads its stdout and stderr
  redi::ipstream proc("./some_command", redi::pstreams::pstdout | redi::pstreams::pstderr);
  std::string line;
  // read child's stdout
  while (std::getline(proc.out(), line))
    std::cout << "stdout: " << line << '\n';
  # if reading stdout stopped at EOF then reset the state:
  if (proc.eof() && proc.fail())
    proc.clear();
  // read child's stderr
  while (std::getline(proc.err(), line))
    std::cout << "stderr: " << line << '\n';
} 

StringIO in Python3

when i write import StringIO it says there is no such module.

From What’s New In Python 3.0:

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

.


A possibly useful method of fixing some Python 2 code to also work in Python 3 (caveat emptor):

try:
    from StringIO import StringIO ## for Python 2
except ImportError:
    from io import StringIO ## for Python 3

Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing StringIO module. For a more direct solution the message TypeError: Can't convert 'bytes' object to str implicitly, see this answer.

Adding and using header (HTTP) in nginx

To add a header just add the following code to the location block where you want to add the header:

location some-location {
  add_header X-my-header my-header-content;      
}

Obviously, replace the x-my-header and my-header-content with what you want to add. And that's all there is to it.

Android, How to create option Menu

Replace return super.onCreateOptionsMenu(menu); with return true; in your onCreateOptionsMenu method This will help

And you should also have the onCreate method in your activity

Absolute and Flexbox in React Native

The first step would be to add

position: 'absolute',

then if you want the element full width, add

left: 0,
right: 0,

then, if you want to put the element in the bottom, add

bottom: 0,
// don't need set top: 0

if you want to position the element at the top, replace bottom: 0 by top: 0

How to use OKHTTP to make a post request?

If you want to post parameter in okhttp as body content which can be encrypted string with content-type as "application/x-www-form-urlencoded" you can first use URLEncoder to encode the data and then use :

final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("application/x-www-form-urlencoded");

okhttp3.Request request = new okhttp3.Request.Builder()
    .url(urlOfServer)
    .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, yourBodyDataToPostOnserver))
    .build();

you can add header according to your requirement.

How to set web.config file to show full error message

not sure if it'll work in your scenario, but try adding the following to your web.config under <system.web>:

  <system.web>
    <customErrors mode="Off" />
  ...
  </system.web>

works in my instance.

also see:

CustomErrors mode="Off"

Android: Color To Int conversion

R.color.black or some color are obviously integers. It needs a RGB value. You can give your own like #FF123454 which represents various primary colors

PHP Include for HTML?

Try to get some debugging information, could be that the file path is wrong, for example.

Try these two things:- Add this line to the top of your sample page:

<?php error_reporting(E_ALL);?>

This will print all errors/warnings/notices in the page so if there is any problem you get a text message describing it instead of a blank page

Additionally you can change include() to require()

<?php require ('headings.php'); ?>
<?php require ('navbar.php'); ?>
<?php require ('image.php'); ?>

This will throw a FATAL error PHP is unable to load required pages, and should help you in getting better tracing what is going wrong..

You can post the error descriptions here, if you get any, and you are unable to figure out what it means..

Convert Iterator to ArrayList

List result = new ArrayList();
while (i.hasNext()){
    result.add(i.next());
}

How to pass extra variables in URL with WordPress

<?php
$edit_post = add_query_arg('c', '123', 'news' );

?>

<a href="<?php echo $edit_post; ?>">Go to New page</a>

You can add any page inplace of "news".

Is there any way to install Composer globally on Windows?

Sure. Just put composer.phar somewhere like C:\php\composer.phar, then make a batch file somewhere within the PATH called composer.bat which does the following:

@ECHO OFF
php "%~dp0composer.phar" %*

The "%*" repeats all of the arguments passed to the shell script.

Then you can run around doing composer update all ya want!

JSONDecodeError: Expecting value: line 1 column 1

If you look at the output you receive from print() and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b):

b'{\n  "note":"This file    .....

If you fetch the URL using a tool such as curl -v, you will see that the content type is

Content-Type: application/json; charset=utf-8

So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.

Change the last line of code to this:

info = json.loads(js.decode("utf-8"))

What is the default database path for MongoDB?

I depends on the version and the distro.

For example the default download pre-2.2 from the MongoDB site uses: /data/db but the Ubuntu install at one point used to use: var/lib/mongodb.

I think these have been standardised now so that 2.2+ will only use data/db whether it comes from direct download on the site or from the repos.

How to commit my current changes to a different branch in Git

The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash:

git stash
git checkout other-branch
git stash pop

The first stash hides away your changes (basically making a temporary commit), and the subsequent stash pop re-applies them. This lets Git use its merge capabilities.

If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.

On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:

# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset

# Add the things you *do* want to commit here
git add -p     # or maybe git add -i
git commit

# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop

# Add the changes meant for this branch
git add -p
git commit

# And throw away the rest
git reset --hard

Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:

git add -p
git commit
git stash
git checkout other-branch
git stash pop

And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1) to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)

Example of multipart/form-data

Many thanks to @Ciro Santilli answer! I found that his choice for boundary is quite "unhappy" because all of thoose hyphens: in fact, as @Fake Name commented, when you are using your boundary inside request it comes with two more hyphens on front:

Example:

POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345

--12345
Content-Disposition: form-data; name="sometext"

some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"

content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"

content of picture_of_sunset.jpg ...
--12345--

I found on this w3.org page that is possible to incapsulate multipart/mixed header in a multipart/form-data, simply choosing another boundary string inside multipart/mixed and using that one to incapsulate data. At the end, you must "close" all boundary used in FILO order to close the POST request (like:

POST / HTTP/1.1
...
Content-Type: multipart/form-data; boundary=12345

--12345
Content-Disposition: form-data; name="sometext"

some text sent via post...
--12345
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=abcde

--abcde
Content-Disposition: file; file="picture.jpg"

content of jpg...
--abcde
Content-Disposition: file; file="test.py"

content of test.py file ....
--abcde--
--12345--

Take a look at the link above.

Convert text into number in MySQL query

A generic way to do :

SELECT * FROM your_table ORDER BY LENTH(your_column) ASC, your_column ASC

Html.EditorFor Set Default Value

Its not right to set default value in View. The View should perform display work, not more. This action breaks ideology of MVC pattern. So the right place to set defaults - create method of controller class.

How to list all methods for an object in Ruby?

The following will list the methods that the User class has that the base Object class does not have...

>> User.methods - Object.methods
=> ["field_types", "maximum", "create!", "active_connections", "to_dropdown",
    "content_columns", "su_pw?", "default_timezone", "encode_quoted_value", 
    "reloadable?", "update", "reset_sequence_name", "default_timezone=", 
    "validate_find_options", "find_on_conditions_without_deprecation", 
    "validates_size_of", "execute_simple_calculation", "attr_protected", 
    "reflections", "table_name_prefix", ...

Note that methods is a method for Classes and for Class instances.

Here's the methods that my User class has that are not in the ActiveRecord base class:

>> User.methods - ActiveRecord::Base.methods
=> ["field_types", "su_pw?", "set_login_attr", "create_user_and_conf_user", 
    "original_table_name", "field_type", "authenticate", "set_default_order",
    "id_name?", "id_name_column", "original_locking_column", "default_order",
    "subclass_associations",  ... 
# I ran the statements in the console.

Note that the methods created as a result of the (many) has_many relationships defined in the User class are not in the results of the methods call.

Added Note that :has_many does not add methods directly. Instead, the ActiveRecord machinery uses the Ruby method_missing and responds_to techniques to handle method calls on the fly. As a result, the methods are not listed in the methods method result.

Conda command not found

I faced this issue on my mac after updating conda. Solution was to run conda mini installer on top of existing conda setup.

$ curl https://repo.continuum.io/miniconda/Miniconda3-latest-MacOSX-x86_64.sh -o ~/miniconda3.sh
$ bash ~/miniconda3.sh -bfp ~/miniconda3

On linux, you can use:

$ curl https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -o ~/miniconda3.sh
$ bash ~/miniconda3.sh -bfp ~/miniconda3

For other versions, you can go to https://repo.continuum.io/miniconda/

For details check: https://github.com/conda/conda/issues/1364

How do I "select Android SDK" in Android Studio?

Press "Ctrl+shift+A" and in the pop-up EditText, write "Sync Project with Gradle Files". After that double click on the appeared option. It will then sync your Gradle file SDK with the project file.

Check if element is in the list (contains)

Use std::find, something like:

if (std::find(std::begin(my_list), std::end(my_list), my_var) != std::end(my_list))
    // my_list has my_var

Disable form auto submit on button click

Buttons like <button>Click to do something</button> are submit buttons.

Set type="button" to change that. type="submit" is the default (as specified by the HTML recommendation).

Good tutorial for using HTML5 History API (Pushstate?)

For a great tutorial the Mozilla Developer Network page on this functionality is all you'll need: https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history

Unfortunately, the HTML5 History API is implemented differently in all the HTML5 browsers (making it inconsistent and buggy) and has no fallback for HTML4 browsers. Fortunately, History.js provides cross-compatibility for the HTML5 browsers (ensuring all the HTML5 browsers work as expected) and optionally provides a hash-fallback for HTML4 browsers (including maintained support for data, titles, pushState and replaceState functionality).

You can read more about History.js here: https://github.com/browserstate/history.js

For an article about Hashbangs VS Hashes VS HTML5 History API, see here: https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling

Is it safe to clean docker/overlay2/

Backgroud

The blame for the issue can be split between our misconfiguration of container volumes, and a problem with docker leaking (failing to release) temporary data written to these volumes. We should be mapping (either to host folders or other persistent storage claims) all of out container's temporary / logs / scratch folders where our apps write frequently and/or heavily. Docker does not take responsibility for the cleanup of all automatically created so-called EmptyDirs located by default in /var/lib/docker/overlay2/*/diff/*. Contents of these "non-persistent" folders should be purged automatically by docker after container is stopped, but apparently are not (they may be even impossible to purge from the host side if the container is still running - and it can be running for months at a time).

Workaround

A workaround requires careful manual cleanup, and while already described elsewhere, you still may find some hints from my case study, which I tried to make as instructive and generalizable as possible.

So what happened is the culprit app (in my case clair-scanner) managed to write over a few months hundreds of gigs of data to the /diff/tmp subfolder of docker's overlay2

du -sch /var/lib/docker/overlay2/<long random folder name seen as bloated in df -haT>/diff/tmp

271G total

So as all those subfolders in /diff/tmp were pretty self-explanatory (all were of the form clair-scanner-* and had obsolete creation dates), I stopped the associated container (docker stop clair) and carefully removed these obsolete subfolders from diff/tmp, starting prudently with a single (oldest) one, and testing the impact on docker engine (which did require restart [systemctl restart docker] to reclaim disk space):

rm -rf $(ls -at /var/lib/docker/overlay2/<long random folder name seen as bloated in df -haT>/diff/tmp | grep clair-scanner | tail -1)

I reclaimed hundreds of gigs of disk space without the need to re-install docker or purge its entire folders. All running containers did have to be stopped at one point, because docker daemon restart was required to reclaim disk space, so make sure first your failover containers are running correctly on an/other node/s). I wish though that the docker prune command could cover the obsolete /diff/tmp (or even /diff/*) data as well (via yet another switch).

It's a 3-year-old issue now, you can read its rich and colorful history on Docker forums, where a variant aimed at application logs of the above solution was proposed in 2019 and seems to have worked in several setups: https://forums.docker.com/t/some-way-to-clean-up-identify-contents-of-var-lib-docker-overlay/30604

Google reCAPTCHA: How to get user response and validate in the server side?

Hi curious you can validate your google recaptcha at client side also 100% work for me to verify your google recaptcha just see below code
This code at the html body:

 <div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
 <span id="captcha" style="margin-left:100px;color:red" />

This code put at head section on call get_action(this) method form button:

function get_action(form) {

var v = grecaptcha.getResponse();
if(v.length == 0)
{
    document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
    return false;
}
 if(v.length != 0)
 {
    document.getElementById('captcha').innerHTML="Captcha completed";
    return true; 
 }
}

How to convert UTF-8 byte[] to string?

Using (byte)b.ToString("x2"), Outputs b4b5dfe475e58b67

public static class Ext {

    public static string ToHexString(this byte[] hex)
    {
        if (hex == null) return null;
        if (hex.Length == 0) return string.Empty;

        var s = new StringBuilder();
        foreach (byte b in hex) {
            s.Append(b.ToString("x2"));
        }
        return s.ToString();
    }

    public static byte[] ToHexBytes(this string hex)
    {
        if (hex == null) return null;
        if (hex.Length == 0) return new byte[0];

        int l = hex.Length / 2;
        var b = new byte[l];
        for (int i = 0; i < l; ++i) {
            b[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
        }
        return b;
    }

    public static bool EqualsTo(this byte[] bytes, byte[] bytesToCompare)
    {
        if (bytes == null && bytesToCompare == null) return true; // ?
        if (bytes == null || bytesToCompare == null) return false;
        if (object.ReferenceEquals(bytes, bytesToCompare)) return true;

        if (bytes.Length != bytesToCompare.Length) return false;

        for (int i = 0; i < bytes.Length; ++i) {
            if (bytes[i] != bytesToCompare[i]) return false;
        }
        return true;
    }

}

Model summary in pytorch

While you will not get as detailed information about the model as in Keras' model.summary, simply printing the model will give you some idea about the different layers involved and their specifications.

For instance:

from torchvision import models
model = models.vgg16()
print(model)

The output in this case would be something as follows:

VGG (
  (features): Sequential (
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU (inplace)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU (inplace)
    (4): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1))
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU (inplace)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU (inplace)
    (9): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1))
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU (inplace)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU (inplace)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU (inplace)
    (16): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1))
    (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (18): ReLU (inplace)
    (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU (inplace)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU (inplace)
    (23): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1))
    (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (25): ReLU (inplace)
    (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (27): ReLU (inplace)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU (inplace)
    (30): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1))
  )
  (classifier): Sequential (
    (0): Dropout (p = 0.5)
    (1): Linear (25088 -> 4096)
    (2): ReLU (inplace)
    (3): Dropout (p = 0.5)
    (4): Linear (4096 -> 4096)
    (5): ReLU (inplace)
    (6): Linear (4096 -> 1000)
  )
)

Now you could, as mentioned by Kashyap, use the state_dict method to get the weights of the different layers. But using this listing of the layers would perhaps provide more direction is creating a helper function to get that Keras like model summary! Hope this helps!

Possible to iterate backwards through a foreach?

It is possible if you can change the collection code that implements IEnumerable or IEnumerable (e.g. your own implementation of IList).

Create an Iterator doing this job for you, for example like the following implementation through the IEnumerable interface (assuming 'items' is a List field in this sample):

public IEnumerator<TObject> GetEnumerator()
{
    for (var i = items.Count - 1; i >= 0; i--)
    { 
        yield return items[i];
    }
}

IEnumerator IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}

Because of this your List will iterate in reverse order through your list.

Just a hint: You should clearly state this special behaviour of your list within the documentation (even better by choosing a self-explaining class name like Stack or Queue, too).

Correct way of looping through C++ arrays

sizeof(texts) on my system evaluated to 96: the number of bytes required for the array and its string instances.

As mentioned elsewhere, the sizeof(texts)/sizeof(texts[0]) would give the value of 3 you were expecting.

Getting the computer name in Java

The computer "name" is resolved from the IP address by the underlying DNS (Domain Name System) library of the OS. There's no universal concept of a computer name across OSes, but DNS is generally available. If the computer name hasn't been configured so DNS can resolve it, it isn't available.

import java.net.InetAddress;
import java.net.UnknownHostException;

String hostname = "Unknown";

try
{
    InetAddress addr;
    addr = InetAddress.getLocalHost();
    hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
    System.out.println("Hostname can not be resolved");
}

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

I'd do

for i in `seq 0 2 10`; do echo $i; done

(though of course seq 0 2 10 will produce the same output on its own).

Note that seq allows floating-point numbers (e.g., seq .5 .25 3.5) but bash's brace expansion only allows integers.

Google Maps API: open url by clicking on marker

If anyone wants to add an URL on a single marker which not require for loops, here is how it goes:

if ($('#googleMap').length) {
    var initialize = function() {
        var mapOptions = {
            zoom: 15,
            scrollwheel: false,
            center: new google.maps.LatLng(45.725788, -73.5120818),
            styles: [{
                stylers: [{
                    saturation: -100
                }]
            }]
        };
        var map = new google.maps.Map(document.getElementById("googleMap"), mapOptions);
        var marker = new google.maps.Marker({
            position: map.getCenter(),
            animation: google.maps.Animation.BOUNCE,
            icon: 'example-marker.png',
            map: map,
            url: 'https://example.com'
        });

        //Add an url to the marker
    google.maps.event.addListener(marker, 'click', function() {
        window.location.href = this.url;
    });
    }
    // Add the map initialize function to the window load function
    google.maps.event.addDomListener(window, "load", initialize);
}

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

You might also consider removing the need for duplicated parameter names in your Sql by changing your Sql to

table.Variable2 LIKE '%' || :VarB || '%'

and then getting your client to provide '%' for any value of VarB instead of null. In some ways I think this is more natural.

You could also change the Sql to

table.Variable2 LIKE '%' || IfNull(:VarB, '%') || '%'

What does the clearfix class do in css?

How floats work

When floating elements exist on the page, non-floating elements wrap around the floating elements, similar to how text goes around a picture in a newspaper. From a document perspective (the original purpose of HTML), this is how floats work.

float vs display:inline

Before the invention of display:inline-block, websites use float to set elements beside each other. float is preferred over display:inline since with the latter, you can't set the element's dimensions (width and height) as well as vertical paddings (top and bottom) - which floated elements can do since they're treated as block elements.

Float problems

The main problem is that we're using float against its intended purpose.

Another is that while float allows side-by-side block-level elements, floats do not impart shape to its container. It's like position:absolute, where the element is "taken out of the layout". For instance, when an empty container contains a floating 100px x 100px <div>, the <div> will not impart 100px in height to the container.

Unlike position:absolute, it affects the content that surrounds it. Content after the floated element will "wrap" around the element. It starts by rendering beside it and then below it, like how newspaper text would flow around an image.

Clearfix to the rescue

What clearfix does is to force content after the floats or the container containing the floats to render below it. There are a lot of versions for clear-fix, but it got its name from the version that's commonly being used - the one that uses the CSS property clear.

Examples

Here are several ways to do clearfix , depending on the browser and use case. One only needs to know how to use the clear property in CSS and how floats render in each browser in order to achieve a perfect cross-browser clear-fix.

What you have

Your provided style is a form of clearfix with backwards compatibility. I found an article about this clearfix. It turns out, it's an OLD clearfix - still catering the old browsers. There is a newer, cleaner version of it in the article also. Here's the breakdown:

  • The first clearfix you have appends an invisible pseudo-element, which is styled clear:both, between the target element and the next element. This forces the pseudo-element to render below the target, and the next element below the pseudo-element.

  • The second one appends the style display:inline-block which is not supported by earlier browsers. inline-block is like inline but gives you some properties that block elements, like width, height as well as vertical padding. This was targeted for IE-MAC.

  • This was the reapplication of display:block due to IE-MAC rule above. This rule was "hidden" from IE-MAC.

All in all, these 3 rules keep the .clearfix working cross-browser, with old browsers in mind.

How to change a <select> value from JavaScript

I think I know what the problem is here - if you are trying to have it select an option that doesn't exist, it won't work. You need to ADD the option first. Like so:

var option=document.createElement("option");
option.text=document.getElementById('other_referee').value
document.getElementById('referee_new').add(option,null);
document.getElementById('referee_new').value = document.getElementById('other_referee').value;

Not elegant, but you get the idea.

How to disable HTML button using JavaScript?

<button disabled=true>text here</button>

You can still use an attribute. Just use the 'disabled' attribute instead of 'value'.

How do I authenticate a WebClient request?

This helped me to call API that was using cookie authentication. I have passed authorization in header like this:

request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));

complete code:

// utility method to read the cookie value:
        public static string ReadCookie(string cookieName)
        {
            var cookies = HttpContext.Current.Request.Cookies;
            var cookie = cookies.Get(cookieName);
            if (cookie != null)
                return cookie.Value;
            return null;
        }

// using statements where you are creating your webclient
using System.Web.Script.Serialization;
using System.Net;
using System.IO;

// WebClient:

var requestUrl = "<API_url>";
var postRequest = new ClassRoom { name = "kushal seth" };

using (var webClient = new WebClient()) {
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      byte[] requestData = Encoding.ASCII.GetBytes(serializer.Serialize(postRequest));
      HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
      request.Method = "POST";
      request.ContentType = "application/json";                        
      request.ContentLength = requestData.Length;
      request.ContentType = "application/json";
      request.Expect = "application/json";
      request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));
      request.GetRequestStream().Write(requestData, 0, requestData.Length);

      using (var response = (HttpWebResponse)request.GetResponse()) {
         var reader = new StreamReader(response.GetResponseStream());
         var objText = reader.ReadToEnd(); // objText will have the value
      }
}


Simplest way to restart service on a remote computer

I recommend the method given by doofledorfer.

If you really want to do it via a direct API call, then look at the OpenSCManager function. Below are sample functions to take a machine name and service, and stop or start them.

function ServiceStart(sMachine, sService : string) : boolean;  //start service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    psTemp     : PChar;
    dwChkP     : DWord;
begin
  ss.dwCurrentState := 0;
  schm := OpenSCManager(PChar(sMachine),Nil,SC_MANAGER_CONNECT);  //connect to the service control manager

  if(schm > 0)then begin // if successful...
    schs := OpenService( schm,PChar(sService),SERVICE_START or SERVICE_QUERY_STATUS);    // open service handle, start and query status
    if(schs > 0)then begin     // if successful...
      psTemp := nil;
      if (StartService(schs,0,psTemp)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_RUNNING <> ss.dwCurrentState)do begin
          dwChkP := ss.dwCheckPoint;  //dwCheckPoint contains a value incremented periodically to report progress of a long operation.  Store it.
          Sleep(ss.dwWaitHint);  //Sleep for recommended time before checking status again
          if(not QueryServiceStatus(schs,ss))then
            break;  //couldn't check status
          if(ss.dwCheckPoint < dwChkP)then
            Break;  //if QueryServiceStatus didn't work for some reason, avoid infinite loop
        end;  //while not running
      CloseServiceHandle(schs);
    end;  //if able to get service handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_RUNNING = ss.dwCurrentState;  //if we were able to start it, return true
end;

function ServiceStop(sMachine, sService : string) : boolean;  //stop service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    dwChkP     : DWord;
begin
  schm := OpenSCManager(PChar(sMachine),nil,SC_MANAGER_CONNECT);

  if(schm > 0)then begin
    schs := OpenService(schm,PChar(sService),SERVICE_STOP or SERVICE_QUERY_STATUS);
    if(schs > 0)then begin
      if (ControlService(schs,SERVICE_CONTROL_STOP,ss)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_STOPPED <> ss.dwCurrentState) do begin
          dwChkP := ss.dwCheckPoint;
          Sleep(ss.dwWaitHint);
          if(not QueryServiceStatus(schs,ss))then
            Break;

          if(ss.dwCheckPoint < dwChkP)then
            Break;
        end;  //while
      CloseServiceHandle(schs);
    end;  //if able to get svc handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_STOPPED = ss.dwCurrentState;
end;