Programs & Examples On #Meta tags

The HTML meta element provides a means to add various kinds of metadata to an HTML document.

Getting title and meta tags from external website

Improved answer from @shamittomar above to get the meta tags (or the specified one from html source)

Can be improved further... the difference from php's default get_meta_tags is that it works even when there is unicode string

function getMetaTags($html, $name = null)
{
    $doc = new DOMDocument();
    try {
        @$doc->loadHTML($html);
    } catch (Exception $e) {

    }

    $metas = $doc->getElementsByTagName('meta');

    $data = [];
    for ($i = 0; $i < $metas->length; $i++)
    {
        $meta = $metas->item($i);

        if (!empty($meta->getAttribute('name'))) {
            // will ignore repeating meta tags !!
            $data[$meta->getAttribute('name')] = $meta->getAttribute('content');
        }
    }

    if (!empty($name)) {
        return !empty($data[$name]) ? $data[$name] : false;
    }

    return $data;
}

What is the attribute property="og:title" inside meta tag?

The property in meta tags allows you to specify values to property fields which come from a property library. The property library (RDFa format) is specified in the head tag.

For example, to use that code you would have to have something like this in your <head tag. <head xmlns:og="http://example.org/"> and inside the http://example.org/ there would be a specification for title (og:title).

The tag from your example was almost definitely from the Open Graph Protocol, the purpose is to specify structured information about your website for the use of Facebook (and possibly other search engines).

Is it possible to use JavaScript to change the meta-tags of the page?

No, a div is a body element, not a head element

EDIT: Then the only thing SEs are going to get is the base HTML, not the ajax modified one.

Provide an image for WhatsApp link sharing

2020 standards

It takes a few steps to get the perfect preview for WhatsApp, Twitter, Facebook and bookmark icons for pc's and mobile devices. If you like reading go to ogp.me - but make sure to read steps 1 - 6 in this answer to get the best WhatsApp preview.

Please note: some apps or websites use cache or even store the website preview to their database. This means when you're testing your link in WhatsApp or Facebook for example, you'll most likely not see any difference right away. Using another link (another page) will do the trick. But as soon as you use that link once, this "please note" section starts all over again.


Step 1: title

Maximum of 65 characters

<title>your keyword rich title of the website and/or webpage</title>

Step 2: description

Maximum of 155 characters

<meta name="description" content="description of your website/webpage, make sure you use keywords!">

Step 3: og:title

Maximum 35 characters

<meta property="og:title" content="short title of your website/webpage" />

Step 4: og:url

Full link to the current webpage address

<meta property="og:url" content="https://www.example.com/webpage/" />

Step 5: og:description

Maximum 65 characters

<meta property="og:description" content="description of your website/webpage">

Step 6: og:image

Image(JPG or PNG) with a size less than 300KB and minimum dimensions of 300 x 200 *. This image should be served via a HTTPS connection with a valid non-self-signed certificate.

<meta property="og:image" content="//cdn.example.com/uploads/images/webpage_300x200.png">

* @RichDeBourke mentioned this to me, but apparently WhatsApp has increased its maximum image size (dimensions as well as file size). I did some tests: it does not work consistently every time on every device. I tested 2.x Mb images and even that seemed to work 9/10 times. <300KB is the safest approach, but you should be fine using larger images as of 18-02-2020. I would recommend keeping the file size below 2MB, though. And definitely throw your image through TinyPNG or any other image compression algorithm if you haven't already.



If you completed the steps above, you can now see your preview in WhatsApp! However, be aware of the "please note" section above.



Step 7: og:type

In order for your object to be represented within the graph, you need to specify its type. Here's a list of the global types available: http://ogp.me/#types. You can also specify your own types.

<meta property="og:type" content="article" />

Step 8: og:locale

The locale of the resource. You can also use og:locale:alternate if you have other language translations available.

If you don't specify og:locale, it defaults to en_US.

<meta property="og:locale" content="en_GB" />
<meta property="og:locale:alternate" content="fr_FR" />
<meta property="og:locale:alternate" content="es_ES" />

Step 9: Twitter

For the best Twitter support read this.


Step 10: Facebook

For the best Facebook support read this.


Step 11: favicon

For the best favicon support for all browsers and devices read this.


Bonus step 12: video/audio

It's also possible to share audio/video. Facebook and twitter for example share videos very well. Read ogp.me.

HTML meta tag for content language

<meta name="language" content="Spanish">

This isn't defined in any specification (including the HTML5 draft)

<meta http-equiv="content-language" content="es">

This is a poor man's version of a real HTTP header and should really be expressed in the headers. For example:

Content-language: es
Content-type: text/html;charset=UTF-8

It says that the document is intended for Spanish language speakers (it doesn't, however mean the document is written in Spanish; it could, for example, be written in English as part of a language course for Spanish speakers).

From the spec:

The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Note that this might not be equivalent to all the languages used within the entity-body.

If you want to state that a document is written in Spanish then use:

<html lang="es">

<meta charset="utf-8"> vs <meta http-equiv="Content-Type">

To embed a signature on an email, I would use the long version:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

The reason is that not many email readers use html5, so it's always better use old html styles. Actually, it's better to use tables than divs + css as well.

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

I belive you need to add itemprop to the og:image meta tag, have the image size set to 256x256 and also it would not harm to add the site_name, type and updated_time properties either :)

<meta property="og:site_name" content="San Roque 2014 Pollos">
<meta property="og:title" content="San Roque 2014 Pollos" />
<meta property="og:description" content="Programa de fiestas" />
<meta property="og:image" itemprop="image" content="http://pollosweb.wesped.es/programa_pollos/play.png">
<meta property="og:type" content="website" />
<meta property="og:updated_time" content="1440432930" />

You can see these meta tags in action on for example Google Maps.
After you have changed your meta tags, you might need to wait a while for possible caches to update.

You can debug/verify Open Graph meta tags from the Facebook Debugger
If you can see all your tags there, then the sites/apps where your tags are not showing properly might have different requirements for Open Graph tags.

EDIT:
If you are going to specify an image by a HTTP-Secure link, you need to use og:image:secure_url instead of og:image.

EDIT2:
You also need to specify og:type as it is one of the four base required parameters.
<meta property="og:type" content="website" /> should get you in the right direction.

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

Disabling user-scalable (namely, the ability to double tap to zoom) allows the browser to reduce the click delay. In touch-enable browsers, when the user expects the double tap to zoom, the browser generally waits 300ms before firing the click event, waiting to see if the user will double tap. Disabling user-scalable allows for the Chrome browser to fire the click event immediately, allowing for a better user experience.

From Google IO 2013 session https://www.youtube.com/watch?feature=player_embedded&v=DujfpXOKUp8#t=1435s

Update: its not true anymore, <meta name="viewport" content="width=device-width"> is enough to remove 300ms delay

How do I get the information from a meta tag with JavaScript?

I personally prefer to just get them in one object hash, then I can access them anywhere. This could easily be set to an injectable variable and then everything could have it and it only grabbed once.

By wrapping the function this can also be done as a one liner.

var meta = (function () {
    var m = document.querySelectorAll("meta"), r = {};
    for (var i = 0; i < m.length; i += 1) {
        r[m[i].getAttribute("name")] = m[i].getAttribute("content")
    }
    return r;
})();

Is it possible to use jQuery to read meta tags

For select twitter meta name , you can add a data attribute.

example :

meta name="twitter:card" data-twitterCard="" content=""
$('[data-twitterCard]').attr('content');

Is it still valid to use IE=edge,chrome=1?

<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>

worked for me, to force IE to "snap out of compatibility mode" (so to speak), BUT that meta statement must appear IMMEDIATELY after the <head>, or it won't work!

Force to open "Save As..." popup open at text link click for PDF in HTML

Just put the below code in your .htaccess file:

AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf

Or you can also do trick by JavaScript

element.setAttribute( 'download', whatever_string_you_want);

How to add meta tag in JavaScript

Like this ?

<script>
var meta = document.createElement('meta');
meta.setAttribute('http-equiv', 'X-UA-Compatible');
meta.setAttribute('content', 'IE=Edge');
document.getElementsByTagName('head')[0].appendChild(meta);
</script>

How to start automatic download of a file in Internet Explorer?

SourceForge uses an <iframe> element with the src="" attribute pointing to the file to download.

<iframe width="1" height="1" frameborder="0" src="[File location]"></iframe>

(Side effect: no redirect, no JavaScript, original URL remains unchanged.)

Why aren't python nested functions called closures?

I'd like to offer another simple comparison between python and JS example, if this helps make things clearer.

JS:

function make () {
  var cl = 1;
  function gett () {
    console.log(cl);
  }
  function sett (val) {
    cl = val;
  }
  return [gett, sett]
}

and executing:

a = make(); g = a[0]; s = a[1];
s(2); g(); // 2
s(3); g(); // 3

Python:

def make (): 
  cl = 1
  def gett ():
    print(cl);
  def sett (val):
    cl = val
  return gett, sett

and executing:

g, s = make()
g() #1
s(2); g() #1
s(3); g() #1

Reason: As many others said above, in python, if there is an assignment in the inner scope to a variable with the same name, a new reference in the inner scope is created. Not so with JS, unless you explicitly declare one with the var keyword.

Sending HTTP POST with System.Net.WebClient

WebClient doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:

Using client as new WebClient
    result = client.UploadString(someurl, "param1=somevalue&param2=othervalue")
End Using

Find the number of columns in a table

Can get using following sql statement:

select count(*) Noofcolumns from SYSCOLUMNS where id=(select id from SYSOBJECTS where name='table_name')

What is the use of adding a null key or value to a HashMap in Java?

Another example : I use it to group Data by date. But some data don't have date. I can group it with the header "NoDate"

SQL Server find and replace specific word in all rows of specific column

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'

or simply this if you are sure that you have no values like this CKIT002

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')

How do I skip an iteration of a `foreach` loop?

Another approach using linq is:

foreach ( int number in numbers.Skip(1))
{   
    // process number  
}

If you want to skip the first in a number of items.

Or use .SkipWhere if you want to specify a condition for skipping.

How to manually set REFERER header in Javascript?

You can change the value of the referrer in the HTTP header using the Web Request API.

It requires a background js script for it's use. You can use the onBeforeSendHeaders as it modifies the header before the request is sent.

Your code will be something like this :

    chrome.webRequest.onBeforeSendHeaders.addEventListener(function(details){
    var newRef = "http://new-referer/path";
    var hasRef = false;
    for(var n in details.requestHeaders){
        hasRef = details.requestHeaders[n].name == "Referer";
        if(hasRef){
            details.requestHeaders[n].value = newRef;
         break;
        }
    }
    if(!hasRef){
        details.requestHeaders.push({name:"Referer",value:newRef});
    }
    return {requestHeaders:details.requestHeaders};
},
{
    urls:["http://target/*"]
},
[
    "requestHeaders",
    "blocking"
]);

urls : It acts as a request filter, and invokes the listener only for certain requests.

For more info: https://developer.chrome.com/extensions/webRequest

change image opacity using javascript

Supposing you're using plain JS (see other answers for jQuery), to change an element's opacity, write:

var element = document.getElementById('id');
element.style.opacity = "0.9";
element.style.filter  = 'alpha(opacity=90)'; // IE fallback

'too many values to unpack', iterating over a dict. key=>string, value=>list

For Python 3.x iteritems has been removed. Use items instead.

for field, possible_values in fields.items():
    print(field, possible_values)

Getters \ setters for dummies

Getters and setters really only make sense when you have private properties of classes. Since Javascript doesn't really have private class properties as you would normally think of from Object Oriented Languages, it can be hard to understand. Here is one example of a private counter object. The nice thing about this object is that the internal variable "count" cannot be accessed from outside the object.

var counter = function() {
    var count = 0;

    this.inc = function() {
        count++;
    };

    this.getCount = function() {
        return count;
    };
};

var i = new Counter();
i.inc();
i.inc();
// writes "2" to the document
document.write( i.getCount());

If you are still confused, take a look at Crockford's article on Private Members in Javascript.

How to rename uploaded file before saving it into a directory?

You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file.

Instead of

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);

Use

$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

Changed to reflect your question, will product a random number based on the current time and append the extension from the originally uploaded file.

How I can print to stderr in C?

Some examples of formatted output to stdout and stderr:

printf("%s", "Hello world\n");              // "Hello world" on stdout (using printf)
fprintf(stdout, "%s", "Hello world\n");     // "Hello world" on stdout (using fprintf)
fprintf(stderr, "%s", "Stack overflow!\n"); // Error message on stderr (using fprintf)

Output an Image in PHP

Try this:

<?php
  header("Content-type: image/jpeg");
  readfile("/path/to/image.jpg");
  exit(0);
?>

Image is not showing in browser?

You need to import your image from the image folder. import name_of_image from '../imageFolder/name_of_image.jpg';

<img src={name_of_image} alt=''>

Please refer here. https://create-react-app.dev/docs/adding-images-fonts-and-files -

Downloading folders from aws s3, cp or sync?

In case you need to use another profile, especially cross account. you need to add the profile in the config file

[profile profileName]
region = us-east-1
role_arn = arn:aws:iam::XXX:role/XXXX
source_profile = default

and then if you are accessing only a single file

aws s3 cp s3://crossAccountBucket/dir localdir --profile profileName

Android Studio - Failed to apply plugin [id 'com.android.application']

In my case delete your gradle file and then again import your file again it will work

Opposite of %in%: exclude rows with values specified in a vector

Instead of creating your own function, it would be useful to just negate the behavior of

needle %in% haystack 

do this instead:

!(needle %in% haystack)

this works as well.

Python class returning value

the worked proposition for me is __call__ on class who create list of little numbers:

import itertools
    
class SmallNumbers:
    def __init__(self, how_much):
        self.how_much = int(how_much)
        self.work_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        self.generated_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        start = 10
        end = 100
        for cmb in range(2, len(str(self.how_much)) + 1):
            self.ListOfCombinations(is_upper_then=start, is_under_then=end, combinations=cmb)
            start *= 10
            end *= 10

    def __call__(self, number, *args, **kwargs):
        return self.generated_list[number]

    def ListOfCombinations(self, is_upper_then, is_under_then, combinations):
        multi_work_list = eval(str('self.work_list,') * combinations)
        nbr = 0
        for subset in itertools.product(*multi_work_list):
            if is_upper_then <= nbr < is_under_then:
                self.generated_list.append(''.join(subset))
                if self.how_much == nbr:
                    break
            nbr += 1

and to run it:

if __name__ == '__main__':
        sm = SmallNumbers(56)
        print(sm.generated_list)
        print(sm.generated_list[34], sm.generated_list[27], sm.generated_list[10])
        print('The Best', sm(15), sm(55), sm(49), sm(0))

result

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56']
34 27 10
The Best 15 55 49 0

Number of regex matches

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

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

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

Countdown timer in React

The problem is in your "this" value. Timer function cannot access the "state" prop because run in a different context. I suggest you to do something like this:

...
startTimer = () => {
  let interval = setInterval(this.timer.bind(this), 1000);
  this.setState({ interval });
};

As you can see I've added a "bind" method to your timer function. This allows the timer, when called, to access the same "this" of your react component (This is the primary problem/improvement when working with javascript in general).

Another option is to use another arrow function:

startTimer = () => {
  let interval = setInterval(() => this.timer(), 1000);
  this.setState({ interval });
};

mysql stored-procedure: out parameter

try changing OUT to INOUT for your out_number parameter definition.

CREATE PROCEDURE my_sqrt(input_number INT, INOUT out_number FLOAT)

INOUT means that the input variable for out_number (@out_value in your case.) will also serve as the output variable from which you can select the value from.

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

Seriously, the top answer is not working for me. tried cxf.version 2.4.1 and 3.0.10. and generate absolute path with wsdlLocation every times.

My solution is to use the wsdl2java command in the apache-cxf-3.0.10\bin\ with -wsdlLocation classpath:wsdl/QueryService.wsdl.

Detail:

    wsdl2java -encoding utf-8 -p com.jeiao.boss.testQueryService -impl -wsdlLocation classpath:wsdl/testQueryService.wsdl http://127.0.0.1:9999/platf/testQueryService?wsdl

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Swift 5.1:

let storyboard = UIStoryboard.init(name: "Main", bundle: Bundle.main)
let mainViewController = storyboard.instantiateViewController(withIdentifier: "ID")
let appDeleg = UIApplication.shared.delegate as! AppDelegate
let root = appDeleg.window?.rootViewController as! UINavigationController
root.pushViewController(mainViewController, animated: true)

Fastest way of finding differences between two files in unix?

You could try..

comm -13 <(sort file1) <(sort file2) > file3

or

grep -Fxvf file1 file2 > file3

or

diff file1 file2 | grep "<" | sed 's/^<//g'  > file3

or

join -v 2 <(sort file1) <(sort file2) > file3

No log4j2 configuration file found. Using default configuration: logging only errors to the console

I am working on TestNG Maven project, This worked for me by adding <resources> tag in pom.xml, this happens to be the path of my custom configuration file log4j2.xml.

<url>http://maven.apache.org</url>
<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<build>
  <resources>
    <resource>
      <directory>src/main/java/resources</directory>
      <filtering>true</filtering>
    </resource>
  </resources>
  <pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M3</version>
        <configuration>
          <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>
          </suiteXmlFiles>
        </configuration>
      </plugin>
    </plugins>
  </pluginManagement>
</build>
<dependencies>
  <dependency>

Java - ignore exception and continue

It's generally considered a bad idea to ignore exceptions. Usually, if it's appropriate, you want to either notify the user of the issue (if they would care) or at the very least, log the exception, or print the stack trace to the console.

However, if that's truly not necessary (you're the one making the decision) then no, there's no other way to ignore an exception that forces you to catch it. The only revision, in that case, that I would suggest is explicitly listing the the class of the Exceptions you're ignoring, and some comment as to why you're ignoring them, rather than simply ignoring any exception, as you've done in your example.

How do I skip a header from CSV files in Spark?

Working in 2018 (Spark 2.3)

Python

df = spark.read
    .option("header", "true")
    .format("csv")
    .schema(myManualSchema)
    .load("mycsv.csv")

Scala

val myDf = spark.read
  .option("header", "true")
  .format("csv")
  .schema(myManualSchema)
  .load("mycsv.csv")

PD1: myManualSchema is a predefined schema written by me, you could skip that part of code

UPDATE 2021 The same code works for Spark 3.x

df = spark.read
    .option("header", "true")
    .option("inferSchema", "true")
    .format("csv")
    .csv("mycsv.csv")

QR Code encoding and decoding using zxing

this is my working example Java code to encode QR code using ZXing with UTF-8 encoding, please note: you will need to change the path and utf8 data to your path and language characters

package com.mypackage.qr;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Hashtable;

import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.*;

public class CreateQR {

public static void main(String[] args)
{
    Charset charset = Charset.forName("UTF-8");
    CharsetEncoder encoder = charset.newEncoder();
    byte[] b = null;
    try {
        // Convert a string to UTF-8 bytes in a ByteBuffer
        ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("utf 8 characters - i used hebrew, but you should write some of your own language characters"));
        b = bbuf.array();
    } catch (CharacterCodingException e) {
        System.out.println(e.getMessage());
    }

    String data;
    try {
        data = new String(b, "UTF-8");
        // get a byte matrix for the data
        BitMatrix matrix = null;
        int h = 100;
        int w = 100;
        com.google.zxing.Writer writer = new MultiFormatWriter();
        try {
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(2);
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            matrix = writer.encode(data,
            com.google.zxing.BarcodeFormat.QR_CODE, w, h, hints);
        } catch (com.google.zxing.WriterException e) {
            System.out.println(e.getMessage());
        }

        // change this path to match yours (this is my mac home folder, you can use: c:\\qr_png.png if you are on windows)
                String filePath = "/Users/shaybc/Desktop/OutlookQR/qr_png.png";
        File file = new File(filePath);
        try {
            MatrixToImageWriter.writeToFile(matrix, "PNG", file);
            System.out.println("printing to " + file.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    } catch (UnsupportedEncodingException e) {
        System.out.println(e.getMessage());
    }
}

}

How to check if field is null or empty in MySQL?

If you would like to check in PHP , then you should do something like :

$query_s =mysql_query("SELECT YOURROWNAME from `YOURTABLENAME` where name = $name");
$ertom=mysql_fetch_array($query_s);
if ('' !== $ertom['YOURROWNAME']) {
  //do your action
  echo "It was filled";
} else { 
  echo "it was empty!";
}

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

Here is the perfect method:

Please note that Environment.NewLine works on on Microsoft platforms.

In addition to the above, you need to add \r and \n in a separate function!

Here is the code which will support whether you type on Linux, Windows, or Mac:

var stringTest = "\r Test\nThe Quick\r\n brown fox";

Console.WriteLine("Original is:");
Console.WriteLine(stringTest);
Console.WriteLine("-------------");

stringTest = stringTest.Trim().Replace("\r", string.Empty);
stringTest = stringTest.Trim().Replace("\n", string.Empty);
stringTest = stringTest.Replace(Environment.NewLine, string.Empty);

Console.WriteLine("Output is : ");
Console.WriteLine(stringTest);
Console.ReadLine();

Div Height in Percentage

It doesn't take the 50% of the whole page is because the "whole page" is only how tall your contents are. Change the enclosing html and body to 100% height and it will work.

html, body{
    height: 100%;
}
div{
    height: 50%;
}

http://jsfiddle.net/DerekL/5YukJ/1/

enter image description here

^ Your document is only 20px high. 50% of 20px is 10px, and it is not what you expected.

enter image description here

^ Now if you change the height of the document to the height of the whole page (150px), 50% of 150px is 75px, then it will work.

How to implement OnFragmentInteractionListener

I'd like to add the destruction of the listener when the fragment is detached from the activity or destroyed.

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

and when using the new onStart() method with Context

@Override
public void onDestroy() {
    super.onDestroy();
    mListener = null;
}

Are there benefits of passing by pointer over passing by reference in C++?

A pointer can receive a NULL parameter, a reference parameter can not. If there's ever a chance that you could want to pass "no object", then use a pointer instead of a reference.

Also, passing by pointer allows you to explicitly see at the call site whether the object is passed by value or by reference:

// Is mySprite passed by value or by reference?  You can't tell 
// without looking at the definition of func()
func(mySprite);

// func2 passes "by pointer" - no need to look up function definition
func2(&mySprite);

How do you receive a url parameter with a spring controller mapping

You should be using @RequestParam instead of @ModelAttribute, e.g.

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 @RequestParam String someAttr) {
}

You can even omit @RequestParam altogether if you choose, and Spring will assume that's what it is:

@RequestMapping("/{someID}")
public @ResponseBody int getAttr(@PathVariable(value="someID") String id, 
                                 String someAttr) {
}

What does '&' do in a C++ declaration?

The "&" denotes a reference instead of a pointer to an object (In your case a constant reference).

The advantage of having a function such as

foo(string const& myname) 

over

foo(string const* myname)

is that in the former case you are guaranteed that myname is non-null, since C++ does not allow NULL references. Since you are passing by reference, the object is not copied, just like if you were passing a pointer.

Your second example:

const string &GetMethodName() { ... }

Would allow you to return a constant reference to, for example, a member variable. This is useful if you do not wish a copy to be returned, and again be guaranteed that the value returned is non-null. As an example, the following allows you direct, read-only access:

class A
{
  public:
  int bar() const {return someValue;}
  //Big, expensive to copy class
}

class B
{
public:
 A const& getA() { return mA;}
private:
 A mA;
}
void someFunction()
{
 B b = B();
 //Access A, ability to call const functions on A
 //No need to check for null, since reference is guaranteed to be valid.
 int value = b.getA().bar(); 
}

You have to of course be careful to not return invalid references. Compilers will happily compile the following (depending on your warning level and how you treat warnings)

int const& foo() 
{
 int a;

 //This is very bad, returning reference to something on the stack. This will
 //crash at runtime.
 return a; 
}

Basically, it is your responsibility to ensure that whatever you are returning a reference to is actually valid.

Reading Space separated input in python

For python 3 use this

inp = list(map(int,input().split()))
#input => java is a programming language
#return as => ("java","is","a","programming","language")

input() accepts a string from STDIN.

split() splits the string about whitespace character and returns a list of strings.

map() passes each element of the 2nd argument to the first argument and returns a map object

Finally list() converts the map to a list

How to change bower's default components folder?

In addition to editing .bowerrc to setup your default install path, you can also setup custom install paths for different file types.

There is a node package called bower-installer that provides a single command for managing alternate install paths.

run npm install -g bower-installer

Set up your bower.json

{
  "name" : "test",
  "version": "0.1",
  "dependencies" : {
    "jquery-ui" : "latest"
  },
  "install" : {
    "path" : {
      "css": "src/css",
      "js": "src/js"
    },
    "sources" : {
      "jquery-ui" : [
        "components/jquery-ui/ui/jquery-ui.custom.js",
        "components/jquery-ui/themes/start/jquery-ui.css"
      ]
    }
  }
}

Run the following command: bower-installer

This will install components/jquery-ui/themes/start/jquery-ui.css to ./src/css, etc

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

Missed to configure tag in manifest file

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Python name 'os' is not defined

The problem is that you forgot to import os. Add this line of code:

import os

And everything should be fine. Hope this helps!

Change a Git remote HEAD to point to something besides master

First, create the new branch you would like to set as your default, for example:

$>git branch main

Next, push that branch to the origin:

$>git push origin main

Now when you login to your GitHub account, you can go to your repository and choose Settings>Default Branch and choose "main."

Then, if you so choose, you can delete the master branch:

$>git push origin :master

Passing an array as a function parameter in JavaScript

Note this

function FollowMouse() {
    for(var i=0; i< arguments.length; i++) {
        arguments[i].style.top = event.clientY+"px";
        arguments[i].style.left = event.clientX+"px";
    }

};

//---------------------------

html page

<body onmousemove="FollowMouse(d1,d2,d3)">

<p><div id="d1" style="position: absolute;">Follow1</div></p>
<div id="d2" style="position: absolute;"><p>Follow2</p></div>
<div id="d3" style="position: absolute;"><p>Follow3</p></div>


</body>

can call function with any Args

<body onmousemove="FollowMouse(d1,d2)">

or

<body onmousemove="FollowMouse(d1)">

Get list from pandas dataframe column or row?

Assuming the name of the dataframe after reading the excel sheet is df, take an empty list (e.g. dataList), iterate through the dataframe row by row and append to your empty list like-

dataList = [] #empty list
for index, row in df.iterrows(): 
    mylist = [row.cluster, row.load_date, row.budget, row.actual, row.fixed_price]
    dataList.append(mylist)

Or,

dataList = [] #empty list
for row in df.itertuples(): 
    mylist = [row.cluster, row.load_date, row.budget, row.actual, row.fixed_price]
    dataList.append(mylist)

No, if you print the dataList, you will get each rows as a list in the dataList.

How to create a fixed-size array of objects

Declare an empty SKSpriteNode, so there won't be needing for unwraping

var sprites = [SKSpriteNode](count: 64, repeatedValue: SKSpriteNode())

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

This will validate against special characters and leading and trailing spaces:

var strString = "Your String";

strString.match(/^[A-Za-z0-9][A-Za-z0-9 ]\*[A-Za-z0-9]\*$/)

How to solve java.lang.OutOfMemoryError trouble in Android

android:largeHeap="true" didn't fix the error

In my case, I got this error after I added an icon/image to Drawable folder by converting SVG to vector. Simply, go to the icon xml file and set small numbers for the width and height

android:width="24dp"
android:height="24dp"
android:viewportWidth="3033"
android:viewportHeight="3033"

How to populate/instantiate a C# array with a single value?

Here is another appraoch with System.Collections.BitArray which has such a constructor.

bool[] result = new BitArray(1000000, true).Cast<bool>().ToArray();

or

bool[] result = new bool[1000000];
new BitArray(1000000, true).CopyTo(result, 0);

How to find the process id of a running Java process on Windows? And how to kill the process alone?

In windows XP and later, there's a command: tasklist that lists all process id's.

For killing a process in Windows, see:

Really killing a process in Windows | Stack Overflow

You can execute OS-commands in Java by:

Runtime.getRuntime().exec("your command here");

If you need to handle the output of a command, see example: using Runtime.exec() in Java

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

The iOS 8.0 simulator runtime has a bug whereby if your network configuration changes while the simulated device is booted, higher level APIs (eg: CFNetwork) in the simulated runtime will think that it has lost network connectivity. Currently, the advised workaround is to simply reboot the simulated device when your network configuration changes.

If you are impacted by this issue, please file additional duplicate radars at http://bugreport.apple.com to get it increased priority.

If you see this issue without having changed network configurations, then that is not a known bug, and you should definitely file a radar, indicating that the issue is not the known network-configuration-changed bug.

JQuery Ajax - How to Detect Network Connection error when making Ajax call

// start snippet
error: function(XMLHttpRequest, textStatus, errorThrown) {
        if (XMLHttpRequest.readyState == 4) {
            // HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
        }
        else if (XMLHttpRequest.readyState == 0) {
            // Network error (i.e. connection refused, access denied due to CORS, etc.)
        }
        else {
            // something weird is happening
        }
    }
//end snippet

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

It works for me.

git remote add origin https://github.com/repo.git
git push origin master

add the repository URL to the origin in the local working directory

How can I append a string to an existing field in MySQL?

Update image field to add full URL, ignoring null fields:

UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;

How to redirect to the same page in PHP

To really be universal, I'm using this:

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' 
    || $_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://';
header('Location: '.$protocol.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit;

I like $_SERVER['REQUEST_URI'] because it respects mod_rewrite and/or any GET variables.

https detection from https://stackoverflow.com/a/2886224/947370

Break string into list of characters in Python

I'm a bit late it seems to be, but...

a='hello'
print list(a)
# ['h','e','l','l', 'o']

string sanitizer for filename

These may be a bit heavy, but they're flexible enough to sanitize whatever string into a "safe" en style filename or folder name (or heck, even scrubbed slugs and things if you bend it).

1) Building a full filename (with fallback name in case input is totally truncated):

str_file($raw_string, $word_separator, $file_extension, $fallback_name, $length);

2) Or using just the filter util without building a full filename (strict mode true will not allow [] or () in filename):

str_file_filter($string, $separator, $strict, $length);

3) And here are those functions:

// Returns filesystem-safe string after cleaning, filtering, and trimming input
function str_file_filter(
    $str,
    $sep = '_',
    $strict = false,
    $trim = 248) {

    $str = strip_tags(htmlspecialchars_decode(strtolower($str))); // lowercase -> decode -> strip tags
    $str = str_replace("%20", ' ', $str); // convert rogue %20s into spaces
    $str = preg_replace("/%[a-z0-9]{1,2}/i", '', $str); // remove hexy things
    $str = str_replace("&nbsp;", ' ', $str); // convert all nbsp into space
    $str = preg_replace("/&#?[a-z0-9]{2,8};/i", '', $str); // remove the other non-tag things
    $str = preg_replace("/\s+/", $sep, $str); // filter multiple spaces
    $str = preg_replace("/\.+/", '.', $str); // filter multiple periods
    $str = preg_replace("/^\.+/", '', $str); // trim leading period

    if ($strict) {
        $str = preg_replace("/([^\w\d\\" . $sep . ".])/", '', $str); // only allow words and digits
    } else {
        $str = preg_replace("/([^\w\d\\" . $sep . "\[\]\(\).])/", '', $str); // allow words, digits, [], and ()
    }

    $str = preg_replace("/\\" . $sep . "+/", $sep, $str); // filter multiple separators
    $str = substr($str, 0, $trim); // trim filename to desired length, note 255 char limit on windows

    return $str;
}


// Returns full file name including fallback and extension
function str_file(
    $str,
    $sep = '_',
    $ext = '',
    $default = '',
    $trim = 248) {

    // Run $str and/or $ext through filters to clean up strings
    $str = str_file_filter($str, $sep);
    $ext = '.' . str_file_filter($ext, '', true);

    // Default file name in case all chars are trimmed from $str, then ensure there is an id at tail
    if (empty($str) && empty($default)) {
        $str = 'no_name__' . date('Y-m-d_H-m_A') . '__' . uniqid();
    } elseif (empty($str)) {
        $str = $default;
    }

    // Return completed string
    if (!empty($ext)) {
        return $str . $ext;
    } else {
        return $str;
    }
}

So let's say some user input is: .....&lt;div&gt;&lt;/div&gt;<script></script>&amp; Weiß Göbel ?????File name %20 %20 %21 %2C Décor \/. /. . z \... y \...... x ./ “This name” is & 462^^ not &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = that grrrreat -][09]()1234747) ???????-??-????????????

And we wanna convert it to something friendlier to make a tar.gz with a file name length of 255 chars. Here is an example use. Note: this example includes a malformed tar.gz extension as a proof of concept, you should still filter the ext after string is built against your whitelist(s).

$raw_str = '.....&lt;div&gt;&lt;/div&gt;<script></script>&amp; Weiß Göbel ?????File name  %20   %20 %21 %2C Décor  \/.  /. .  z \... y \...... x ./  “This name” is & 462^^ not &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; = that grrrreat -][09]()1234747) ???????-??-????????????';
$fallback_str = 'generated_' . date('Y-m-d_H-m_A');
$bad_extension = '....t&+++a()r.gz[]';

echo str_file($raw_str, '_', $bad_extension, $fallback_str);

The output would be: _wei_gbel_file_name_dcor_._._._z_._y_._x_._this_name_is_462_not_that_grrrreat_][09]()1234747)_.tar.gz

You can play with it here: https://3v4l.org/iSgi8

Or a Gist: https://gist.github.com/dhaupin/b109d3a8464239b7754a

EDIT: updated script filter for &nbsp; instead of space, updated 3v4l link

Add numpy array as column to Pandas data frame

Here is other example:

import numpy as np
import pandas as pd

""" This just creates a list of touples, and each element of the touple is an array"""
a = [ (np.random.randint(1,10,10), np.array([0,1,2,3,4,5,6,7,8,9]))  for i in 
range(0,10) ]

""" Panda DataFrame will allocate each of the arrays , contained as a touple 
element , as column"""
df = pd.DataFrame(data =a,columns=['random_num','sequential_num'])

The secret in general is to allocate the data in the form a = [ (array_11, array_12,...,array_1n),...,(array_m1,array_m2,...,array_mn) ] and panda DataFrame will order the data in n columns of arrays. Of course , arrays of arrays could be used instead of touples, in that case the form would be : a = [ [array_11, array_12,...,array_1n],...,[array_m1,array_m2,...,array_mn] ]

This is the output if you print(df) from the code above:

                       random_num                  sequential_num
0  [7, 9, 2, 2, 5, 3, 5, 3, 1, 4]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1  [8, 7, 9, 8, 1, 2, 2, 6, 6, 3]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2  [3, 4, 1, 2, 2, 1, 4, 2, 6, 1]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3  [3, 1, 1, 1, 6, 2, 8, 6, 7, 9]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4  [4, 2, 8, 5, 4, 1, 2, 2, 3, 3]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5  [3, 2, 7, 4, 1, 5, 1, 4, 6, 3]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6  [5, 7, 3, 9, 7, 8, 4, 1, 3, 1]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
7  [7, 4, 7, 6, 2, 6, 3, 2, 5, 6]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8  [3, 1, 6, 3, 2, 1, 5, 2, 2, 9]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9  [7, 2, 3, 9, 5, 5, 8, 6, 9, 8]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Other variation of the example above:

b = [ (i,"text",[14, 5,], np.array([0,1,2,3,4,5,6,7,8,9]))  for i in 
range(0,10) ]
df = pd.DataFrame(data=b,columns=['Number','Text','2Elemnt_array','10Element_array'])

Output of df:

   Number  Text 2Elemnt_array                 10Element_array
0       0  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1       1  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2       2  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3       3  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4       4  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5       5  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6       6  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
7       7  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8       8  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9       9  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If you want to add other columns of arrays, then:

df['3Element_array']=[([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3])]

The final output of df will be:

   Number  Text 2Elemnt_array                 10Element_array 3Element_array
0       0  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
1       1  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
2       2  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
3       3  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
4       4  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
5       5  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
6       6  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
7       7  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
8       8  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
9       9  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]

Static way to get 'Context' in Android?

If you don't want to modify the manifest file, you can manually store the context in a static variable in your initial activity:

public class App {
    private static Context context;

    public static void setContext(Context cntxt) {
        context = cntxt;
    }

    public static Context getContext() {
        return context;
    }
}

And just set the context when your activity (or activities) start:

// MainActivity

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

    // Set Context
    App.setContext(getApplicationContext());

    // Other stuff
}

Note: Like all other answers, this is a potential memory leak.

Compare if BigDecimal is greater than zero

using ".intValue()" on BigDecimal object is not right when you want to check if its grater than zero. The only option left is ".compareTo()" method.

Shortest distance between a point and a line segment

Here is the simplest complete code in Javascript.

x, y is your target point and x1, y1 to x2, y2 is your line segment.

UPDATED: fix for 0 length line problem from comments.

function pDistance(x, y, x1, y1, x2, y2) {

  var A = x - x1;
  var B = y - y1;
  var C = x2 - x1;
  var D = y2 - y1;

  var dot = A * C + B * D;
  var len_sq = C * C + D * D;
  var param = -1;
  if (len_sq != 0) //in case of 0 length line
      param = dot / len_sq;

  var xx, yy;

  if (param < 0) {
    xx = x1;
    yy = y1;
  }
  else if (param > 1) {
    xx = x2;
    yy = y2;
  }
  else {
    xx = x1 + param * C;
    yy = y1 + param * D;
  }

  var dx = x - xx;
  var dy = y - yy;
  return Math.sqrt(dx * dx + dy * dy);
}

Image to help visualize the solution

Parsing boolean values with argparse

I think a more canonical way to do this is via:

command --feature

and

command --no-feature

argparse supports this version nicely:

parser.add_argument('--feature', dest='feature', action='store_true')
parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)

Of course, if you really want the --arg <True|False> version, you could pass ast.literal_eval as the "type", or a user defined function ...

def t_or_f(arg):
    ua = str(arg).upper()
    if 'TRUE'.startswith(ua):
       return True
    elif 'FALSE'.startswith(ua):
       return False
    else:
       pass  #error condition maybe?

How do I search for files in Visual Studio Code?

For windows. if Ctrl+p doesn't always work use Ctrl+shift+n instead.

PHP regular expression - filter number only

Using is_numeric or intval is likely the best way to validate a number here, but to answer your question you could try using preg_replace instead. This example removes all non-numeric characters:

$output = preg_replace( '/[^0-9]/', '', $string );

How do I delete from multiple tables using INNER JOIN in SQL server

$sql="DELETE FROM basic_tbl,education_tbl, personal_tbl ,address_tbl,department_tbl USING basic_tbl,education_tbl, personal_tbl ,address_tbl,department_tbl WHERE b_id=e_id=p_id=a_id=d_id='".$id."' "; $rs=mysqli_query($con,$sql);

Using the "start" command with parameters passed to the started program

If you must use double quotation mark at any parameter, you can get error "'c:\somepath' is not recognized a an internal or external command, operable program or batch file". I suggest below solution when using double qoutation mark: https://stackoverflow.com/a/43467194/3835640

"inconsistent use of tabs and spaces in indentation"

If your editor doesn't recognize tabs when doing a search and replace (like SciTE), you can paste the code into Word and search using Ctr-H and ^t which finds the tabs which then can be replace with 4 spaces.

Why use HttpClient for Synchronous Connection

but what i am doing is purely synchronous

You could use HttpClient for synchronous requests just fine:

using (var client = new HttpClient())
{
    var response = client.GetAsync("http://google.com").Result;

    if (response.IsSuccessStatusCode)
    {
        var responseContent = response.Content; 

        // by calling .Result you are synchronously reading the result
        string responseString = responseContent.ReadAsStringAsync().Result;

        Console.WriteLine(responseString);
    }
}

As far as why you should use HttpClient over WebRequest is concerned, well, HttpClient is the new kid on the block and could contain improvements over the old client.

How to convert Moment.js date to users local timezone?

Here's what I did:

var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();

Where {{ time }} is the utc timestamp.

using facebook sdk in Android studio

NOTE

For Android Studio 0.5.5 and later, and with later versions of the Facebook SDK, this process is much simpler than what is documented below (which was written for earlier versions of both). If you're running the latest, all you need to do is this:

  1. Download the Facebook SDK from https://developers.facebook.com/docs/android/
  2. Unzip the archive
  3. In Android Studio 0.5.5 or later, choose "Import Module" from the File menu.
  4. In the wizard, set the source path of the module to import as the "facebook" directory inside the unpacked archive. (Note: If you choose the entire parent folder, it will bring in not only the library itself, but also all of the sample apps, each as a separate module. This may work but probably isn't what you want).
  5. Open project structure by Ctrl + Shift + Alt + S and then select dependencies tab. Click on + button and select Module Dependency. In the new window pop up select :facebook.
  6. You should be good to go.

Instructions for older Android Studio and older Facebook SDK

This applies to Android Studio 0.5.4 and earlier, and makes the most sense for versions of the Facebook SDK before Facebook offered Gradle build files for the distribution. I don't know in which version of the SDK they made that change.

Facebook's instructions under "Import the SDK into an Android Studio Project" on their https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android-using-android-studio/3.0/ page are wrong for Gradle-based projects (i.e. your project was built using Android Studio's New Project wizard and/or has a build.gradle file for your application module). Follow these instructions instead:

  1. Create a libraries folder underneath your project's main directory. For example, if your project is HelloWorldProject, you would create a HelloWorldProject/libraries folder.

  2. Now copy the entire facebook directory from the SDK installation into the libraries folder you just created.

  3. Delete the libs folder in the facebook directory. If you like, delete the project.properties, build.xml, .classpath, and .project. files as well. You don't need them.

  4. Create a build.gradle file in the facebook directory with the following contents:

    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:0.6.+'
        }
    }
    
    apply plugin: 'android-library'
    
    dependencies {
        compile 'com.android.support:support-v4:+'
    }
    
    android {
        compileSdkVersion 17
        buildToolsVersion "19.0.0"
    
        defaultConfig {
            minSdkVersion 7
            targetSdkVersion 16
        }
    
        sourceSets {
            main {
                manifest.srcFile 'AndroidManifest.xml'
                java.srcDirs = ['src']
                resources.srcDirs = ['src']
                res.srcDirs = ['res']
            }
        }
    }
    

    Note that depending on when you're following these instructions compared to when this is written, you may need to adjust the classpath 'com.android.tools.build:gradle:0.6.+' line to reference a newer version of the Gradle plugin. Soon we will require version 0.7 or later. Try it out, and if you get an error that a newer version of the Gradle plugin is required, that's the line you have to edit.

  5. Make sure the Android Support Library in your SDK manager is installed.

  6. Edit your settings.gradle file in your application’s main directory and add this line:

    include ':libraries:facebook'
    
  7. If your project is already open in Android Studio, click the "Sync Project with Gradle Files" button in the toolbar. Once it's done, the facebook module should appear. enter image description here

  8. Open the Project Structure dialog. Choose Modules from the left-hand list, click on your application’s module, click on the Dependencies tab, and click on the + button to add a new dependency. enter image description here
  9. Choose “Module dependency”. It will bring up a dialog with a list of modules to choose from; select “:libraries:facebook”. enter image description here
  10. Click OK on all the dialogs. Android Studio will automatically resynchronize your project (making it unnecessary to click that "Sync Project with Gradle Files" button again) and pick up the new dependency. You should be good to go.

Use string in switch case in java

Java (before version 7) does not support String in switch/case. But you can achieve the desired result by using an enum.

private enum Fruit {
    apple, carrot, mango, orange;
}

String value; // assume input
Fruit fruit = Fruit.valueOf(value); // surround with try/catch

switch(fruit) {
    case apple:
        method1;
        break;
    case carrot:
        method2;
        break;
    // etc...
}

How to create .ipa file using Xcode?

In Xcode-11.2.1

You might be see different pattern for uploading IPA
Steps:-

i) Add your apple developer id in xcode preference -> account

ii)Clean Build Folder :-

enter image description here

iii) Archive

enter image description here

iv) Tap on Distribute App

enter image description here

v) Choose Ad-hoc to distribute on designated device

enter image description here

6)Tricky part -> User can download app from company's website URL. Many of us might get stuck and start creating website url to upload ipa, which is not required. Simply write google website url with https. :)

enter image description here

enter image description here

7)Click on export and you get ipa.

enter image description here

8)Visit https://www.diawi.com/ & drag and drop ipa you have downloaded. & share the link to your client/user who want to test :)

How to count down in for loop?

First I recommand you can try use print and observe the action:

for i in range(0, 5, 1):
    print i

the result:

0
1
2
3
4

You can understand the function principle. In fact, range scan range is from 0 to 5-1. It equals 0 <= i < 5

When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.

You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.

for i in range(5, 0, -1):
    print i

the result:

5
4
3
2
1

Thus it can be seen, it equals 5 >= i > 0

You want to implement your java code in python:

for (int index = last-1; index >= posn; index--)

It should code this:

for i in range(last-1, posn-1, -1)

Running Node.js in apache?

Although there are a lot of good tips here I'd like to answer the question you asked:

So in other words can they work hand in hand just like Apache/Perl or Apache/PHP etc..

YES, you can run Node.js on Apache along side Perl and PHP IF you run it as a CGI module. As of yet, I am unable to find a mod-node for Apache but check out: CGI-Node for Apache here http://www.cgi-node.org/ .

The interesting part about cgi-node is that it uses JavaScript exactly like you would use PHP to generate dynamic content, service up static pages, access SQL database etc. You can even share core JavaScript libraries between the server and the client/browser.

I think the shift to a single language between client and server is happening and JavaScript seems to be a good candidate.

A quick example from cgi-node.org site:

<? include('myJavaScriptFile.js'); ?>
<html>
   <body>
      <? var helloWorld = 'Hello World!'; ?>
      <b><?= helloWorld ?><br/>
      <? for( var index = 0; index < 10; index++) write(index + ' '); ?>
   </body>
</html>

This outputs:

Hello World!
0 1 2 3 4 5 6 7 8 9

You also have full access to the HTTP request. That includes forms, uploaded files, headers etc.

I am currently running Node.js through the cgi-node module on Godaddy.

CGI-Node.org site has all the documentation to get started.

I know I'm raving about this but it is finally a relief to use something other than PHP. Also, to be able to code JavaScript on both client and server.

Hope this helps.

IF a == true OR b == true statement

Comparison expressions should each be in their own brackets:

{% if (a == 'foo') or (b == 'bar') %}
    ...
{% endif %}

Alternative if you are inspecting a single variable and a number of possible values:

{% if a in ['foo', 'bar', 'qux'] %}
    ...
{% endif %}

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

SQL Server 2008- Get table constraints

You should use the current sys catalog views (if you're on SQL Server 2005 or newer - the sysobjects views are deprecated and should be avoided) - check out the extensive MSDN SQL Server Books Online documentation on catalog views here.

There are quite a few views you might be interested in:

  • sys.default_constraints for default constraints on columns
  • sys.check_constraints for check constraints on columns
  • sys.key_constraints for key constraints (e.g. primary keys)
  • sys.foreign_keys for foreign key relations

and a lot more - check it out!

You can query and join those views to get the info needed - e.g. this will list the tables, columns and all default constraints defined on them:

SELECT 
    TableName = t.Name,
    ColumnName = c.Name,
    dc.Name,
    dc.definition
FROM sys.tables t
INNER JOIN sys.default_constraints dc ON t.object_id = dc.parent_object_id
INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND c.column_id = dc.parent_column_id
ORDER BY t.Name

How to show and update echo on same line

My favorite way is called do the sleep to 50. here i variable need to be used inside echo statements.

for i in $(seq 1 50); do
  echo -ne "$i%\033[0K\r"
  sleep 50
done
echo "ended"

What does collation mean?

Collation defines how you sort and compare string values

For example, it defines how to deal with

  • accents (äàa etc)
  • case (Aa)
  • the language context:
    • In a French collation, cote < côte < coté < côté.
    • In the SQL Server Latin1 default , cote < coté < côte < côté
  • ASCII sorts (a binary collation)

Sniff HTTP packets for GET and POST requests from an application

post in http
Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet

How do I debug a stand-alone VBScript script?

Export this folder to a backup file and try remove this folder and all the content.

HKEY_CURRENT_USER\Software\Microsoft\Script Debugger

How to split (chunk) a Ruby array into parts of X elements?

Take a look at Enumerable#each_slice:

foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]

how to get vlc logs?

Or you can use the more obvious solution, right in the GUI: Tools -> Messages (set verbosity to 2)...

How to activate JMX on my JVM for access with jconsole?

On Linux, I used the following params:

-Djavax.management.builder.initial= 
-Dcom.sun.management.jmxremote 
-Dcom.sun.management.jmxremote.port=9010 
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.authenticate=false 
-Dcom.sun.management.jmxremote.ssl=false

and also I edited /etc/hosts so that the hostname resolves to the host address (192.168.0.x) rather than the loopback address (127.0.0.1)

Android ListView with Checkbox and all clickable

Below code will help you:

public class DeckListAdapter extends BaseAdapter{

      private LayoutInflater mInflater;
        ArrayList<String> teams=new ArrayList<String>();
        ArrayList<Integer> teamcolor=new ArrayList<Integer>();


        public DeckListAdapter(Context context) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);

            teams.add("Upload");
            teams.add("Download");
            teams.add("Device Browser");
            teams.add("FTP Browser");
            teams.add("Options");

            teamcolor.add(Color.WHITE);
            teamcolor.add(Color.LTGRAY);
            teamcolor.add(Color.WHITE);
            teamcolor.add(Color.LTGRAY);
            teamcolor.add(Color.WHITE);


        }



        public int getCount() {
            return teams.size();
        }


        public Object getItem(int position) {
            return position;
        }


        public long getItemId(int position) {
            return position;
        }

       @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;


            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.decklist, null);

                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.deckarrow);
                holder.text = (TextView) convertView.findViewById(R.id.textname);

             .......here you can use holder.text.setonclicklistner(new View.onclick.

                        for each textview


                System.out.println(holder.text.getText().toString());

                convertView.setTag(holder);
            } else {

                holder = (ViewHolder) convertView.getTag();
            }



             holder.text.setText(teams.get(position));

             if(position<teamcolor.size())
             holder.text.setBackgroundColor(teamcolor.get(position));

             holder.icon.setImageResource(R.drawable.arraocha);







            return convertView;
        }

        class ViewHolder {
            ImageView icon;
            TextView text;



        }
}

Hope this helps.

How to use cURL to send Cookies?

I'm using Debian, and I was unable to use tilde for the path. Originally I was using

curl -c "~/cookie" http://localhost:5000/login -d username=myname password=mypassword

I had to change this to:

curl -c "/tmp/cookie" http://localhost:5000/login -d username=myname password=mypassword

-c creates the cookie, -b uses the cookie

so then I'd use for instance:

curl -b "/tmp/cookie" http://localhost:5000/getData

SQlite - Android - Foreign key syntax

As you can see in the error description your table contains the columns (_id, tast_title, notes, reminder_date_time) and you are trying to add a foreign key from a column "taskCat" but it does not exist in your table!

How to check all checkboxes using jQuery?

Usually you also want the master checkbox to be unchecked if at least 1 slave checkbox is unchecked and to be ckecked if all slave checkboxes are checked:

/**
 * Checks and unchecks checkbox-group with a master checkbox and slave checkboxes
 * @param masterId is the id of master checkbox
 * @param slaveName is the name of slave checkboxes
 */
function checkAll(masterId, slaveName) {
    $master = $('#' + masterId);
    $slave = $('input:checkbox[name=' + slaveName + ']');

    $master.click(function(){
        $slave.prop('checked', $(this).prop('checked'));
        $slave.trigger('change');
    });

    $slave.change(function() {
        if ($master.is(':checked') && $slave.not(':checked').length > 0) {
            $master.prop('checked', false);
        } else if ($master.not(':checked') && $slave.not(':checked').length == 0) {
        $master.prop('checked', 'checked');
    }
    });
}

And if you want to enable any control (e.g. Remove All button or a Add Something button), when at least one checkbox is checked and disable when no checkbox is checked:

/**
 * Checks and unchecks checkbox-group with a master checkbox and slave checkboxes,
 * enables or disables a control when a checkbox is checked
 * @param masterId is the id of master checkbox
 * @param slaveName is the name of slave checkboxes
 */
function checkAllAndSwitchControl(masterId, slaveName, controlId) {
    $master = $('#' + masterId);
    $slave = $('input:checkbox[name=' + slaveName + ']');

    $master.click(function(){
        $slave.prop('checked', $(this).prop('checked'));
        $slave.trigger('change');
    });

    $slave.change(function() {
        switchControl(controlId, $slave.filter(':checked').length > 0);
        if ($master.is(':checked') && $slave.not(':checked').length > 0) {
            $master.prop('checked', false);
        } else if ($master.not(':checked') && $slave.not(':checked').length == 0) {
        $master.prop('checked', 'checked');
    }
    });
}

/**
 * Enables or disables a control
 * @param controlId is the control-id
 * @param enable is true, if control must be enabled, or false if not
 */
function switchControl(controlId, enable) {
    var $control = $('#' + controlId);
    if (enable) {
        $control.removeProp('disabled');
    } else {
        $control.prop('disabled', 'disabled');
    }
}

One-line list comprehension: if-else variants

[x if x % 2 else x * 100 for x in range(1, 10) ]

POSTing JSON to URL via WebClient in C#

The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:

var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");

PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.

How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

Reading string from input with space character?

Using this code you can take input till pressing enter of your keyboard.

char ch[100];
int i;
for (i = 0; ch[i] != '\n'; i++)
{
    scanf("%c ", &ch[i]);
}

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

sudo snap install postman

This single command worked for me.

Unable to run Java GUI programs with Ubuntu

Check your X Window environment variables using the "env" command.

What are NR and FNR and what does "NR==FNR" imply?

In awk, FNR refers to the record number (typically the line number) in the current file and NR refers to the total record number. The operator == is a comparison operator, which returns true when the two surrounding operands are equal.

This means that the condition NR==FNR is only true for the first file, as FNR resets back to 1 for the first line of each file but NR keeps on increasing.

This pattern is typically used to perform actions on only the first file. The next inside the block means any further commands are skipped, so they are only run on files other than the first.

The condition FNR==NR compares the same two operands as NR==FNR, so it behaves in the same way.

jQuery add text to span within a div

You can use:

$("#tagscloud span").text("Your text here");

The same code will also work for the second case. You could also use:

$("#tagscloud #WebPartCaptionWPQ2").text("Your text here");

Is there any way to kill a Thread?

It is generally a bad pattern to kill a thread abruptly, in Python, and in any language. Think of the following cases:

  • the thread is holding a critical resource that must be closed properly
  • the thread has created several other threads that must be killed as well.

The nice way of handling this, if you can afford it (if you are managing your own threads), is to have an exit_request flag that each thread checks on a regular interval to see if it is time for it to exit.

For example:

import threading

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self,  *args, **kwargs):
        super(StoppableThread, self).__init__(*args, **kwargs)
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

In this code, you should call stop() on the thread when you want it to exit, and wait for the thread to exit properly using join(). The thread should check the stop flag at regular intervals.

There are cases, however, when you really need to kill a thread. An example is when you are wrapping an external library that is busy for long calls, and you want to interrupt it.

The following code allows (with some restrictions) to raise an Exception in a Python thread:

def _async_raise(tid, exctype):
    '''Raises an exception in the threads with id tid'''
    if not inspect.isclass(exctype):
        raise TypeError("Only types can be raised (not instances)")
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid),
                                                     ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # "if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"
        ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
        raise SystemError("PyThreadState_SetAsyncExc failed")

class ThreadWithExc(threading.Thread):
    '''A thread class that supports raising an exception in the thread from
       another thread.
    '''
    def _get_my_tid(self):
        """determines this (self's) thread id

        CAREFUL: this function is executed in the context of the caller
        thread, to get the identity of the thread represented by this
        instance.
        """
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")

        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id

        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid

        # TODO: in python 2.6, there's a simpler way to do: self.ident

        raise AssertionError("could not determine the thread's id")

    def raiseExc(self, exctype):
        """Raises the given exception type in the context of this thread.

        If the thread is busy in a system call (time.sleep(),
        socket.accept(), ...), the exception is simply ignored.

        If you are sure that your exception should terminate the thread,
        one way to ensure that it works is:

            t = ThreadWithExc( ... )
            ...
            t.raiseExc( SomeException )
            while t.isAlive():
                time.sleep( 0.1 )
                t.raiseExc( SomeException )

        If the exception is to be caught by the thread, you need a way to
        check that your thread has caught it.

        CAREFUL: this function is executed in the context of the
        caller thread, to raise an exception in the context of the
        thread represented by this instance.
        """
        _async_raise( self._get_my_tid(), exctype )

(Based on Killable Threads by Tomer Filiba. The quote about the return value of PyThreadState_SetAsyncExc appears to be from an old version of Python.)

As noted in the documentation, this is not a magic bullet because if the thread is busy outside the Python interpreter, it will not catch the interruption.

A good usage pattern of this code is to have the thread catch a specific exception and perform the cleanup. That way, you can interrupt a task and still have proper cleanup.

Create a CSS rule / class with jQuery at runtime

Here is a jquery plugin that allows you to inject CSS:

https://github.com/kajic/jquery-injectCSS

Example:

$.injectCSS({
    "#my-window": {
        "position": "fixed",
        "z-index": 102,
        "display": "none",
        "top": "50%",
        "left": "50%"
    }
});

Fill remaining vertical space - only CSS

You can use CSS Flexbox instead another display value, The Flexbox Layout (Flexible Box) module aims at providing a more efficient way to lay out, align and distribute space among items in a container, even when their size is unknown and/or dynamic.

Example

/* CONTAINER */
#wrapper
{
   width:300px;
   height:300px;
    display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
    display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
    display: -ms-flexbox; /* TWEENER - IE 10 */
    display: -webkit-flex; /* NEW - Chrome */
    display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */
    -ms-flex-direction: column;
    -moz-flex-direction: column;
    -webkit-flex-direction: column;
    flex-direction: column;
}

/* SOME ITEM CHILD ELEMENTS */
#first
{
   width:300px;
    height: 200px;
   background-color:#F5DEB3;

}

#second
{
   width:300px;
   background-color: #9ACD32;
    -webkit-box-flex: 1; /* OLD - iOS 6-, Safari 3.1-6 */
    -moz-box-flex: 1; /* OLD - Firefox 19- */
    -webkit-flex: 1; /* Chrome */
    -ms-flex: 1; /* IE 10 */
    flex: 1; /* NEW, */
}

jsfiddle Example

If you want to have full support for old browsers like IE9 or below, you will have to use a polyfills like flexy, this polyfill enable support for Flexbox model but only for 2012 spec of flexbox model.

Recently I found another polyfill to help you with Internet Explorer 8 & 9 or any older browser that not have support for flexbox model, I still have not tried it but I leave the link here

You can find a usefull and complete Guide to Flexbox model by Chris Coyer here

Get encoding of a file in Windows

If you have "git" or "Cygwin" on your Windows Machine, then go to the folder where your file is present and execute the command:

file *

This will give you the encoding details of all the files in that folder.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

it's also a good thing to make sure you have the right import

I had an issue like that and I found out that the bean was using

    javax.faces.view.ViewScoped;
                 ^

instead of

    javax.faces.bean.ViewScoped;
                 ^

How to create a shortcut using PowerShell

I don't know any native cmdlet in powershell but you can use com object instead:

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()

you can create a powershell script save as set-shortcut.ps1 in your $pwd

param ( [string]$SourceExe, [string]$DestinationPath )

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()

and call it like this

Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"

If you want to pass arguments to the target exe, it can be done by:

#Set the additional parameters for the shortcut  
$Shortcut.Arguments = "/argument=value"  

before $Shortcut.Save().

For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.

param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()

post ajax data to PHP and return data

So what does count_votes look like? Is it a script? Anything that you want to get back from an ajax call can be retrieved using a simple echo (of course you could use JSON or xml, but for this simple example you would just need to output something in count_votes.php like:

$id = $_POST['id'];

function getVotes($id){
    // call your database here
    $query = ("SELECT votes FROM poll WHERE ID = $id");
    $result = @mysql_query($query);
    $row = mysql_fetch_row($result);

    return $row->votes;
}
$votes = getVotes($id);
echo $votes;

This is just pseudocode, but should give you the idea. What ever you echo from count_votes will be what is returned to "data" in your ajax call.

Display all items in array using jquery

Original from Sept. 13, 2015:
Quick and easy.

$.each(yourArray, function(index, value){
    $('.element').html( $('.element').html() + '<span>' + value +'</span>')
});

Update Sept 9, 2019: No jQuery is needed to iterate the array.

yourArray.forEach((value) => {
    $(".element").html(`${$(".element").html()}<span>${value}</span>`);
});

/* --- Or without jQuery at all --- */

yourArray.forEach((value) => {
    document.querySelector(".element").innerHTML += `<span>${value}</span>`;
});

Can I position an element fixed relative to parent?

The CSS specification requires that position:fixed be anchored to the viewport, not the containing positioned element.

If you must specify your coordinates relative to a parent, you will have to use JavaScript to find the parent's position relative to the viewport first, then set the child (fixed) element's position accordingly.

ALTERNATIVE: Some browsers have sticky CSS support which limits an element to be positioned within both its container and the viewport. Per the commit message:

sticky ... constrains an element to be positioned inside the intersection of its container box, and the viewport.

A stickily positioned element behaves like position:relative (space is reserved for it in-flow), but with an offset that is determined by the sticky position. Changed isInFlowPositioned() to cover relative and sticky.

Depending on your design goals, this behavior may be helpful in some cases. It is currently a working draft, and has decent support, aside from table elements. position: sticky still needs a -webkit prefix in Safari.

See caniuse for up-to-date stats on browser support.

How to prevent tensorflow from allocating the totality of a GPU memory?

Tensorflow 2.0 Beta and (probably) beyond

The API changed again. It can be now found in:

tf.config.experimental.set_memory_growth(
    device,
    enable
)

Aliases:

  • tf.compat.v1.config.experimental.set_memory_growth
  • tf.compat.v2.config.experimental.set_memory_growth

References:

See also: Tensorflow - Use a GPU: https://www.tensorflow.org/guide/gpu

for Tensorflow 2.0 Alpha see: this answer

How to get an element by its href in jquery?

var myElement = $("a[href='http://www.stackoverflow.com']");

http://api.jquery.com/attribute-equals-selector/

How can I do string interpolation in JavaScript?

Supplant more for ES6 version of @Chris Nielsen's post.

String.prototype.supplant = function (o) {
  return this.replace(/\${([^\${}]*)}/g,
    (a, b) => {
      var r = o[b];
      return typeof r === 'string' || typeof r === 'number' ? r : a;
    }
  );
};

string = "How now ${color} cow? {${greeting}}, ${greeting}, moo says the ${color} cow.";

string.supplant({color: "brown", greeting: "moo"});
=> "How now brown cow? {moo}, moo, moo says the brown cow."

What is a predicate in c#?

In C# Predicates are simply delegates that return booleans. They're useful (in my experience) when you're searching through a collection of objects and want something specific.

I've recently run into them in using 3rd party web controls (like treeviews) so when I need to find a node within a tree, I use the .Find() method and pass a predicate that will return the specific node I'm looking for. In your example, if 'a' mod 2 is 0, the delegate will return true. Granted, when I'm looking for a node in a treeview, I compare it's name, text and value properties for a match. When the delegate finds a match, it returns the specific node I was looking for.

Evenly distributing n points on a sphere

In this example code node[k] is just the kth node. You are generating an array N points and node[k] is the kth (from 0 to N-1). If that is all that is confusing you, hopefully you can use that now.

(in other words, k is an array of size N that is defined before the code fragment starts, and which contains a list of the points).

Alternatively, building on the other answer here (and using Python):

> cat ll.py
from math import asin
nx = 4; ny = 5
for x in range(nx):
    lon = 360 * ((x+0.5) / nx)
    for y in range(ny):                                                         
        midpt = (y+0.5) / ny                                                    
        lat = 180 * asin(2*((y+0.5)/ny-0.5))                                    
        print lon,lat                                                           
> python2.7 ll.py                                                      
45.0 -166.91313924                                                              
45.0 -74.0730322921                                                             
45.0 0.0                                                                        
45.0 74.0730322921                                                              
45.0 166.91313924                                                               
135.0 -166.91313924                                                             
135.0 -74.0730322921                                                            
135.0 0.0                                                                       
135.0 74.0730322921                                                             
135.0 166.91313924                                                              
225.0 -166.91313924                                                             
225.0 -74.0730322921                                                            
225.0 0.0                                                                       
225.0 74.0730322921                                                             
225.0 166.91313924
315.0 -166.91313924
315.0 -74.0730322921
315.0 0.0
315.0 74.0730322921
315.0 166.91313924

If you plot that, you'll see that the vertical spacing is larger near the poles so that each point is situated in about the same total area of space (near the poles there's less space "horizontally", so it gives more "vertically").

This isn't the same as all points having about the same distance to their neighbours (which is what I think your links are talking about), but it may be sufficient for what you want and improves on simply making a uniform lat/lon grid.

Maximum length of HTTP GET request

You are asking two separate questions here:

What's the maximum length of an HTTP GET request?

As already mentioned, HTTP itself doesn't impose any hard-coded limit on request length; but browsers have limits ranging on the 2 KB - 8 KB (255 bytes if we count very old browsers).

Is there a response error defined that the server can/should return if it receives a GET request exceeds this length?

That's the one nobody has answered.

HTTP 1.1 defines status code 414 Request-URI Too Long for the cases where a server-defined limit is reached. You can see further details on RFC 2616.

For the case of client-defined limits, there isn't any sense on the server returning something, because the server won't receive the request at all.

How to restart service using command prompt?

PowerShell features a Restart-Service cmdlet, which either starts or restarts the service as appropriate.

The Restart-Service cmdlet sends a stop message and then a start message to the Windows Service Controller for a specified service. If a service was already stopped, it is started without notifying you of an error.

You can specify the services by their service names or display names, or you can use the InputObject parameter to pass an object that represents each service that you want to restart.

It is a little more foolproof than running two separate commands.

The easiest way to use it just pass either the service name or the display name directly:

Restart-Service 'Service Name'

It can be used directly from the standard cmd prompt with a command like:

powershell -command "Restart-Service 'Service Name'"

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

For me it was because of the Chrome extension 'Grammarly'. After disabling that, I did not get the error.

Create instance of generic type whose constructor requires a parameter?

You can use the following command:

 T instance = (T)typeof(T).GetConstructor(new Type[0]).Invoke(new object[0]);

Be sure to see the following reference.

reading text file with utf-8 encoding using java

You are reading the file right but the problem seems to be with the default encoding of System.out. Try this to print the UTF-8 string-

PrintStream out = new PrintStream(System.out, true, "UTF-8");
out.println(str);

Java dynamic array sizes?

I recommend using vectors instead. Very easy to use and has many predefined methods for implementation.

import java.util.*;

Vector<Integer> v=new Vector<Integer>(5,2);

to add an element simply use:

v.addElement(int);

In the (5,2) the first 5 is the initial size of the vector. If you exceed the initial size,the vector will grow by 2 places. If it exceeds again, then it will again increase by 2 places and so on.

Django DateField default options

I think a better way to solve this would be to use the datetime callable:

from datetime import datetime

date = models.DateField(default=datetime.now)

Note that no parenthesis were used. If you used parenthesis you would invoke the now() function just once (when the model is created). Instead, you pass the callable as an argument, thus being invoked everytime an instance of the model is created.

Credit to Django Musings. I've used it and works fine.

Using OR & AND in COUNTIFS

You could just add a few COUNTIF statements together:

=COUNTIF(A1:A196,"yes")+COUNTIF(A1:A196,"no")+COUNTIF(J1:J196,"agree")

This will give you the result you need.

EDIT

Sorry, misread the question. Nicholas is right that the above will double count. I wasn't thinking of the AND condition the right way. Here's an alternative that should give you the correct results, which you were pretty close to in the first place:

=SUM(COUNTIFS(A1:A196,{"yes","no"},J1:J196,"agree"))

jQuery counting elements by class - what is the best way to implement this?

try

document.getElementsByClassName('myclass').length

_x000D_
_x000D_
let num = document.getElementsByClassName('myclass').length;_x000D_
console.log('Total "myclass" elements: '+num);
_x000D_
.myclass { color: red }
_x000D_
<span class="myclass" >1</span>_x000D_
<span>2</span>_x000D_
<span class="myclass">3</span>_x000D_
<span class="myclass">4</span>
_x000D_
_x000D_
_x000D_

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

Python Script execute commands in Terminal

for python3 use subprocess

import subprocess
s = subprocess.getstatusoutput(f'ps -ef | grep python3')
print(s)

How to convert ASCII code (0-255) to its corresponding character?

One can iterate from a to z like this

int asciiForLowerA = 97;
int asciiForLowerZ = 122;
for(int asciiCode = asciiForLowerA; asciiCode <= asciiForLowerZ; asciiCode++){
    search(sCurrentLine, searchKey + Character.toString ((char) asciiCode));
}

CSS Input Type Selectors - Possible to have an "or" or "not" syntax?

input[type='text'], input[type='password']
{
   // my css
}

That is the correct way to do it. Sadly CSS is not a programming language.

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

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

package com.xxx.test.schedulers;

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

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

import com.xxx.core.XProvLogger;

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


private ApplicationContext context;

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

public void onApplicationEvent(ContextClosedEvent event) {


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

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

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

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


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

}


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


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

}

When does a cookie with expiration time 'At end of session' expire?

When you use setcookie, you can either set the expiration time to 0 or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).

update package.json version automatically

This is what I normally do with my projects:

npm version patch
git add *;
git commit -m "Commit message"
git push
npm publish

The first line, npm version patch, will increase the patch version by 1 (x.x.1 to x.x.2) in package.json. Then you add all files -- including package.json which at that point has been modified. Then, the usual git commit and git push, and finally npm publish to publish the module.

I hope this makes sense...

Merc.

Split text file into smaller multiple text file using command line

I have created a simple program for this and your question helped me complete the solution... I added one more feature and few configurations. In case you want to add a specific character/ string after every few lines (configurable). Please go through the notes. I have added the code files : https://github.com/mohitsharma779/FileSplit

How to bring view in front of everything?

There can be another way which saves the day. Just init a new Dialog with desired layout and just show it. I need it for showing a loadingView over a DialogFragment and this was the only way I succeed.

Dialog topDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
topDialog.setContentView(R.layout.dialog_top);
topDialog.show();

bringToFront() might not work in some cases like mine. But content of dialog_top layout must override anything on the ui layer. But anyway, this is an ugly workaround.

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

You can load an assembly using *Assembly.Load** methods. Using Activator.CreateInstance you can create new instances of the type you want. Keep in mind that you have to use the full type name of the class you want to load (for example Namespace.SubNamespace.ClassName). Using the method InvokeMember of the Type class you can invoke methods on the type.

Also, take into account that once loaded, an assembly cannot be unloaded until the whole AppDomain is unloaded too (this is basically a memory leak).

ERROR 2006 (HY000): MySQL server has gone away

How about using the mysql client like this:

mysql -h <hostname> -u username -p <databasename> < file.sql

How to avoid Number Format Exception in java?

Documentation for the method from the Apache Commons Lang (from here):

Checks whether the String a valid Java number.

Valid numbers include hexadecimal marked with the 0x qualifier, scientific notation and numbers marked with a type qualifier (e.g. 123L).

Null and empty String will return false.

Parameters:

`str` - the `String` to check

Returns:

`true` if the string is a correctly formatted number

isNumber from java.org.apache.commons.lang3.math.NumberUtils:

public static boolean isNumber(final String str) {
    if (StringUtils.isEmpty(str)) {
        return false;
    }
    final char[] chars = str.toCharArray();
    int sz = chars.length;
    boolean hasExp = false;
    boolean hasDecPoint = false;
    boolean allowSigns = false;
    boolean foundDigit = false;
    // deal with any possible sign up front
    final int start = (chars[0] == '-') ? 1 : 0;
    if (sz > start + 1 && chars[start] == '0' && chars[start + 1] == 'x') {
        int i = start + 2;
        if (i == sz) {
            return false; // str == "0x"
        }
        // checking hex (it can't be anything else)
        for (; i < chars.length; i++) {
            if ((chars[i] < '0' || chars[i] > '9')
                && (chars[i] < 'a' || chars[i] > 'f')
                && (chars[i] < 'A' || chars[i] > 'F')) {
                return false;
            }
        }
        return true;
    }
    sz--; // don't want to loop to the last char, check it afterwords
          // for type qualifiers
    int i = start;
    // loop to the next to last char or to the last char if we need another digit to
    // make a valid number (e.g. chars[0..5] = "1234E")
    while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {
        if (chars[i] >= '0' && chars[i] <= '9') {
            foundDigit = true;
            allowSigns = false;

        } else if (chars[i] == '.') {
            if (hasDecPoint || hasExp) {
                // two decimal points or dec in exponent   
                return false;
            }
            hasDecPoint = true;
        } else if (chars[i] == 'e' || chars[i] == 'E') {
            // we've already taken care of hex.
            if (hasExp) {
                // two E's
                return false;
            }
            if (!foundDigit) {
                return false;
            }
            hasExp = true;
            allowSigns = true;
        } else if (chars[i] == '+' || chars[i] == '-') {
            if (!allowSigns) {
                return false;
            }
            allowSigns = false;
            foundDigit = false; // we need a digit after the E
        } else {
            return false;
        }
        i++;
    }
    if (i < chars.length) {
        if (chars[i] >= '0' && chars[i] <= '9') {
            // no type qualifier, OK
            return true;
        }
        if (chars[i] == 'e' || chars[i] == 'E') {
            // can't have an E at the last byte
            return false;
        }
        if (chars[i] == '.') {
            if (hasDecPoint || hasExp) {
                // two decimal points or dec in exponent
                return false;
            }
            // single trailing decimal point after non-exponent is ok
            return foundDigit;
        }
        if (!allowSigns
            && (chars[i] == 'd'
                || chars[i] == 'D'
                || chars[i] == 'f'
                || chars[i] == 'F')) {
            return foundDigit;
        }
        if (chars[i] == 'l'
            || chars[i] == 'L') {
            // not allowing L with an exponent or decimal point
            return foundDigit && !hasExp && !hasDecPoint;
        }
        // last character is illegal
        return false;
    }
    // allowSigns is true iff the val ends in 'E'
    // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass
    return !allowSigns && foundDigit;
}

[code is under version 2 of the Apache License]

How to reset a timer in C#?

Other alternative way to reset the windows.timer is using the counter, as follows:

int timerCtr = 0;
Timer mTimer;

private void ResetTimer() => timerCtr = 0;
private void mTimer_Tick()
{
    timerCtr++;
    // Perform task
}  

So if you intend to repeat every 1 second, you can set the timer interval at 100ms, and test the counter to 10 cycles.

This is suitable if the timer should wait for some processes those may be ended at the different time span.

How do we determine the number of days for a given month in python

Use calendar.monthrange:

>>> from calendar import monthrange
>>> monthrange(2011, 2)
(1, 28)

Just to be clear, monthrange supports leap years as well:

>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)

As @mikhail-pyrev mentions in a comment:

First number is weekday of first day of the month, second number is number of days in said month.

How to add additional fields to form before submit?

You can add a hidden input with whatever value you need to send:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="someName" value="someValue">');
    return true;
});

Practical uses for AtomicInteger

The key is that they allow concurrent access and modification safely. They're commonly used as counters in a multithreaded environment - before their introduction this had to be a user written class that wrapped up the various methods in synchronized blocks.

How can I print out all possible letter combinations a given phone number can represent?

This version in C# is reasonably efficient, and it works for non-western digits (like "???????" for example).

static void Main(string[] args)
{
    string phoneNumber = null;
    if (1 <= args.Length)
        phoneNumber = args[0];
    if (string.IsNullOrEmpty(phoneNumber))
    {
        Console.WriteLine("No phone number supplied.");
        return;
    }
    else
    {
        Console.WriteLine("Alphabetic phone numbers for \"{0}\":", phoneNumber);
        foreach (string phoneNumberText in GetPhoneNumberCombos(phoneNumber))
            Console.Write("{0}\t", phoneNumberText);
    }
}

public static IEnumerable<string> GetPhoneNumberCombos(string phoneNumber)
{
    phoneNumber = RemoveNondigits(phoneNumber);
    if (string.IsNullOrEmpty(phoneNumber))
        return new List<string>();

    char[] combo = new char[phoneNumber.Length];
    return GetRemainingPhoneNumberCombos(phoneNumber, combo, 0);
}

private static string RemoveNondigits(string phoneNumber)
{
    if (phoneNumber == null)
        return null;
    StringBuilder sb = new StringBuilder();
    foreach (char nextChar in phoneNumber)
        if (char.IsDigit(nextChar))
            sb.Append(nextChar);
    return sb.ToString();
}

private static IEnumerable<string> GetRemainingPhoneNumberCombos(string phoneNumber, char[] combo, int nextDigitIndex)
{
    if (combo.Length - 1 == nextDigitIndex)
    {
        foreach (char nextLetter in phoneNumberAlphaMapping[(int)char.GetNumericValue(phoneNumber[nextDigitIndex])])
        {
            combo[nextDigitIndex] = nextLetter;
            yield return new string(combo);
        }
    }
    else
    {
        foreach (char nextLetter in phoneNumberAlphaMapping[(int)char.GetNumericValue(phoneNumber[nextDigitIndex])])
        {
            combo[nextDigitIndex] = nextLetter;
            foreach (string result in GetRemainingPhoneNumberCombos(phoneNumber, combo, nextDigitIndex + 1))
                yield return result;
        }
    }

}

private static char[][] phoneNumberAlphaMapping = new char[][]
{
    new char[] { '0' },
    new char[] { '1' },
    new char[] { 'a', 'b', 'c' },
    new char[] { 'd', 'e', 'f' },
    new char[] { 'g', 'h', 'i' },
    new char[] { 'j', 'k', 'l' },
    new char[] { 'm', 'n', 'o' },
    new char[] { 'p', 'q', 'r', 's' },
    new char[] { 't', 'u', 'v' },
    new char[] { 'w', 'x', 'y', 'z' }
};

How do I display images from Google Drive on a website?

I have the same problem right now but this article helps me. Updates for the year 2020!

I got the solution from this article:
https://dev.to/imamcu07/embed-or-display-image-to-html-page-from-google-drive-3ign

These are the steps from the article:

  1. Upload your image to google drive.
  2. Share your image from the sharing option.
  3. Copy your sharing link (Sample: https://drive.google.com/file/d/14hz3ySPn-zBd4Tu3NtY1F05LSGdFfWvp/view?usp=sharing)
  4. Copy the id from your link, in the above link, the id is: 14hz3ySPn-zBd4Tu3NtY1F05LSGdFfWvp
  5. Have a look at the below link and replace the ID. https://drive.google.com/thumbnail?id=1jNWSPr_BOSbm7iIJQTTbl7lXX06NH9_r

After Replace ID: https://drive.google.com/thumbnail?id=14hz3ySPn-zBd4Tu3NtY1F05LSGdFfWvp

  1. Now insert the link to your <img> tag.

And now it should work.

! [rejected] master -> master (fetch first)

Your error might be because of the merge branch.
Just follow this:

step 1 : git pull origin master (in case if you get any message then ignore it)
step 2 : git add .
step 3 : git commit -m 'your commit message'
step 4 : git push origin master

delete vs delete[] operators in C++

This the basic usage of allocate/DE-allocate pattern in c++ malloc/free, new/delete, new[]/delete[]

We need to use them correspondingly. But I would like to add this particular understanding for the difference between delete and delete[]

1) delete is used to de-allocate memory allocated for single object

2) delete[] is used to de-allocate memory allocated for array of objects

class ABC{}

ABC *ptr = new ABC[100]

when we say new ABC[100], compiler can get the information about how many objects that needs to be allocated(here it is 100) and will call the constructor for each of the objects created

but correspondingly if we simply use delete ptr for this case, compiler will not know how many objects that ptr is pointing to and will end up calling of destructor and deleting memory for only 1 object(leaving the invocation of destructors and deallocation of remaining 99 objects). Hence there will be a memory leak.

so we need to use delete [] ptr in this case.

Programmatically Hide/Show Android Soft Keyboard

Did you try InputMethodManager.SHOW_IMPLICIT in first window.

and for hiding in second window use InputMethodManager.HIDE_IMPLICIT_ONLY

EDIT :

If its still not working then probably you are putting it at the wrong place. Override onFinishInflate() and show/hide there.

@override
public void onFinishInflate() {
     /* code to show keyboard on startup */
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(mUserNameEdit, InputMethodManager.SHOW_IMPLICIT);
}

What's the difference between TRUNCATE and DELETE in SQL

With SQL Server or MySQL, if there is a PK with auto increment, truncate will reset the counter.

How to generate a random number between a and b in Ruby?

For 10 and 10**24

rand(10**24-10)+10

Constructors in Go

If you want to emulate ___.new() syntax you can do something along the lines of:

type Thing struct {
    Name string
    Num int
}
type Constructor_Thing struct {}
func (c CThing) new(<<CONSTRUCTOR ARGS>>) Thing {
  var thing Thing
  //initiate thing from constructor args
  return thing
}
var cThing CThing

func main(){
  var myThing Thing
  myThing = cThing.new(<<CONSTRUCTOR ARGS>>)
  //...
}

Granted, it is a shame that Thing.new() cannot be implemented without CThing.new() also being implemented (iirc) which is a bit of a shame...

Get Absolute URL from Relative path (refactored method)

When you want to generate URL from your Business Logic layer, you do not have the flexibility of using ASP.NET Web Form's Page class/ Control's ResolveUrl(..) etc. Moreover, you may need to generate URL from ASP.NET MVC controller too where you not only miss the Web Form's ResolveUrl(..) method, but also you cannot get the Url.Action(..) even though Url.Action takes only Controller name and Action name, not the relative url.

I tried using

var uri = new Uri(absoluteUrl, relativeUrl)

approach, but there is a problem too. If the web application is hosted in IIS virtual directory, where the url of the app is like this : http://localhost/MyWebApplication1/, and the relative url is "/myPage" then the relative url is resolved as "http://localhost/MyPage" which is another problem.

Therefore, in order to overcome such problems, I have written a UrlUtils class which can work from a class library. So, it wont depend on Page class but it depends on ASP.NET MVC. So, if you dont mind adding reference to MVC dll to your class library project then my class will work smoothly. I have tested in IIS virtual directory scenario where the web application url is like this : http://localhost/MyWebApplication/MyPage. I realized that, sometimes we need to make sure that the Absolute url is SSL url or non SSL url. So, I wrote my class library supporting this option. I have restricted this class library so that the relative url can be absolute url or a relative url that starts with '~/'.

Using this library, I can call

string absoluteUrl = UrlUtils.MapUrl("~/Contact");

Returns : http://localhost/Contact when the page url is : http://localhost/Home/About

Returns : http://localhost/MyWebApplication/Contact when the page url is : http://localhost/MyWebApplication/Home/About

  string absoluteUrl = UrlUtils.MapUrl("~/Contact", UrlUtils.UrlMapOptions.AlwaysSSL);

Returns : **https**://localhost/MyWebApplication/Contact when the page url is : http://localhost/MyWebApplication/Home/About

Here is my class Library :

 public class UrlUtils
    {
        public enum UrlMapOptions
        {
            AlwaysNonSSL,
            AlwaysSSL,
            BasedOnCurrentScheme
        }

        public static string MapUrl(string relativeUrl, UrlMapOptions option = UrlMapOptions.BasedOnCurrentScheme)
        {
            if (relativeUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
                relativeUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
                return relativeUrl;

            if (!relativeUrl.StartsWith("~/"))
                throw new Exception("The relative url must start with ~/");

            UrlHelper theHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);

            string theAbsoluteUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
                                           theHelper.Content(relativeUrl);

            switch (option)
            {
                case UrlMapOptions.AlwaysNonSSL:
                    {
                        return theAbsoluteUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
                            ? string.Format("http://{0}", theAbsoluteUrl.Remove(0, 8))
                            : theAbsoluteUrl;
                    }
                case UrlMapOptions.AlwaysSSL:
                    {
                        return theAbsoluteUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
                            ? theAbsoluteUrl
                            : string.Format("https://{0}", theAbsoluteUrl.Remove(0, 7));
                    }
            }

            return theAbsoluteUrl;
        }
    }   

How to position a CSS triangle using ::after?

You can set triangle with position see this code for reference

.top-left-corner {
    width: 0px;
    height: 0px;
    border-top: 0px solid transparent;
    border-bottom: 55px solid transparent;
    border-left: 55px solid #289006;
    position: absolute;
    left: 0px;
    top: 0px;
}

Angular2 Routing with Hashtag to page anchor

None of the previous answers worked for me. In a last ditch effort, I tried in my template:

<a (click)="onClick()">From Here</a>
<div id='foobar'>To Here</div>

With this in my .ts:

onClick(){
    let x = document.querySelector("#foobar");
    if (x){
        x.scrollIntoView();
    }
}

And it works as expected for internal links. This does not actually use anchor tags so it would not touch the URL at all.

Issue with background color in JavaFX 8

panel.setStyle("-fx-background-color: #FFFFFF;");

ES6 Map in Typescript

As a bare minimum:

tsconfig:

 "lib": [
      "es2015"
    ]

and install a polyfill such as https://github.com/zloirock/core-js if you want IE < 11 support: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Proper way to restrict text input values (e.g. only numbers)

Anoher one

<form [formGroup]="myForm" novalidate>
    <input type="text" class="form-control" id="data" name="data"
           formControlName="input3" #item (input)="change(item.value)">
</form>
{{myForm.value |json}}

change(value:string)
  {
    let lastchar = value.substr(value.length - 1);
    if (!(new RegExp('[0-9]').test(lastchar)))
    {
      value=value.substr(0,value.length-1);
      this.myForm.controls["input3"].setValue(value);

    }
  }

if you use from driven template

  <input type="text" class="form-control" id="data" name="data"
       [(ngModel)]="data" #item (input)="change(item)">
   {{data}}

change(item:any)
  {
    let value=item.value;
    let lastchar = value.substr(value.length - 1);
    if (!(new RegExp('[0-9]').test(lastchar)))
    {
      value=value.substr(0,value.length-1);
      item.value=this.data=value;
    }
  }

Update As @BikashBishwokarma comment, this not work if you insert a character in middle. We can change the function by some like

  change(item:any)
  {
    let value=item.value;
    let pos=item.selectionStart;
    if (!(new RegExp('^[0-9]+$').test(value)))
    {
      item.value=this.data=value.replace(/[^0-9]+/g, '');
      item.selectionStart = item.selectionEnd = pos-1;
    }
  }

See, how mainten the cursor position

Read the package name of an Android APK

A very simple method is to use apkanalyzer.

apkanalyzer manifest application-id "${_path_to_apk}"

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

This is my solution:

  1. Copy&paste $ANDROID_SDK/extras/android/support/v7/appcompat to your project ROOT

  2. Open "Project Structure" on Intellij, click "Modules" on "Project Settings", then click "appcompat"->"android', make sure "Library Module" checkbox is checked.

  3. click "YOUR-PROJECT_NAME" under "appcompat", remove "android-support-v4" and "android-support-v7-compat"; ensure the checkbox before "appcompat" is checked. And, click "ok" to close "Project Structure" dialogue.

  4. back to the mainwindow, click "appcompat"->"libs" on the top-left project area. Right-click on "android-support-v4", select menuitem "Add as library", change "Add to Module" to "Your-project". Same with "android-support-v7-compat".

After doing above, intellij should be able to correctly find the android-support-XXXX modules.

Good Luck!

Integer value comparison

You can also use equals:

 Integer a = 0;

 if (a.equals(0)) {
     // a == 0
 }

which is equivalent to:

 if (a.intValue() == 0) {
     // a == 0
 }

and also:

 if (a == 0) {

 }

(the Java compiler automatically adds intValue())

Note that autoboxing/autounboxing can introduce a significant overhead (especially inside loops).

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

Android Studio (Preview) sometimes recommends updating to a Gradle Plugin that is not available yet (did Google forget to publish it?). Such as today with

'com.android.tools.build:gradle:3.1.0-beta1'

I found I can see current versions of com.android.tools.build:gradle here, and then I just pick the newest:

https://dl.google.com/dl/android/maven2/index.html

I just found this beta1 gradle bug in the Android Bug Tracker. I also just learned Android Studio > Help Menu > Submit Feedback brought me to the bug tracker.

Found temporary solution at androiddev reddit for the 3.1.0-beta1 problem: Either roll back to Preview Canary 8, or switch to gradle plugin 3.0.1 until Canary 10 is released shortly.

How to `wget` a list of URLs in a text file?

If you're on OpenWrt or using some old version of wget which doesn't gives you -i option:

#!/bin/bash
input="text_file.txt"
while IFS= read -r line
do
  wget $line
done < "$input"

Furthermore, if you don't have wget, you can use curl or whatever you use for downloading individual files.

100% Min Height CSS layout

Here is another solution based on vh, or viewpoint height, for details visit CSS units. It is based on this solution, which uses flex instead.

_x000D_
_x000D_
* {_x000D_
    /* personal preference */_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
html {_x000D_
    /* make sure we use up the whole viewport */_x000D_
    width: 100%;_x000D_
    min-height: 100vh;_x000D_
    /* for debugging, a red background lets us see any seams */_x000D_
    background-color: red;_x000D_
}_x000D_
body {_x000D_
    /* make sure we use the full width but allow for more height */_x000D_
    width: 100%;_x000D_
    min-height: 100vh; /* this helps with the sticky footer */_x000D_
}_x000D_
main {_x000D_
    /* for debugging, a blue background lets us see the content */_x000D_
    background-color: skyblue;_x000D_
 min-height: calc(100vh - 2.5em); /* this leaves space for the sticky footer */_x000D_
}_x000D_
footer {_x000D_
    /* for debugging, a gray background lets us see the footer */_x000D_
    background-color: gray;_x000D_
 min-height:2.5em;_x000D_
}
_x000D_
<main>_x000D_
    <p>This is the content. Resize the viewport vertically to see how the footer behaves.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
    <p>This is the content.</p>_x000D_
</main>_x000D_
<footer>_x000D_
    <p>This is the footer. Resize the viewport horizontally to see how the height behaves when text wraps.</p>_x000D_
    <p>This is the footer.</p>_x000D_
</footer>
_x000D_
_x000D_
_x000D_

The units are vw , vh, vmax, vmin. Basically, each unit is equal to 1% of viewport size. So, as the viewport changes, the browser computes that value and adjusts accordingly.

You may find more information here:

Specifically:

1vw (viewport width) = 1% of viewport width
1vh (viewport height) = 1% of viewport height
1vmin (viewport minimum) = 1vw or 1vh, whatever is smallest
1vmax (viewport minimum) = 1vw or 1vh, whatever is largest

How do I find which process is leaking memory?

I suggest the use of htop, as a better alternative to top.

How to access full source of old commit in BitBucket?

Great answers from a couple of years ago. Now Bitbucket has made it easier.

Tag the Commit you want to download (as mentioned in answer by Rudy Matela).

Then head over to Downloads and click the "Tags" tab and you'll get multiple options for download.

Tag Downloads

Attempt to set a non-property-list object as an NSUserDefaults

https://developer.apple.com/reference/foundation/userdefaults

A default object must be a property list—that is, an instance of (or for collections, a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.

If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.

Does a favicon have to be 32x32 or 16x16?

I don't see any up to date info listed here, so here goes:

To answer this question now, 2 favicons will not do it if you want your icon to look great everywhere. See the sizes below:

16 x 16 – Standard size for browsers
24 x 24 – IE9 pinned site size for user interface
32 x 32 – IE new page tab, Windows 7+ taskbar button, Safari Reading List sidebar
48 x 48 – Windows site
57 x 57 – iPod touch, iPhone up to 3G
60 x 60 – iPhone touch up to iOS7
64 x 64 – Windows site, Safari Reader List sidebar in HiDPI/Retina
70 x 70 – Win 8.1 Metro tile
72 x 72 – iPad touch up to iOS6
76 x 76 – iOS7
96 x 96 – GoogleTV
114 x 114 – iPhone retina touch up to iOS6
120 x 120 – iPhone retina touch iOS7
128 x 128 – Chrome Web Store app, Android
144 x 144 – IE10 Metro tile for pinned site, iPad retina up to iOS6
150 x 150 – Win 8.1 Metro tile
152 x 152 – iPad retina touch iOS7
196 x 196 – Android Chrome
310 x 150 – Win 8.1 wide Metro tile
310 x 310 – Win 8.1 Metro tile

Block direct access to a file over http but allow php script access

The safest way is to put the files you want kept to yourself outside of the web root directory, like Damien suggested. This works because the web server follows local file system privileges, not its own privileges.

However, there are a lot of hosting companies that only give you access to the web root. To still prevent HTTP requests to the files, put them into a directory by themselves with a .htaccess file that blocks all communication. For example,

Order deny,allow
Deny from all

Your web server, and therefore your server side language, will still be able to read them because the directory's local permissions allow the web server to read and execute the files.

How to get index of object by its property in JavaScript?

As the other answers suggest, looping through the array is probably the best way. But I would put it in it's own function, and make it a little more abstract:

function findWithAttr(array, attr, value) {
    for(var i = 0; i < array.length; i += 1) {
        if(array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}

var Data = [
    {id_list: 2, name: 'John', token: '123123'},
    {id_list: 1, name: 'Nick', token: '312312'}
];

With this, not only can you find which one contains 'John' but you can find which contains the token '312312':

findWithAttr(Data, 'name', 'John'); // returns 0
findWithAttr(Data, 'token', '312312'); // returns 1
findWithAttr(Data, 'id_list', '10'); // returns -1

EDIT: Updated function to return -1 when not found so it follows the same construct as Array.prototype.indexOf()

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

Please take a look at Zdenek Kalal's Predator tracker. It requires some training, but it can actively learn how the tracked object looks at different orientations and scales and does it in realtime!

The source code is available on his site. It's in MATLAB, but perhaps there is a Java implementation already done by a community member. I have succesfully re-implemented the tracker part of TLD in C#. If I remember correctly, TLD is using Ferns as the keypoint detector. I use either SURF or SIFT instead (already suggested by @stacker) to reacquire the object if it was lost by the tracker. The tracker's feedback makes it easy to build with time a dynamic list of sift/surf templates that with time enable reacquiring the object with very high precision.

If you're interested in my C# implementation of the tracker, feel free to ask.

C#: How do you edit items and subitems in a listview?

Click the items in the list view. Add a button that will edit the selected items. Add the code

try
{              
    LSTDEDUCTION.SelectedItems[0].SubItems[1].Text = txtcarName.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[0].Text = txtcarBrand.Text;
    LSTDEDUCTION.SelectedItems[0].SubItems[2].Text = txtCarName.Text;
}
catch{}

Vue js error: Component template should contain exactly one root element

I was confused as I knew VueJS should only contain 1 root element and yet I was still getting this same "template syntax error Component template should contain exactly one root element..." error on an extremely simple component. Turns out I had just mispelled </template> as </tempate> and that was giving me this same error in a few files I copied and pasted. In summary, check your syntax for any mispellings in your component.

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

The accepted answer in 2008 recommended SIGAR. However, as a comment from 2014 (@Alvaro) says:

Be careful when using Sigar, there are problems on x64 machines... Sigar 1.6.4 is crashing: EXCEPTION_ACCESS_VIOLATION and it seems the library doesn't get updated since 2010

My recommendation is to use https://github.com/oshi/oshi

Or the answer mentioned above.

How to generate a HTML page dynamically using PHP?

I suggest you to use URL rewrite mod is enough for your problem,I have the same problem but using URL rewrite mod and getting good SEO response. I can give you a small example. Example is that you consider WordPress , here the data is stored in database but using URL rewrite mod many WordPress websites getting good responses from Google and got rank also.

Example: wordpress url with out url rewrite mod -- domain.com/?p=123 after url rewrite mode -- domain.com/{title of article} like domain.com/seo-url-rewrite-mod

i think you have understood what i want to say you

jQuery UI DatePicker to show month year only

If you are looking for a month picker try this jquery.mtz.monthpicker

This worked for me well.

options = {
    pattern: 'yyyy-mm', // Default is 'mm/yyyy' and separator char is not mandatory
    selectedYear: 2010,
    startYear: 2008,
    finalYear: 2012,
    monthNames: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
};

$('#custom_widget').monthpicker(options);

How to do the Recursive SELECT query in MySQL?

leftclickben answer worked for me, but I wanted a path from a given node back up the tree to the root, and these seemed to be going the other way, down the tree. So, I had to flip some of the fields around and renamed for clarity, and this works for me, in case this is what anyone else wants too--

item | parent
-------------
1    | null
2    | 1
3    | 1
4    | 2
5    | 4
6    | 3

and

select t.item_id as item, @pv:=t.parent as parent
from (select * from item_tree order by item_id desc) t
join
(select @pv:=6)tmp
where t.item_id=@pv;

gives:

item | parent
-------------
6    | 3
3    | 1
1    | null

Internet Explorer cache location

If it's been moved you can also (in IE 11, and I'm pretty sure this translates back to at least 10):

  • Tools - Internet Options
  • Under Browsing history click Settings
  • Under Current location it shows the directory name

Note: The View files button will open a Windows Explorer window there.

For example, mine shows C:\BrowserCache\IE\Temporary Internet Files

What is the "-->" operator in C/C++?

It's equivalent to

while (x-- > 0)

x-- (post decrement) is equivalent to x = x-1 so, the code transforms to:

while(x > 0) {
    x = x-1;
    // logic
}
x--;   // The post decrement done when x <= 0

Emulator: ERROR: x86 emulation currently requires hardware acceleration

This answer works for latest update on Windows 10 version 1709. Not tried with other version. But i hope it'll work.

I also ran into similar issue in my windows 10 system. I disabled Hyper-V and I tried all the answers posted here. But after that also i faced the same issue. So after lot of try, made it work using an documentation available in haxm manual. The document menntioned to use a tool named Device Guard and Credential Guard hardware readiness tool provided by Microsoft to disable Hyper-V along with some other features(Remember not only Hyper-V. So little cautios) completely. Follow the below steps to do that.

  1. Download the latest version of the tool from here.
  2. Unzip.
  3. Open an elevated (i.e. Run as administrator) Command Prompt and run the below command by changing the extrated path and the respective version number.

@powershell -ExecutionPolicy RemoteSigned -Command "X:\path\to\dgreadiness_v3.6\DG_Readiness_Tool_v3.6.ps1 -Disable"

  1. Reboot.

Then if you try to install intel haxm, it'll work.

In case of latest update check the docs available in official intel haxm development link.

Hope it helps someone.

When using a Settings.settings file in .NET, where is the config actually stored?

I know it's already answered but couldn't you just synchronize the settings in the settings designer to move back to your default settings?

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Your syntax isn't quite right: you need to list the fields in order before the INTO, and the corresponding target variables after:

SELECT Id, dateCreated
INTO iId, dCreate
FROM products
WHERE pName = iName

write multiple lines in a file in python

with open('target.txt','w') as out:
    line1 = raw_input("line 1: ")
    line2 = raw_input("line 2: ")
    line3 = raw_input("line 3: ")
    print("I'm going to write these to the file.")
    out.write('{}\n{}\n{}\n'.format(line1,line2,line3))

How to assign an exec result to a sql variable?

declare @EventId int

CREATE TABLE #EventId (EventId int)

insert into #EventId exec rptInputEventId

set @EventId = (select * from #EventId)

drop table #EventId 

Can't stop rails server

check the /tmp/tmp/server.pid

there is a pid inside.

Usually, I ill do "kill -9 THE_PID" in the cmd

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

This error occurs if you are trying to set variable of type DateTime to null. Declare the variable as nullable, i.e. DateTime? . This will solve the problem.

How to place the ~/.composer/vendor/bin directory in your PATH?

The Composer bin directory is set and stored in bin-dir config variable and can be different depending on your setup. Running the command composer global config bin-dir --absolute will tell you the absolute path to your global composer bin directory. Using this command you can modify your .bash_profile to add it to your PATH exactly how it is configured.

# Add Composer bin-dir to PATH if it is installed.
command -v composer >/dev/null 2>&1 && {
        COMPOSER_BIN_DIR=$(composer global config bin-dir --absolute 2> /dev/null)
        PATH="$PATH:$COMPOSER_BIN_DIR";
}
export PATH

Highest Salary in each department

If you just want to get the highest salary from that table, by department:

SELECT MAX(Salary) FROM TableName GROUP BY DeptID

iptables LOG and DROP in one rule

Example:

iptables -A INPUT -j LOG --log-prefix "INPUT:DROP:" --log-level 6
iptables -A INPUT -j DROP

Log Exampe:

Feb 19 14:18:06 servername kernel: INPUT:DROP:IN=eth1 OUT= MAC=aa:bb:cc:dd:ee:ff:11:22:33:44:55:66:77:88 SRC=x.x.x.x DST=x.x.x.x LEN=48 TOS=0x00 PREC=0x00 TTL=117 ID=x PROTO=TCP SPT=x DPT=x WINDOW=x RES=0x00 SYN URGP=0

Other options:

   LOG
       Turn on kernel logging of matching packets.  When this option 
       is set for a rule, the Linux kernel will print some 
       information  on  all  matching  packets
       (like most IP header fields) via the kernel log (where it can 
       be read with dmesg or syslogd(8)).  This is a "non-terminating 
       target", i.e. rule traversal
       continues at the next rule.  So if you want to LOG the packets 
       you refuse, use two separate rules with the same matching 
       criteria, first using target LOG
       then DROP (or REJECT).

       --log-level level
              Level of logging (numeric or see syslog.conf(5)).

       --log-prefix prefix
              Prefix log messages with the specified prefix; up to 29 
              letters long, and useful for distinguishing messages in 
              the logs.

       --log-tcp-sequence
              Log TCP sequence numbers. This is a security risk if the 
              log is readable by users.

       --log-tcp-options
              Log options from the TCP packet header.

       --log-ip-options
              Log options from the IP packet header.

       --log-uid
              Log the userid of the process which generated the packet.

When to use: Java 8+ interface default method, vs. abstract method

These two are quite different:

Default methods are to add external functionality to existing classes without changing their state.

And abstract classes are a normal type of inheritance, they are normal classes which are intended to be extended.

Reset IntelliJ UI to Default

From the main menu, select File | Manage IDE Settings | Restore Default Settings.

Alternatively, press Shift twice and type Restore default settings

How to drop a unique constraint from table column?

I have stopped on the script like below (as I have only one non-clustered unique index in this table):

declare @table_name nvarchar(256)  
declare @col_name nvarchar(256)  
declare @Command  nvarchar(1000)  

set @table_name = N'users'
set @col_name = N'login'

select @Command = 'ALTER TABLE ' + @table_name + ' drop constraint ' + d.name
    from sys.tables t join sys.indexes d on d.object_id = t.object_id  
    where t.name = @table_name and d.type=2 and d.is_unique=1

--print @Command

execute (@Command)

Has anyone comments if this solution is acceptable? Any pros and cons?

Thanks.

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 do I do word Stemming or Lemmatization?

Look into WordNet, a large lexical database for the English language:

http://wordnet.princeton.edu/

There are APIs for accessing it in several languages.

How to get docker-compose to always re-create containers from fresh images?

By current official documentation there is a short cut that stops and removes containers, networks, volumes, and images created by up, if they are already stopped or partially removed and so on, then it will do the trick too:

docker-compose down

Then if you have new changes on your images or Dockerfiles use:

docker-compose build --no-cache

Finally:docker-compose up

In one command: docker-compose down && docker-compose build --no-cache && docker-compose up

React Native Error: ENOSPC: System limit for number of file watchers reached

Linux uses the inotify package to observe filesystem events, individual files or directories.

Since React / Angular hot-reloads and recompiles files on save it needs to keep track of all project's files. Increasing the inotify watch limit should hide the warning messages.

You could try editing

# insert the new value into the system config
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

# check that the new value was applied
cat /proc/sys/fs/inotify/max_user_watches

# config variable name (not runnable)
fs.inotify.max_user_watches=524288

javac option to compile all java files under a given directory recursively

I would also suggest using some kind of build tool (Ant or Maven, Ant is already suggested and is easier to start with) or an IDE that handles the compilation (Eclipse uses incremental compilation with reconciling strategy, and you don't even have to care to press any "Compile" buttons).

Using Javac

If you need to try something out for a larger project and don't have any proper build tools nearby, you can always use a small trick that javac offers: the classnames to compile can be specified in a file. You simply have to pass the name of the file to javac with the @ prefix.

If you can create a list of all the *.java files in your project, it's easy:

# Linux / MacOS
$ find -name "*.java" > sources.txt
$ javac @sources.txt

:: Windows
> dir /s /B *.java > sources.txt
> javac @sources.txt
  • The advantage is that is is a quick and easy solution.
  • The drawback is that you have to regenerate the sources.txt file each time you create a new source or rename an existing one file which is an easy to forget (thus error-prone) and tiresome task.

Using a build tool

On the long run it is better to use a tool that was designed to build software.

Using Ant

If you create a simple build.xml file that describes how to build the software:

<project default="compile">
    <target name="compile">
        <mkdir dir="bin"/>
        <javac srcdir="src" destdir="bin"/>
    </target>
</project>

you can compile the whole software by running the following command:

$ ant
  • The advantage is that you are using a standard build tool that is easy to extend.
  • The drawback is that you have to download, set up and learn an additional tool. Note that most of the IDEs (like NetBeans and Eclipse) offer great support for writing build files so you don't have to download anything in this case.

Using Maven

Maven is not that trivial to set up and work with, but learning it pays well. Here's a great tutorial to start a project within 5 minutes.

  • It's main advantage (for me) is that it handles dependencies too, so you won't need to download any more Jar files and manage them by hand and I found it more useful for building, packaging and testing larger projects.
  • The drawback is that it has a steep learning curve, and if Maven plugins like to suppress errors :-) Another thing is that quite a lot of tools also operate with Maven repositories (like Sbt for Scala, Ivy for Ant, Graddle for Groovy).

Using an IDE

Now that what could boost your development productivity. There are a few open source alternatives (like Eclipse and NetBeans, I prefer the former) and even commercial ones (like IntelliJ) which are quite popular and powerful.

They can manage the project building in the background so you don't have to deal with all the command line stuff. However, it always comes handy if you know what actually happens in the background so you can hunt down occasional errors like a ClassNotFoundException.

One additional note

For larger projects, it is always advised to use an IDE and a build tool. The former boosts your productivity, while the latter makes it possible to use different IDEs with the project (e.g., Maven can generate Eclipse project descriptors with a simple mvn eclipse:eclipse command). Moreover, having a project that can be tested/built with a single line command is easy to introduce to new colleagues and into a continuous integration server for example. Piece of cake :-)

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

Iterating over Typescript Map

Per the TypeScript 2.3 release notes on "New --downlevelIteration":

for..of statements, Array Destructuring, and Spread elements in Array, Call, and New expressions support Symbol.iterator in ES5/E3 if available when using --downlevelIteration

This is not enabled by default! Add "downlevelIteration": true to your tsconfig.json, or pass --downlevelIteration flag to tsc, to get full iterator support.

With this in place, you can write for (let keyval of myMap) {...} and keyval's type will be automatically inferred.


Why is this turned off by default? According to TypeScript contributor @aluanhaddad,

It is optional because it has a very significant impact on the size of generated code, and potentially on performance, for all uses of iterables (including arrays).

If you can target ES2015 ("target": "es2015" in tsconfig.json or tsc --target ES2015) or later, enabling downlevelIteration is a no-brainer, but if you're targeting ES5/ES3, you might benchmark to ensure iterator support doesn't impact performance (if it does, you might be better off with Array.from conversion or forEach or some other workaround).

How to set a value to a file input in HTML?

As everyone else here has stated: You cannot upload just any file automatically with JavaScript.

HOWEVER! If you have access to the information you want to send in your code (i.e., not C:\passwords.txt), then you can upload it as a blob-type, and then treat it as a file.

What the server will end up seeing will be indistinguishable from someone actually setting the value of <input type="file" />. The trick, ultimately, is to begin a new XMLHttpRequest() with the server...

function uploadFile (data) {
        // define data and connections
    var blob = new Blob([JSON.stringify(data)]);
    var url = URL.createObjectURL(blob);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'myForm.php', true);
    
        // define new form
    var formData = new FormData();
    formData.append('someUploadIdentifier', blob, 'someFileName.json');
        
        // action after uploading happens
    xhr.onload = function(e) {
        console.log("File uploading completed!");
    };
    
        // do the uploading
    console.log("File uploading started!");
    xhr.send(formData);
}

    // This data/text below is local to the JS script, so we are allowed to send it!
uploadFile({'hello!':'how are you?'});

So, what could you possibly use this for? I use it for uploading HTML5 canvas elements as jpg's. This saves the user the trouble of having to open a file input element, only to select the local, cached image that they just resized, modified, etc.. But it should work for any file type.

select2 onchange event only works once

Set your .on listener to check for specific select2 events. The "change" event is the same as usual but the others are specific to the select2 control thus:

  • change
  • select2-opening
  • select2-open
  • select2-close
  • select2-highlight
  • select2-selecting
  • select2-removed
  • select2-loaded
  • select2-focus

The names are self-explanatory. For example, select2-focus fires when you give focus to the control.

"This SqlTransaction has completed; it is no longer usable."... configuration error?

I believe this error message is due to a "zombie transaction".

Look for possible areas where the transacton is being committed twice (or rolled back twice, or rolled back and committed, etc.). Does the .Net code commit the transaction after the SP has already committed it? Does the .Net code roll it back on encountering an error, then attempt to roll it back again in a catch (or finally) clause?

It's possible an error condition was never being hit on the old server, and thus the faulty "double rollback" code was never hit. Maybe now you have a situation where there is some configuration error on the new server, and now the faulty code is getting hit via exception handling.

Can you debug into the error code? Do you have a stack trace?

How can I put a database under git (version control)?

I would recommend neXtep for version controlling the database it has got a good set of documentation and forums that explains how to install and the errors encountered. I have tested it for postgreSQL 9.1 and 9.3, i was able to get it working for 9.1 but for 9.3 it doesn't seems to work.

Conversion failed when converting date and/or time from character string in SQL SERVER 2008

DECLARE @FromDate DATETIME

SET @FromDate =  'Jan 10 2016 12:00AM'

DECLARE @ToDate DATETIME
SET @ToDate = 'Jan 10 2017 12:00AM'

DECLARE @Dynamic_Qry nvarchar(Max) =''

SET @Dynamic_Qry='SELECT

(CONVERT(DATETIME,(SELECT 
     CASE WHEN (  ''IssueDate''   =''IssueDate'') THEN 
               EMP_DOCUMENT.ISSUE_DATE 
          WHEN (''IssueDate'' =''ExpiryDate'' ) THEN       
               EMP_DOCUMENT.EXPIRY_DATE ELSE EMP_DOCUMENT.APPROVED_ON END   
          CHEKDATE ), 101)  

)FROM CR.EMP_DOCUMENT  as EMP_DOCUMENT WHERE 1=1 

AND  (
      CONVERT(DATETIME,(SELECT 
        CASE WHEN (  ''IssueDate''   =''IssueDate'') THEN
                 EMP_DOCUMENT.ISSUE_DATE 
             WHEN (''IssueDate'' =''ExpiryDate'' ) THEN EMP_DOCUMENT.EXPIRY_DATE 
             ELSE EMP_DOCUMENT.APPROVED_ON END 
             CHEKDATE ), 101)  
) BETWEEN  '''+ CONVERT(CHAR(10), @FromDate, 126) +'''  AND '''+CONVERT(CHAR(10),  @ToDate , 126
)
+'''  
'

print @Dynamic_Qry

EXEC(@Dynamic_Qry) 

How to retrieve available RAM from Windows command line?

PS C:\Users\Rack> systeminfo | findstr "System Memory"
System Boot Time:          5/5/2016, 11:10:41 PM
System Manufacturer:       VMware, Inc.
System Model:              VMware Virtual Platform
System Type:               x64-based PC
System Directory:          C:\Windows\system32
System Locale:             en-us;English (United States)
Total Physical Memory:     40,959 MB
Available Physical Memory: 36,311 MB
Virtual Memory: Max Size:  45,054 MB
Virtual Memory: Available: 41,390 MB
Virtual Memory: In Use:    3,664 MB

What are Runtime.getRuntime().totalMemory() and freeMemory()?

The names and values are confusing. If you are looking for the total free memory you will have to calculate this value by your self. It is not what you get from freeMemory();.

See the following guide:

Total designated memory, this will equal the configured -Xmx value:

Runtime.getRuntime().maxMemory();

Current allocated free memory, is the current allocated space ready for new objects. Caution this is not the total free available memory:

Runtime.getRuntime().freeMemory();

Total allocated memory, is the total allocated space reserved for the java process:

Runtime.getRuntime().totalMemory();

Used memory, has to be calculated:

usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

Total free memory, has to be calculated:

freeMemory = Runtime.getRuntime().maxMemory() - usedMemory;

A picture may help to clarify:

java runtime memory

How can I remove a key from a Python dictionary?

Specifically to answer "is there a one line way of doing this?"

if 'key' in my_dict: del my_dict['key']

...well, you asked ;-)

You should consider, though, that this way of deleting an object from a dict is not atomic—it is possible that 'key' may be in my_dict during the if statement, but may be deleted before del is executed, in which case del will fail with a KeyError. Given this, it would be safest to either use dict.pop or something along the lines of

try:
    del my_dict['key']
except KeyError:
    pass

which, of course, is definitely not a one-liner.