Programs & Examples On #Over the air

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

How to replace DOM element in place using Javascript?

Example for replacing LI elements

function (element) {
    let li = element.parentElement;
    let ul = li.parentNode;   
    if (li.nextSibling.nodeName === 'LI') {
        let li_replaced = ul.replaceChild(li, li.nextSibling);
        ul.insertBefore(li_replaced, li);
    }
}

How to remove leading zeros using C#

This Regex let you avoid wrong result with digits which consits only from zeroes "0000" and work on digits of any length:

using System.Text.RegularExpressions;

/*
00123 => 123
00000 => 0
00000a => 0a
00001a => 1a
00001a => 1a
0000132423423424565443546546356546454654633333a => 132423423424565443546546356546454654633333a
*/

Regex removeLeadingZeroesReg = new Regex(@"^0+(?=\d)");
var strs = new string[]
{
    "00123",
    "00000",
    "00000a",
    "00001a",
    "00001a",
    "0000132423423424565443546546356546454654633333a",
};
foreach (string str in strs)
{
    Debug.Print(string.Format("{0} => {1}", str, removeLeadingZeroesReg.Replace(str, "")));
}

And this regex will remove leading zeroes anywhere inside string:

new Regex(@"(?<!\d)0+(?=\d)");
//  "0000123432 d=0 p=002 3?0574 m=600"
//     => "123432 d=0 p=2 3?574 m=600"

displaying a string on the textview when clicking a button in android

Try this

public void onClick(View view){
    txtView.setText("hello");

    //printmyname();
    Toast.makeText(NameonbuttonclickActivity.this, "hello", Toast.LENGTH_LONG).show();
}

Also in toast use "Hello"

Rails 4 - Strong Parameters - Nested Objects

Permitting a nested object :

params.permit( {:school => [:id , :name]}, 
               {:student => [:id, 
                            :name, 
                            :address, 
                            :city]},
                {:records => [:marks, :subject]})

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

A check of ibliblio and java.net repositories reveal that jmx related jar is not present in either. I think you should manually download jms and install them locally as discussed here.

Parsing XML with namespace in Python via 'ElementTree'

ElementTree is not too smart about namespaces. You need to give the .find(), findall() and iterfind() methods an explicit namespace dictionary. This is not documented very well:

namespaces = {'owl': 'http://www.w3.org/2002/07/owl#'} # add more as needed

root.findall('owl:Class', namespaces)

Prefixes are only looked up in the namespaces parameter you pass in. This means you can use any namespace prefix you like; the API splits off the owl: part, looks up the corresponding namespace URL in the namespaces dictionary, then changes the search to look for the XPath expression {http://www.w3.org/2002/07/owl}Class instead. You can use the same syntax yourself too of course:

root.findall('{http://www.w3.org/2002/07/owl#}Class')

If you can switch to the lxml library things are better; that library supports the same ElementTree API, but collects namespaces for you in a .nsmap attribute on elements.

Get encoding of a file in Windows

The (Linux) command-line tool 'file' is available on Windows via GnuWin32:

http://gnuwin32.sourceforge.net/packages/file.htm

If you have git installed, it's located in C:\Program Files\git\usr\bin.

Example:

    C:\Users\SH\Downloads\SquareRoot>file *
    _UpgradeReport_Files;         directory
    Debug;                        directory
    duration.h;                   ASCII C++ program text, with CRLF line terminators
    ipch;                         directory
    main.cpp;                     ASCII C program text, with CRLF line terminators
    Precision.txt;                ASCII text, with CRLF line terminators
    Release;                      directory
    Speed.txt;                    ASCII text, with CRLF line terminators
    SquareRoot.sdf;               data
    SquareRoot.sln;               UTF-8 Unicode (with BOM) text, with CRLF line terminators
    SquareRoot.sln.docstates.suo; PCX ver. 2.5 image data
    SquareRoot.suo;               CDF V2 Document, corrupt: Cannot read summary info
    SquareRoot.vcproj;            XML  document text
    SquareRoot.vcxproj;           XML document text
    SquareRoot.vcxproj.filters;   XML document text
    SquareRoot.vcxproj.user;      XML document text
    squarerootmethods.h;          ASCII C program text, with CRLF line terminators
    UpgradeLog.XML;               XML  document text

    C:\Users\SH\Downloads\SquareRoot>file --mime-encoding *
    _UpgradeReport_Files;         binary
    Debug;                        binary
    duration.h;                   us-ascii
    ipch;                         binary
    main.cpp;                     us-ascii
    Precision.txt;                us-ascii
    Release;                      binary
    Speed.txt;                    us-ascii
    SquareRoot.sdf;               binary
    SquareRoot.sln;               utf-8
    SquareRoot.sln.docstates.suo; binary
    SquareRoot.suo;               CDF V2 Document, corrupt: Cannot read summary infobinary
    SquareRoot.vcproj;            us-ascii
    SquareRoot.vcxproj;           utf-8
    SquareRoot.vcxproj.filters;   utf-8
    SquareRoot.vcxproj.user;      utf-8
    squarerootmethods.h;          us-ascii
    UpgradeLog.XML;               us-ascii

How to Select Every Row Where Column Value is NOT Distinct

This is significantly faster than the EXISTS way:

SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN
  (SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1)

Count Vowels in String Python

count = 0
name=raw_input("Enter your name:")
for letter in name:
    if(letter in ['A','E','I','O','U','a','e','i','o','u']):
       count=count + 1
print "You have", count, "vowels in your name."

Javascript: Call a function after specific time period

Execute function FetchData() once after 1000 milliseconds:

setTimeout(FetchData,1000);

Execute function FetchData() repeatedly every 1000 milliseconds:

setInterval(FetchData,1000);

MySQL error 1449: The user specified as a definer does not exist

Follow these steps:

  1. Go to PHPMyAdmin
  2. Select Your Database
  3. Select your table
  4. On the top menu Click on 'Triggers'
  5. Click on 'Edit' to edit trigger
  6. Change definer from [user@localhost] to root@localhost

Hope it helps

Java way to check if a string is palindrome

 public boolean isPalindrom(String text) {
    StringBuffer stringBuffer = new StringBuffer(text);
     return stringBuffer.reverse().toString().equals(text);
}

Bash script plugin for Eclipse?

ShellEd looks promising, does syntax highlighting, and has positive reviews, although I've not tried it myself. It was approved for distro inclusion by Redhat. There's a little more info on the ShellEd plugin page on the Eclipse site, and installation instructions on their wiki.

Note that if you're not running an up-to-date version of Eclipse (as of this writing, Juno) you'll need to use an older version, for instance 2.0.1 is compatible with Indigo.

List all kafka topics

You can try using the below two command and list all Kafka topic

  • bin/kafka-topics.sh --describe --zookeeper 192.168.0.142:2181,192.168.9.115:2181,192.168.4.57:2181
  • bin/kafka-topics.sh --zookeeper 192.168.0.142:2181,192.168.9.115:2181,192.168.4.57:218 --list

How to state in requirements.txt a direct github source

First, install with git+git or git+https, in any way you know. Example of installing kronok's branch of the brabeion project:

pip install -e git+https://github.com/kronok/brabeion.git@12efe6aa06b85ae5ff725d3033e38f624e0a616f#egg=brabeion

Second, use pip freeze > requirements.txt to get the right thing in your requirements.txt. In this case, you will get

-e git+https://github.com/kronok/brabeion.git@12efe6aa06b85ae5ff725d3033e38f624e0a616f#egg=brabeion-master

Third, test the result:

pip uninstall brabeion
pip install -r requirements.txt

Difference between a View's Padding and Margin

In simple words:
padding changes the size of the box (with something).
margin changes the space between different boxes

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

All of this assumes core.autocrlf=true

Original error:

warning: LF will be replaced by CRLF
The file will have its original line endings in your working directory.

What the error SHOULD read:

warning: LF will be replaced by CRLF in your working directory
The file will have its original LF line endings in the git repository

Explanation here:

The side-effect of this convenient conversion, and this is what the warning you're seeing is about, is that if a text file you authored originally had LF endings instead of CRLF, it will be stored with LF as usual, but when checked out later it will have CRLF endings. For normal text files this is usually just fine. The warning is a "for your information" in this case, but in case git incorrectly assesses a binary file to be a text file, it is an important warning because git would then be corrupting your binary file.

Basically, a local file that was previously LF will now have CRLF locally

Sublime Text 3, convert spaces to tabs

You can use the command palette to solve this issue.

Step 1: Ctrl + Shift + P (to activate the command palette)

Step 2: Type "Indentation", Choose "Indentation: Convert to Tabs"

How to access the SMS storage on Android?

You are going to need to call the SmsManager class. You are probably going to need to use the STATUS_ON_ICC_READ constant and maybe put what you get there into your apps local db so that you can keep track of what you have already read vs the new stuff for your app to parse through. BUT bear in mind that you have to declare the use of the class in your manifest, so users will see that you have access to their SMS called out in the permissions dialogue they get when they install. Seeing SMS access is unusual and could put some users off. Good luck.

Here is the link that goes into depth on the Sms Manager

(WAMP/XAMP) send Mail using SMTP localhost

If any one of you are getting error like following after following answer given by Afwe Wef

 Warning: mail() [<a href='function.mail'>function.mail</a>]: SMTP server response:

 550 The address is not valid. in c:\wamp\www\email.php

Go to php.ini

; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = [email protected]

Enter [email protected] as your email id which you used to configure the hMailserver in front of sendmail_from .

your problem will be solved.

Tested on Wamp server2.2(Apache 2.2.22, php 5.3.13) on windows 8

If you are also getting following error

"APPLICATION"   6364    "2014-03-24 13:13:33.979"   "SMTPDeliverer - Message 2: Relaying to host smtp.gmail.com."
"APPLICATION"   6364    "2014-03-24 13:13:34.415"   "SMTPDeliverer - Message 2: Message could not be delivered. Scheduling it for later delivery in 60 minutes."
"APPLICATION"   6364    "2014-03-24 13:13:34.430"   "SMTPDeliverer - Message 2: Message delivery thread completed."

You might have forgot to change the port from 25 to 465

How to stop "setInterval"

This is based on CMS's answer. The question asked for the timer to be restarted on the blur and stopped on the focus, so I moved it around a little:

$(function () {
  var timerId = 0;

  $('textarea').focus(function () {
    clearInterval(timerId);
  });

  $('textarea').blur(function () {
    timerId = setInterval(function () {
     //some code here 
    }, 1000);
  });
});

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

How to save an image locally using Python whose URL address I already know?

Python 3

urllib.request — Extensible library for opening URLs

from urllib.error import HTTPError
from urllib.request import urlretrieve

try:
    urlretrieve(image_url, image_local_path)
except FileNotFoundError as err:
    print(err)   # something wrong with local path
except HTTPError as err:
    print(err)  # something wrong with url

Getting current directory in .NET web application

Use this code:

 HttpContext.Current.Server.MapPath("~")

Detailed Reference:

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let's say you pointed a web site application (http://www.example.com/) to

C:\Inetpub\wwwroot

and installed your shop application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop

For example, if you call Server.MapPath in following request:

http://www.example.com/shop/products/GetProduct.aspx?id=2342

then:

Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop

If Path starts with either a forward (/) or backward slash (), the MapPath method returns a path as if Path were a full, virtual path.

If Path doesn't start with a slash, the MapPath method returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Footnotes

Server.MapPath(null) and Server.MapPath("") will produce this effect too.

jQuery javascript regex Replace <br> with \n

a cheap and nasty would be:

jQuery("#myDiv").html().replace("<br>", "\n").replace("<br />", "\n")

EDIT

jQuery("#myTextArea").val(
    jQuery("#myDiv").html()
        .replace(/\<br\>/g, "\n")
        .replace(/\<br \/\>/g, "\n")
);

Also created a jsfiddle if needed: http://jsfiddle.net/2D3xx/

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

You need to use the CONCAT() function in MySQL for string concatenation:

UPDATE categories SET code = CONCAT(code, '_standard') WHERE id = 1;

Retrieve filename from file descriptor in C

As Tyler points out, there's no way to do what you require "directly and reliably", since a given FD may correspond to 0 filenames (in various cases) or > 1 (multiple "hard links" is how the latter situation is generally described). If you do still need the functionality with all the limitations (on speed AND on the possibility of getting 0, 2, ... results rather than 1), here's how you can do it: first, fstat the FD -- this tells you, in the resulting struct stat, what device the file lives on, how many hard links it has, whether it's a special file, etc. This may already answer your question -- e.g. if 0 hard links you will KNOW there is in fact no corresponding filename on disk.

If the stats give you hope, then you have to "walk the tree" of directories on the relevant device until you find all the hard links (or just the first one, if you don't need more than one and any one will do). For that purpose, you use readdir (and opendir &c of course) recursively opening subdirectories until you find in a struct dirent thus received the same inode number you had in the original struct stat (at which time if you want the whole path, rather than just the name, you'll need to walk the chain of directories backwards to reconstruct it).

If this general approach is acceptable, but you need more detailed C code, let us know, it won't be hard to write (though I'd rather not write it if it's useless, i.e. you cannot withstand the inevitably slow performance or the possibility of getting != 1 result for the purposes of your application;-).

Why XML-Serializable class need a parameterless constructor

This is a limitation of XmlSerializer. Note that BinaryFormatter and DataContractSerializer do not require this - they can create an uninitialized object out of the ether and initialize it during deserialization.

Since you are using xml, you might consider using DataContractSerializer and marking your class with [DataContract]/[DataMember], but note that this changes the schema (for example, there is no equivalent of [XmlAttribute] - everything becomes elements).

Update: if you really want to know, BinaryFormatter et al use FormatterServices.GetUninitializedObject() to create the object without invoking the constructor. Probably dangerous; I don't recommend using it too often ;-p See also the remarks on MSDN:

Because the new instance of the object is initialized to zero and no constructors are run, the object might not represent a state that is regarded as valid by that object. The current method should only be used for deserialization when the user intends to immediately populate all fields. It does not create an uninitialized string, since creating an empty instance of an immutable type serves no purpose.

I have my own serialization engine, but I don't intend making it use FormatterServices; I quite like knowing that a constructor (any constructor) has actually executed.

How to include files outside of Docker's build context?

I believe the simpler workaround would be to change the 'context' itself.

So, for example, instead of giving:

docker build -t hello-demo-app .

which sets the current directory as the context, let's say you wanted the parent directory as the context, just use:

docker build -t hello-demo-app ..

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

This one disables all bogus verbs and only allows GET and POST

<system.webServer>
  <security>
    <requestFiltering>
      <verbs allowUnlisted="false">
    <clear/>
    <add verb="GET" allowed="true"/>
    <add verb="POST" allowed="true"/>
      </verbs>
    </requestFiltering>
  </security>
</system.webServer>

Failed to add the host to the list of know hosts

I was having this issue and found that within ~/.ssh/config I had a line that read:

UserKnownHostsFile=/home/.ssh-agent/known_hosts

I just modified this line to read:

UserKnownHostsFile=~/.ssh/known_hosts

That fixed the problem for me.

Export to csv in jQuery

Hope the following demo can help you out.

_x000D_
_x000D_
$(function() {_x000D_
  $("button").on('click', function() {_x000D_
    var data = "";_x000D_
    var tableData = [];_x000D_
    var rows = $("table tr");_x000D_
    rows.each(function(index, row) {_x000D_
      var rowData = [];_x000D_
      $(row).find("th, td").each(function(index, column) {_x000D_
        rowData.push(column.innerText);_x000D_
      });_x000D_
      tableData.push(rowData.join(","));_x000D_
    });_x000D_
    data += tableData.join("\n");_x000D_
    $(document.body).append('<a id="download-link" download="data.csv" href=' + URL.createObjectURL(new Blob([data], {_x000D_
      type: "text/csv"_x000D_
    })) + '/>');_x000D_
_x000D_
_x000D_
    $('#download-link')[0].click();_x000D_
    $('#download-link').remove();_x000D_
  });_x000D_
});
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
  border: 1px solid #aaa;_x000D_
  padding: 0.5rem;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
td {_x000D_
  font-size: 0.875rem;_x000D_
}_x000D_
_x000D_
.btn-group {_x000D_
  padding: 1rem 0;_x000D_
}_x000D_
_x000D_
button {_x000D_
  background-color: #fff;_x000D_
  border: 1px solid #000;_x000D_
  margin-top: 0.5rem;_x000D_
  border-radius: 3px;_x000D_
  padding: 0.5rem 1rem;_x000D_
  font-size: 1rem;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
  cursor: pointer;_x000D_
  background-color: #000;_x000D_
  color: #fff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id='PrintDiv'>_x000D_
  <table id="mainTable">_x000D_
    <tr>_x000D_
      <td>Col1</td>_x000D_
      <td>Col2</td>_x000D_
      <td>Col3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Val1</td>_x000D_
      <td>Val2</td>_x000D_
      <td>Val3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Val11</td>_x000D_
      <td>Val22</td>_x000D_
      <td>Val33</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Val111</td>_x000D_
      <td>Val222</td>_x000D_
      <td>Val333</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>_x000D_
_x000D_
<div class="btn-group">_x000D_
  <button>csv</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using a scanner to accept String input and storing in a String Array

Would this work better?

import java.util.Scanner;

public class Work {

public static void main(String[] args){

    System.out.println("Please enter the following information");

    String name = "0";
    String num = "0";
    String address = "0";

    int i = 0;

    Scanner input = new Scanner(System.in);

    //The Arrays
    String [] contactName = new String [7];
    String [] contactNum = new String [7];
    String [] contactAdd = new String [7];

    //I set these as the Array titles
    contactName[0] = "Name";
    contactNum[0] = "Phone Number";
    contactAdd[0] = "Address";

    //This asks for the information and builds an Array for each
    //i -= i resets i back to 0 so the arrays are not 7,14,21+
    while (i < 6){

        i++;
        System.out.println("Enter contact name." + i);
        name = input.nextLine();
        contactName[i] = name;
    }

    i -= i;
    while (i < 6){
        i++;
        System.out.println("Enter contact number." + i);
        num = input.nextLine();
        contactNum[i] = num;
    }

    i -= i;
    while (i < 6){
        i++;
        System.out.println("Enter contact address." + i);
        num = input.nextLine();
        contactAdd[i] = num;
    }


    //Now lets print out the Arrays
    i -= i;
    while(i < 6){
    i++;
    System.out.print( i + " " + contactName[i] + " / " );
    }

    //These are set to print the array on one line so println will skip a line
    System.out.println();
    i -= i;
    i -= 1;

    while(i < 6){
    i++;

    System.out.print( i + " " + contactNum[i] + " / " );
    }

    System.out.println();
    i -= i;
    i -= 1;

    while(i < 6){
        i++;

    System.out.print( i + " " + contactAdd[i] + " / " );
    }

    System.out.println();

    System.out.println("End of program");

}

}

Can I give the col-md-1.5 in bootstrap?

According to Rex Bloom response I have write a bootstrap helper:

//8,33333333% col-1

.extra-col {
  position: relative;
  width: 100%;
  padding-right: 15px;
  padding-left: 15px;
}

.col-0-5 {
  @extend .extra-col;
  flex: 0 0 4.16666667%;
  max-width: 4.16666667%;
}

.col-1-5 {
  @extend .extra-col;
  flex: 0 0 12.5%;
  max-width: 12.5%;
}

.col-2-5 {
  @extend .extra-col;
  flex: 0 0 20.833333325%;
  max-width: 20.833333325%;
}

.col-3-5 {
  @extend .extra-col;
  flex: 0 0 29.166666655%;
  max-width: 29.166666655%;
}

.col-4-5 {
  @extend .extra-col;
  flex: 0 0 37.499999985%;
  max-width: 37.499999985%;
}

.col-5-5 {
  @extend .extra-col;
  flex: 0 0 45.833333315%;
  max-width: 45.833333315%;
}

.col-6-5 {
  @extend .extra-col;
  flex: 0 0 54.166666645%;
  max-width: 54.166666645%;
}

.col-7-5 {
  @extend .extra-col;
  flex: 0 0 62.499999975%;
  max-width: 62.499999975%;
}

.col-8-5 {
  @extend .extra-col;
  flex: 0 0 70.833333305%;
  max-width: 70.833333305%;
}

.col-9-5 {
  @extend .extra-col;
  flex: 0 0 79.166666635%;
  max-width: 79.166666635%;
}

.col-10-5 {
  @extend .extra-col;
  flex: 0 0 87.499999965%;
  max-width: 87.499999965%;
}

.col-11-5 {
  @extend .extra-col;
  flex: 0 0 95.8333333%;
  max-width: 95.8333333%;
}

Meaning of tilde in Linux bash (not home directory)

Those are the home directories of the users. Try cd ~(your username), for example.

React JS Error: is not defined react/jsx-no-undef

You have to tell it which component you want to import by explicitly giving the class name..in your case it's Map

import Map from './Map';

class App extends Component{
    /*your code here...*/
}

The FastCGI process exited unexpectedly

You might be using C:/[your-php-directory]/php.exe in Handler mapping of IIS just change it C:/[your-php-directory]/php-cgi.exe.

Path of assets in CSS files in Symfony 2

I offen manage css/js plugin with composer which install it under vendor. I symlink those to the web/bundles directory, that's let composer update bundles as needed.

exemple:

1 - symlink once at all (use command fromweb/bundles/

ln -sf vendor/select2/select2/dist/ select2

2 - use asset where needed, in twig template :

{{ asset('bundles/select2/css/fileinput.css) }}

Regards.

Adding script tag to React/JSX

I tried to edit the accepted answer by @Alex McMillan but it won't let me so heres a separate answer where your able to get the value of the library your loading in. A very important distinction that people asked for and I needed for my implementation with stripe.js.

useScript.js

import { useState, useEffect } from 'react'

export const useScript = (url, name) => {

  const [lib, setLib] = useState({})

  useEffect(() => {
    const script = document.createElement('script')

    script.src = url
    script.async = true
    script.onload = () => setLib({ [name]: window[name] })

    document.body.appendChild(script)

    return () => {
      document.body.removeChild(script)
    }
  }, [url])

  return lib

}

usage looks like

const PaymentCard = (props) => {
  const { Stripe } = useScript('https://js.stripe.com/v2/', 'Stripe')
}

NOTE: Saving the library inside an object because often times the library is a function and React will execute the function when storing in state to check for changes -- which will break libs (like Stripe) that expect to be called with specific args -- so we store that in an object to hide that from React and protect library functions from being called.

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

If you are getting following type of error

maven build error

Then do the following steps-->>

  • Go to Windows. Then select Preferences, in Which select java(on the left corner).
  • In java select Installed JREs and check your JRE(if you have correctly installed jdk and defined environment variables correct then you will see the current version of the installed java here)as shown - installed jre

(I have Java 8 installed) Check the check box if it is not checked. Click apply and close.

Now Press Alt+Enter to go into project properties,or go via right clicking on project and select Properties.

In Properties select Java Build Path on left corner

Select Libraries

Check libraries

And click edit(after selecting The JRE System Library...) In edit Click and select Workspace default JRE. Then click Finish

In Order and Export Check the JRE System Library.

Then Finally Apply and close Clean the project and then build it.

Problem Solved..Cheers!!

How can I remove the extension of a filename in a shell script?

As pointed out by Hawker65 in the comment of chepner answer, the most voted solution does neither take care of multiple extensions (such as filename.tar.gz), nor of dots in the rest of the path (such as this.path/with.dots/in.path.name). A possible solution is:

a=this.path/with.dots/in.path.name/filename.tar.gz
echo $(dirname $a)/$(basename $a | cut -d. -f1)

How to do the equivalent of pass by reference for primitives in Java

Java is not call by reference it is call by value only

But all variables of object type are actually pointers.

So if you use a Mutable Object you will see the behavior you want

public class XYZ {

    public static void main(String[] arg) {
        StringBuilder toyNumber = new StringBuilder("5");
        play(toyNumber);
        System.out.println("Toy number in main " + toyNumber);
    }

    private static void play(StringBuilder toyNumber) {
        System.out.println("Toy number in play " + toyNumber);
        toyNumber.append(" + 1");
        System.out.println("Toy number in play after increement " + toyNumber);
    }
}

Output of this code:

run:
Toy number in play 5
Toy number in play after increement 5 + 1
Toy number in main 5 + 1
BUILD SUCCESSFUL (total time: 0 seconds)

You can see this behavior in Standard libraries too. For example Collections.sort(); Collections.shuffle(); These methods does not return a new list but modifies it's argument object.

    List<Integer> mutableList = new ArrayList<Integer>();

    mutableList.add(1);
    mutableList.add(2);
    mutableList.add(3);
    mutableList.add(4);
    mutableList.add(5);

    System.out.println(mutableList);

    Collections.shuffle(mutableList);

    System.out.println(mutableList);

    Collections.sort(mutableList);

    System.out.println(mutableList);

Output of this code:

run:
[1, 2, 3, 4, 5]
[3, 4, 1, 5, 2]
[1, 2, 3, 4, 5]
BUILD SUCCESSFUL (total time: 0 seconds)

Python Hexadecimal

Another solution is:

>>> "".join(list(hex(255))[2:])
'ff'

Probably an archaic answer, but functional.

MySQL: NOT LIKE

categories_posts and categories_news start with substring 'categories_' then it is enough to check that developer_configurations_cms.cfg_name_unique starts with 'categories' instead of check if it contains the given substring. Translating all that into a query:

SELECT *
    FROM developer_configurations_cms

    WHERE developer_configurations_cms.cat_id = '1'
    AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
    AND developer_configurations_cms.cfg_name_unique NOT LIKE 'categories%'

How to split a long array into smaller arrays, with JavaScript

You can take a look at this code . Simple and Effective .

function chunkArrayInGroups(array, unit) {
var results = [],
length = Math.ceil(array.length / unit);

for (var i = 0; i < length; i++) {
    results.push(array.slice(i * unit, (i + 1) * unit));
}
 return results;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

How can I determine if an image has loaded, using Javascript/jQuery?

We developed a page where it loaded a number of images and then performed other functions only after the image was loaded. It was a busy site that generated a lot of traffic. It seems that the following simple script worked on practically all browsers:

$(elem).onload = function() {
    doSomething();
}

BUT THIS IS A POTENTIAL ISSUE FOR IE9!

The ONLY browser we had reported issues on is IE9. Are we not surprised? It seems that the best way to solve the issue there is to not assign a src to the image until AFTER the onload function has been defined, like so:

$(elem).onload = function() {
    doSomething();
}
$(elem).attr('src','theimage.png');

It seems that IE 9 will sometimes not throw the onload event for whatever reason. Other solutions on this page (such as the one from Evan Carroll, for example) still did not work. Logically, that checked if the load state was already successful and triggered the function and if it wasn't, then set the onload handler, but even when you do that we demonstrated in testing that the image could load between those two lines of js thereby appearing not loaded to the first line and then loading before the onload handler is set.

We found that the best way to get what you want is to not define the image's src until you have set the onload event trigger.

We only just recently stopped supporting IE8 so I can't speak for versions prior to IE9, otherwise, out of all the other browsers that were used on the site -- IE10 and 11 as well as Firefox, Chrome, Opera, Safari and whatever mobile browser people were using -- setting the src before assigning the onload handler was not even an issue.

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Another possible cause of similar issue could be wrong processorArchitecture in the cx_freeze manifest, trying to load x86 common controls dll in x64 process - should be fixed by this patch:

https://bitbucket.org/anthony_tuininga/cx_freeze/pull-request/71/changed-x86-in-windows-manifest-to/diff

Response Content type as CSV

For C# MVC 4.5 you need to do like this:

Response.Clear();
Response.ContentType = "application/CSV";
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileName + ".csv\"");
Response.Write(dataNeedToPrint);
Response.End();
return new EmptyResult();  //this line is important else it will not work.

Insert default value when parameter is null

Christophe,

The default value on a column is only applied if you don't specify the column in the INSERT statement.

Since you're explicitiy listing the column in your insert statement, and explicity setting it to NULL, that's overriding the default value for that column

What you need to do is "if a null is passed into your sproc then don't attempt to insert for that column".

This is a quick and nasty example of how to do that with some dynamic sql.

Create a table with some columns with default values...

CREATE TABLE myTable (
    always VARCHAR(50),
    value1 VARCHAR(50) DEFAULT ('defaultcol1'),
    value2 VARCHAR(50) DEFAULT ('defaultcol2'),
    value3 VARCHAR(50) DEFAULT ('defaultcol3')
)

Create a SPROC that dynamically builds and executes your insert statement based on input params

ALTER PROCEDURE t_insert (
    @always VARCHAR(50),
    @value1 VARCHAR(50) = NULL,
    @value2 VARCHAR(50) = NULL,
    @value3 VARCAHR(50) = NULL
)
AS 
BEGIN
DECLARE @insertpart VARCHAR(500)
DECLARE @valuepart VARCHAR(500)

SET @insertpart = 'INSERT INTO myTable ('
SET @valuepart = 'VALUES ('

    IF @value1 IS NOT NULL
    BEGIN
        SET @insertpart = @insertpart + 'value1,'
        SET @valuepart = @valuepart + '''' + @value1 + ''', '
    END

    IF @value2 IS NOT NULL
    BEGIN
        SET @insertpart = @insertpart + 'value2,'
        SET @valuepart = @valuepart + '''' + @value2 + ''', '
    END

    IF @value3 IS NOT NULL
    BEGIN
        SET @insertpart = @insertpart + 'value3,'
        SET @valuepart = @valuepart + '''' + @value3 + ''', '
    END

    SET @insertpart = @insertpart + 'always) '
    SET @valuepart = @valuepart + + '''' + @always + ''')'

--print @insertpart + @valuepart
EXEC (@insertpart + @valuepart)
END

The following 2 commands should give you an example of what you want as your outputs...

EXEC t_insert 'alwaysvalue'
SELECT * FROM  myTable

EXEC t_insert 'alwaysvalue', 'val1'
SELECT * FROM  myTable

EXEC t_insert 'alwaysvalue', 'val1', 'val2', 'val3'
SELECT * FROM  myTable

I know this is a very convoluted way of doing what you need to do. You could probably equally select the default value from the InformationSchema for the relevant columns but to be honest, I might consider just adding the default value to param at the top of the procedure

What's wrong with using == to compare floats in Java?

Just to give the reason behind what everyone else is saying.

The binary representation of a float is kind of annoying.

In binary, most programmers know the correlation between 1b=1d, 10b=2d, 100b=4d, 1000b=8d

Well it works the other way too.

.1b=.5d, .01b=.25d, .001b=.125, ...

The problem is that there is no exact way to represent most decimal numbers like .1, .2, .3, etc. All you can do is approximate in binary. The system does a little fudge-rounding when the numbers print so that it displays .1 instead of .10000000000001 or .999999999999 (which are probably just as close to the stored representation as .1 is)

Edit from comment: The reason this is a problem is our expectations. We fully expect 2/3 to be fudged at some point when we convert it to decimal, either .7 or .67 or .666667.. But we don't automatically expect .1 to be rounded in the same way as 2/3--and that's exactly what's happening.

By the way, if you are curious the number it stores internally is a pure binary representation using a binary "Scientific Notation". So if you told it to store the decimal number 10.75d, it would store 1010b for the 10, and .11b for the decimal. So it would store .101011 then it saves a few bits at the end to say: Move the decimal point four places right.

(Although technically it's no longer a decimal point, it's now a binary point, but that terminology wouldn't have made things more understandable for most people who would find this answer of any use.)

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

Select Multiple Fields from List in Linq

You can make it a KeyValuePair, so it will return a "IEnumerable<KeyValuePair<string, string>>"

So, it will be like this:

.Select(i => new KeyValuePair<string, string>(i.category_id, i.category_name )).Distinct();

Is it better to use std::memcpy() or std::copy() in terms to performance?

In theory, memcpy might have a slight, imperceptible, infinitesimal, performance advantage, only because it doesn't have the same requirements as std::copy. From the man page of memcpy:

To avoid overflows, the size of the arrays pointed by both the destination and source parameters, shall be at least num bytes, and should not overlap (for overlapping memory blocks, memmove is a safer approach).

In other words, memcpy can ignore the possibility of overlapping data. (Passing overlapping arrays to memcpy is undefined behavior.) So memcpy doesn't need to explicitly check for this condition, whereas std::copy can be used as long as the OutputIterator parameter is not in the source range. Note this is not the same as saying that the source range and destination range can't overlap.

So since std::copy has somewhat different requirements, in theory it should be slightly (with an extreme emphasis on slightly) slower, since it probably will check for overlapping C-arrays, or else delegate the copying of C-arrays to memmove, which needs to perform the check. But in practice, you (and most profilers) probably won't even detect any difference.

Of course, if you're not working with PODs, you can't use memcpy anyway.

Deserialize JSON string to c# object

Same problem happened to me. So if the service returns the response as a JSON string you have to deserialize the string first, then you will be able to deserialize the object type from it properly:

string json= string.Empty;
using (var streamReader = new StreamReader(response.GetResponseStream(), true))
        {
            json= new JavaScriptSerializer().Deserialize<string>(streamReader.ReadToEnd());

        }
//To deserialize to your object type...
MyType myType;
using (var memoryStream = new MemoryStream())
         {
            byte[] jsonBytes = Encoding.UTF8.GetBytes(@json);
            memoryStream.Write(jsonBytes, 0, jsonBytes.Length);
            memoryStream.Seek(0, SeekOrigin.Begin);
            using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(memoryStream, Encoding.UTF8,          XmlDictionaryReaderQuotas.Max, null))
            {
                var serializer = new DataContractJsonSerializer(typeof(MyType));
                myType = (MyType)serializer.ReadObject(jsonReader);

            }
        }

4 Sure it will work.... ;)

Are HTTPS headers encrypted?

Yes, headers are encrypted. It's written here.

Everything in the HTTPS message is encrypted, including the headers, and the request/response load.

MySQL my.ini location

programData is hidden folder so you have to change the option from setting to show hidden folder and then make the change in my.ini file present in that.

Be sure to update the correct my.ini file because it can waste a lot of your time if you keep updating wrong file.

You can look into service to see which my.ini is configured in this service.

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

If you created a new Applications folder in an external drive and installed Xcode there:

sudo xcode-select --switch /Volumes/MyExternalStorageName/Applications/Xcode.app/Contents/Developer

How to remove text from a string?

This doesn't have anything to do with jQuery. You can use the JavaScript replace function for this:

var str = "data-123";
str = str.replace("data-", "");

You can also pass a regex to this function. In the following example, it would replace everything except numerics:

str = str.replace(/[^0-9\.]+/g, "");

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

It usually happens when the certificate does not match with the host name.

The solution would be to contact the host and ask it to fix its certificate.
Otherwise you can turn off cURL's verification of the certificate, use the -k (or --insecure) option.
Please note that as the option said, it is insecure. You shouldn't use this option because it allows man-in-the-middle attacks and defeats the purpose of HTTPS.

More can be found in here: http://curl.haxx.se/docs/sslcerts.html

Fake "click" to activate an onclick method

This is a perfect example of where you should use a javascript library like Prototype or JQuery to abstract away the cross-browser differences.

Use string value from a cell to access worksheet of same name

INDIRECT is the function you want to use. Like so:

=INDIRECT("'"&A5&"'!G7")

With INDIRECT you can build your formula as a text string.

Generating a drop down list of timezones with PHP

This PHP function do the Job for you an give back an array:

function time_zonelist(){
    $return = array();
    $timezone_identifiers_list = timezone_identifiers_list();
    foreach($timezone_identifiers_list as $timezone_identifier){
        $date_time_zone = new DateTimeZone($timezone_identifier);
        $date_time = new DateTime('now', $date_time_zone);
        $hours = floor($date_time_zone->getOffset($date_time) / 3600);
        $mins = floor(($date_time_zone->getOffset($date_time) - ($hours*3600)) / 60);
        $hours = 'GMT' . ($hours < 0 ? $hours : '+'.$hours);
        $mins = ($mins > 0 ? $mins : '0'.$mins);
        $text = str_replace("_"," ",$timezone_identifier);
        $return[$timezone_identifier] = $text.' ('.$hours.':'.$mins.')';
    }
    return $return;
}

This PHP function give back an array of all existing Timezones including Offset:

Use it e.g. like this:

print_r(time_zonelist());

How do I set the selected item in a drop down box

Its too old but I have to add my way as well :) because it is generic and useful especially when you are using static dropdown values.

function selectdCheck($value1,$value2)
   {
     if ($value1 == $value2) 
     {
      echo 'selected="selected"';
     } else 
     {
       echo '';
     }
     return;
   }

and in you dropdown options you can use this function like this and you can use this as many as you can because it fits with all of your select boxes/dropdowns

<option <?php selectdCheck($row[month],january); ?> value="january">january</option>

:) I hope this function help others

Postgres password authentication fails

Assuming, that you have root access on the box you can do:

sudo -u postgres psql

If that fails with a database "postgres" does not exists this block.

sudo -u postgres psql template1

Then sudo nano /etc/postgresql/11/main/pg_hba.conf file

local   all         postgres                          ident

For newer versions of PostgreSQL ident actually might be peer.

Inside the psql shell you can give the DB user postgres a password:

ALTER USER postgres PASSWORD 'newPassword';

day of the week to day number (Monday = 1, Tuesday = 2)

$day_of_week = date('N', strtotime('Monday'));

How to format a floating number to fixed width in Python

I needed something similar for arrays. That helped me

some_array_rounded=np.around(some_array, 5)

How to bind Events on Ajax loaded Content?

If the content is appended after .on() is called, you'll need to create a delegated event on a parent element of the loaded content. This is because event handlers are bound when .on() is called (i.e. usually on page load). If the element doesn't exist when .on() is called, the event will not be bound to it!

Because events propagate up through the DOM, we can solve this by creating a delegated event on a parent element (.parent-element in the example below) that we know exists when the page loads. Here's how:

$('.parent-element').on('click', '.mylink', function(){
  alert ("new link clicked!");
})

Some more reading on the subject:

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

Run this, and your errors will vanish

rm -rf Pods && gem install cocoapods && pod install

Accessing an SQLite Database in Swift

This is by far the best SQLite library that I've used in Swift: https://github.com/stephencelis/SQLite.swift

Look at the code examples. So much cleaner than the C API:

import SQLite

let db = try Connection("path/to/db.sqlite3")

let users = Table("users")
let id = Expression<Int64>("id")
let name = Expression<String?>("name")
let email = Expression<String>("email")

try db.run(users.create { t in
    t.column(id, primaryKey: true)
    t.column(name)
    t.column(email, unique: true)
})
// CREATE TABLE "users" (
//     "id" INTEGER PRIMARY KEY NOT NULL,
//     "name" TEXT,
//     "email" TEXT NOT NULL UNIQUE
// )

let insert = users.insert(name <- "Alice", email <- "[email protected]")
let rowid = try db.run(insert)
// INSERT INTO "users" ("name", "email") VALUES ('Alice', '[email protected]')

for user in try db.prepare(users) {
    print("id: \(user[id]), name: \(user[name]), email: \(user[email])")
    // id: 1, name: Optional("Alice"), email: [email protected]
}
// SELECT * FROM "users"

let alice = users.filter(id == rowid)

try db.run(alice.update(email <- email.replace("mac.com", with: "me.com")))
// UPDATE "users" SET "email" = replace("email", 'mac.com', 'me.com')
// WHERE ("id" = 1)

try db.run(alice.delete())
// DELETE FROM "users" WHERE ("id" = 1)

try db.scalar(users.count) // 0
// SELECT count(*) FROM "users"

The documentation also says that "SQLite.swift also works as a lightweight, Swift-friendly wrapper over the C API," and follows with some examples of that.

How can I extract a good quality JPEG image from a video file with ffmpeg?

Use -qscale:v to control quality

Use -qscale:v (or the alias -q:v) as an output option.

  • Normal range for JPEG is 2-31 with 31 being the worst quality.
  • The scale is linear with double the qscale being roughly half the bitrate.
  • Recommend trying values of 2-5.
  • You can use a value of 1 but you must add the -qmin 1 output option (because the default is -qmin 2).

To output a series of images:

ffmpeg -i input.mp4 -qscale:v 2 output_%03d.jpg

See the image muxer documentation for more options involving image outputs.

To output a single image at ~60 seconds duration:

ffmpeg -ss 60 -i input.mp4 -qscale:v 4 -frames:v 1 output.jpg

Also see

Shell Scripting: Using a variable to define a path

To add to the above correct answer :- For my case in shell, this code worked (working on sqoop)

ROOT_PATH="path/to/the/folder"
--options-file  $ROOT_PATH/query.txt

jQuery selector to get form by name

$('form[name="frmSave"]') is correct. You mentioned you thought this would get all children with the name frmsave inside the form; this would only happen if there was a space or other combinator between the form and the selector, eg: $('form [name="frmSave"]');

$('form[name="frmSave"]') literally means find all forms with the name frmSave, because there is no combinator involved.

The type initializer for 'MyClass' threw an exception

This problem can be caused if a class tries to get value of a key in web.config or app.config which is not present there.

e.g.
The class has a static variable

private static string ClientID = System.Configuration.ConfigurationSettings.AppSettings["GoogleCalendarApplicationClientID"].ToString();

But the web.config doesn't contain the GoogleCalendarApplicationClientID key

The error will be thrown on any static function call or any class instance creation

Removing duplicate characters from a string

Create a list in Python and also a set which doesn't allow any duplicates. Solution1 :

def fix(string):
    s = set()
    list = []
    for ch in string:
        if ch not in s:
            s.add(ch)
            list.append(ch)

    return ''.join(list)        

string = "Protiijaayiiii"
print(fix(string))

Method 2 :

s = "Protijayi"

aa = [ ch  for i, ch in enumerate(s) if ch not in s[:i]]
print(''.join(aa))

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

I was having this same issue this morning. When I checked my Device Manager, it showed COM4 properly, and when I checked in the Arduino IDE COM4 just wasn't an option. Only COM1 was listed.
I tried unplugging and plugging my Arduino in and out a couple more times and eventually COM4 showed up again in the IDE. I didn't have to change any settings.
Hopefully that helps somebody.

ImportError: No module named 'MySQL'

I just moved source folder connector from folder mysql to site-packages. And run import connector

jQuery see if any or no checkboxes are selected

This is what I used for checking if any checkboxes in a list of checkboxes had changed:

$('input[type="checkbox"]').change(function(){ 

        var itemName = $('select option:selected').text();  

         //Do something.

});     

What is The Rule of Three?

The law of the big three is as specified above.

An easy example, in plain English, of the kind of problem it solves:

Non default destructor

You allocated memory in your constructor and so you need to write a destructor to delete it. Otherwise you will cause a memory leak.

You might think that this is job done.

The problem will be, if a copy is made of your object, then the copy will point to the same memory as the original object.

Once, one of these deletes the memory in its destructor, the other will have a pointer to invalid memory (this is called a dangling pointer) when it tries to use it things are going to get hairy.

Therefore, you write a copy constructor so that it allocates new objects their own pieces of memory to destroy.

Assignment operator and copy constructor

You allocated memory in your constructor to a member pointer of your class. When you copy an object of this class the default assignment operator and copy constructor will copy the value of this member pointer to the new object.

This means that the new object and the old object will be pointing at the same piece of memory so when you change it in one object it will be changed for the other objerct too. If one object deletes this memory the other will carry on trying to use it - eek.

To resolve this you write your own version of the copy constructor and assignment operator. Your versions allocate separate memory to the new objects and copy across the values that the first pointer is pointing to rather than its address.

How do I concatenate two strings in C?

Concatenate Strings

Concatenating any two strings in C can be done in atleast 3 ways :-

1) By copying string 2 to the end of string 1

#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
  char str1[MAX],str2[MAX];
  int i,j=0;
  printf("Input string 1: ");
  gets(str1);
  printf("\nInput string 2: ");
  gets(str2);
  for(i=strlen(str1);str2[j]!='\0';i++)  //Copying string 2 to the end of string 1
  {
     str1[i]=str2[j];
     j++;
  }
  str1[i]='\0';
  printf("\nConcatenated string: ");
  puts(str1);
  return 0;
}

2) By copying string 1 and string 2 to string 3

#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
  char str1[MAX],str2[MAX],str3[MAX];
  int i,j=0,count=0;
  printf("Input string 1: ");
  gets(str1);
  printf("\nInput string 2: ");
  gets(str2);
  for(i=0;str1[i]!='\0';i++)          //Copying string 1 to string 3
  {
    str3[i]=str1[i];
    count++;
  }
  for(i=count;str2[j]!='\0';i++)     //Copying string 2 to the end of string 3
  {
    str3[i]=str2[j];
    j++;
  }
  str3[i]='\0';
  printf("\nConcatenated string : ");
  puts(str3);
  return 0;
}

3) By using strcat() function

#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
  char str1[MAX],str2[MAX];
  printf("Input string 1: ");
  gets(str1);
  printf("\nInput string 2: ");
  gets(str2);
  strcat(str1,str2);                    //strcat() function
  printf("\nConcatenated string : ");
  puts(str1);
  return 0;
}

Uninstall mongoDB from ubuntu

sudo service mongod stop
sudo apt-get purge mongodb-org*
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb

this worked for me

How to reset form body in bootstrap modal box?

You can make a JavaScript function to do that:

$.clearInput = function () {
        $('form').find('input[type=text], input[type=password], input[type=number], input[type=email], textarea').val('');
};

and then you can call that function each time your modal is hidden:

$('#Your_Modal').on('hidden', function () {
        $.clearInput();
});

Why do I get a C malloc assertion failure?

I was porting one application from Visual C to gcc over Linux and I had the same problem with

malloc.c:3096: sYSMALLOc: Assertion using gcc on UBUNTU 11.

I moved the same code to a Suse distribution (on other computer ) and I don't have any problem.

I suspect that the problems are not in our programs but in the own libc.

Remove Android App Title Bar

Title bar in android is called Action bar. So if you want to remove it from any specific activity, go to AndroidManifest.xml and add the theme type. Such as android:theme="@style/Theme.AppCompat.Light.NoActionBar".

Example:

<activity
    android:name=".SplashActivity"
    android:noHistory="true"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
</activity>

Android Drawing Separator/Divider Line in Layout?

I usually use this code to add horizontal line:

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"/>

To add vertical separator, switch the layout_width and layout_height values

What's the advantage of a Java enum versus a class with public static final fields?

Another important difference is that java compiler treats static final fields of primitive types and String as literals. It means these constants become inline. It's similar to C/C++ #define preprocessor. See this SO question. This is not the case with enums.

How to update data in one table from corresponding data in another table in SQL Server 2005

Try a query like

INSERT INTO NEW_TABLENAME SELECT * FROM OLD_TABLENAME;

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

It seems odd that this directory was not created at install - have you manually changed the path of the socket file in the my.cfg?

Have you tried simply creating this directory yourself, and restarting the service?

mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld

Android ListView Selector Color

TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)

Here is the FIX for 2.3 and below when using colours:

As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape drawable containing the colour you want, and to use that instead of the colour.

I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).

Copy file or directories recursively in Python

To add on Tzot's and gns answers, here's an alternative way of copying files and folders recursively. (Python 3.X)

import os, shutil

root_src_dir = r'C:\MyMusic'    #Path/Location of the source directory
root_dst_dir = 'D:MusicBackUp'  #Path to the destination folder

for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            os.remove(dst_file)
        shutil.copy(src_file, dst_dir)

Should it be your first time and you have no idea how to copy files and folders recursively, I hope this helps.

How to know when a web page was last updated?

Take a look at archive.org

You can find almost everything about the past of a website there.

Fastest way to remove first char in a String

I would just use

string data= "/temp string";
data = data.substring(1)

Output: temp string

That always works for me.

uncaught syntaxerror unexpected token U JSON

I was getting this message while validating (in MVC project). For me, adding ValidationMessageFor element fixed the issue.

To be precise, line number 43 in jquery.validate.unobtrusive.js caused the issue:

  replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;

Microsoft.ReportViewer.Common Version=12.0.0.0

In My cases, After installing Sql server data tools by Visual Studio 2015 installer, problem has been resolved

Here is the screenshot for installing data tools

How to use XMLReader in PHP?

It all depends on how big the unit of work, but I guess you're trying to treat each <product/> nodes in succession.

For that, the simplest way would be to use XMLReader to get to each node, then use SimpleXML to access them. This way, you keep the memory usage low because you're treating one node at a time and you still leverage SimpleXML's ease of use. For instance:

$z = new XMLReader;
$z->open('data.xml');

$doc = new DOMDocument;

// move to the first <product /> node
while ($z->read() && $z->name !== 'product');

// now that we're at the right depth, hop to the next <product/> until the end of the tree
while ($z->name === 'product')
{
    // either one should work
    //$node = new SimpleXMLElement($z->readOuterXML());
    $node = simplexml_import_dom($doc->importNode($z->expand(), true));

    // now you can use $node without going insane about parsing
    var_dump($node->element_1);

    // go to next <product />
    $z->next('product');
}

Quick overview of pros and cons of different approaches:

XMLReader only

  • Pros: fast, uses little memory

  • Cons: excessively hard to write and debug, requires lots of userland code to do anything useful. Userland code is slow and prone to error. Plus, it leaves you with more lines of code to maintain

XMLReader + SimpleXML

  • Pros: doesn't use much memory (only the memory needed to process one node) and SimpleXML is, as the name implies, really easy to use.

  • Cons: creating a SimpleXMLElement object for each node is not very fast. You really have to benchmark it to understand whether it's a problem for you. Even a modest machine would be able to process a thousand nodes per second, though.

XMLReader + DOM

  • Pros: uses about as much memory as SimpleXML, and XMLReader::expand() is faster than creating a new SimpleXMLElement. I wish it was possible to use simplexml_import_dom() but it doesn't seem to work in that case

  • Cons: DOM is annoying to work with. It's halfway between XMLReader and SimpleXML. Not as complicated and awkward as XMLReader, but light years away from working with SimpleXML.

My advice: write a prototype with SimpleXML, see if it works for you. If performance is paramount, try DOM. Stay as far away from XMLReader as possible. Remember that the more code you write, the higher the possibility of you introducing bugs or introducing performance regressions.

Restrict SQL Server Login access to only one database

this is to topup to what was selected as the correct answer. It has one missing step that when not done, the user will still be able to access the rest of the database. First, do as @DineshDB suggested

  1. Connect to your SQL server instance using management studio
   2. Goto Security -> Logins -> (RIGHT CLICK) New Login
   3. fill in user details
   4. Under User Mapping, select the databases you want the user to be able to access and configure

the missing step is below:

5. Under user mapping, ensure that "sysadmin" is NOT CHECKED and select "db_owner" as the role for the new user.

And thats it.

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

I think it could be almost any javascript error/typing error in your application. I tried to delete one file content after another and finally found the typing error.

.NET / C# - Convert char[] to string

char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);

Java 8 forEach with index

Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:

IntStream.range(0, params.size())
  .forEach(idx ->
    query.bind(
      idx,
      params.get(idx)
    )
  )
;

The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).

Where does R store packages?

This is documented in the 'R Installation and Administration' manual that came with your installation.

On my Linux box:

R> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"      
[3] "/usr/lib/R/library"           
R> 

meaning that the default path is the first of these. You can override that via an argument to both install.packages() (from inside R) or R CMD INSTALL (outside R).

You can also override by setting the R_LIBS_USER variable.

Magento - How to add/remove links on my account navigation?

Open navigation.phtml

app/design/frontend/yourtheme/default/template/customer/account/navigation.phtml

replace

<?php $_links = $this->getLinks(); ?>

with unset link which you want to remove

<?php 
$_count = count($_links);
unset($_links['account']); // Account Information     
unset($_links['account_edit']); // Account Information  
unset($_links['address_book']); // Address Book
unset($_links['orders']); // My Orders
unset($_links['billing_agreements']); // Billing Agreements
unset($_links['recurring_profiles']); // Recurring Profiles
unset($_links['reviews']);  // My Product Reviews
unset($_links['wishlist']); // My Wishlist
unset($_links['OAuth Customer Tokens']); // My Applications
unset($_links['newsletter']); // Newsletter Subscriptions
unset($_links['downloadable_products']); // My Downloadable Products
unset($_links['tags']); // My Tags
unset($_links['invitations']); // My Invitations
unset($_links['enterprise_customerbalance']); // Store Credit
unset($_links['enterprise_reward']); // Reward Points
unset($_links['giftregistry']); // Gift Registry
unset($_links['enterprise_giftcardaccount']); // Gift Card Link
?>

Maven Out of Memory Build Failure

_JAVA_OPTIONS="-Xmx3G" mvn clean install

Construct pandas DataFrame from list of tuples of (row,col,values)

I submit that it is better to leave your data stacked as it is:

df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])

# Possibly also this if these can always be the indexes:
# df = df.set_index(['R_Number', 'C_Number'])

Then it's a bit more intuitive to say

df.set_index(['R_Number', 'C_Number']).Avg.unstack(level=1)

This way it is implicit that you're seeking to reshape the averages, or the standard deviations. Whereas, just using pivot, it's purely based on column convention as to what semantic entity it is that you are reshaping.

Cast Double to Integer in Java

Like this:

Double foo = 123.456;
Integer bar = foo.intValue();

JavaScript hashmap equivalent

JavaScript does not have a built-in map/hashmap. It should be called an associative array.

hash["X"] is equal to hash.X, but it allows "X" as a string variable. In other words, hash[x] is functionally equal to eval("hash."+x.toString()).

It is more similar to object.properties rather than key-value mapping. If you are looking for a better key/value mapping in JavaScript, please use the Map object.

Bootstrap 3.0 Sliding Menu from left

Probably late but here is a plugin that can do the job : http://multi-level-push-menu.make.rs/

Also v2 can use mobile gesture such as swipe ;)

Wait until a process ends

I had a case where Process.HasExited didn't change after closing the window belonging to the process. So Process.WaitForExit() also didn't work. I had to monitor Process.Responding that went to false after closing the window like that:

while (!_process.HasExited && _process.Responding) {
  Thread.Sleep(100);
}
...

Perhaps this helps someone.

What is the difference between __dirname and ./ in node.js?

./ refers to the current working directory, except in the require() function. When using require(), it translates ./ to the directory of the current file called. __dirname is always the directory of the current file.

For example, with the following file structure

/home/user/dir/files/config.json

{
  "hello": "world"
}

/home/user/dir/files/somefile.txt

text file

/home/user/dir/dir.js

var fs = require('fs');

console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));

If I cd into /home/user/dir and run node dir.js I will get

{ hello: 'world' }
text file

But when I run the same script from /home/user/ I get

{ hello: 'world' }

Error: ENOENT, no such file or directory './files/somefile.txt'
    at Object.openSync (fs.js:228:18)
    at Object.readFileSync (fs.js:119:15)
    at Object.<anonymous> (/home/user/dir/dir.js:4:16)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

Using ./ worked with require but not for fs.readFileSync. That's because for fs.readFileSync, ./ translates into the cwd (in this case /home/user/). And /home/user/files/somefile.txt does not exist.

Set multiple system properties Java command line

There's nothing on the Documentation that mentions about anything like that.

Here's a quote:

-Dproperty=value Set a system property value. If value is a string that contains spaces, you must enclose the string in double quotes:

java -Dfoo="some string" SomeClass

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

it works for me Swift 3:

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }

and in ViewDidLoad:

    self.navigationController?.interactivePopGestureRecognizer?.delegate = self
    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true

How to generate graphs and charts from mysql database in php

I use highcharts. They are very interactive (and very fancy I might add). You do have to get a little creative to access data from MySQL database, but if you have a general understanding of JavaScript and PHP, you should have no problems.

Dropdown select with images

If you think about it the concept behind a dropdown select it's pretty simple. For what you're trying to accomplish, a simple <ul> will do.

<ul id="menu">
    <li>
        <a href="#"><img src="" alt=""/></a> <!-- Selected -->
        <ul>
            <li><a href="#"><img src="" alt=""/></a></li>
            <li><a href="#"><img src="" alt=""/></a></li>
            <li><a href="#"><img src="" alt=""/></a></li>
            <li><a href="#"><img src="" alt=""/></a></li>
        </ul>
    </li>
</ul>

You style it with css and then some simple jQuery will do. I haven't tried this tho:

$('#menu ul li').click(function(){
    var $a = $(this).find('a');
    $(this).parents('#menu').children('li a').replaceWith($a).
});

C# RSA encryption/decryption with transmission

well there are really enough examples for this, but anyway, here you go

using System;
using System.Security.Cryptography;

namespace RsaCryptoExample
{
  static class Program
  {
    static void Main()
    {
      //lets take a new CSP with a new 2048 bit rsa key pair
      var csp = new RSACryptoServiceProvider(2048);

      //how to get the private key
      var privKey = csp.ExportParameters(true);

      //and the public key ...
      var pubKey = csp.ExportParameters(false);

      //converting the public key into a string representation
      string pubKeyString;
      {
        //we need some buffer
        var sw = new System.IO.StringWriter();
        //we need a serializer
        var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
        //serialize the key into the stream
        xs.Serialize(sw, pubKey);
        //get the string from the stream
        pubKeyString = sw.ToString();
      }

      //converting it back
      {
        //get a stream from the string
        var sr = new System.IO.StringReader(pubKeyString);
        //we need a deserializer
        var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
        //get the object back from the stream
        pubKey = (RSAParameters)xs.Deserialize(sr);
      }

      //conversion for the private key is no black magic either ... omitted

      //we have a public key ... let's get a new csp and load that key
      csp = new RSACryptoServiceProvider();
      csp.ImportParameters(pubKey);

      //we need some data to encrypt
      var plainTextData = "foobar";

      //for encryption, always handle bytes...
      var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(plainTextData);

      //apply pkcs#1.5 padding and encrypt our data 
      var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);

      //we might want a string representation of our cypher text... base64 will do
      var cypherText = Convert.ToBase64String(bytesCypherText);


      /*
       * some transmission / storage / retrieval
       * 
       * and we want to decrypt our cypherText
       */

      //first, get our bytes back from the base64 string ...
      bytesCypherText = Convert.FromBase64String(cypherText);

      //we want to decrypt, therefore we need a csp and load our private key
      csp = new RSACryptoServiceProvider();
      csp.ImportParameters(privKey);

      //decrypt and strip pkcs#1.5 padding
      bytesPlainTextData = csp.Decrypt(bytesCypherText, false);

      //get our original plainText back...
      plainTextData = System.Text.Encoding.Unicode.GetString(bytesPlainTextData);
    }
  }
}

as a side note: the calls to Encrypt() and Decrypt() have a bool parameter that switches between OAEP and PKCS#1.5 padding ... you might want to choose OAEP if it's available in your situation

How can I list ALL DNS records?

For Windows:

You may find the need to check the status of your domains DNS records, or check the Name Servers to see which records the servers are pulling.

  1. Launch Windows Command Prompt by navigating to Start > Command Prompt or via Run > CMD.

  2. Type NSLOOKUP and hit Enter. The default Server is set to your local DNS, the Address will be your local IP.

  3. Set the DNS Record type you wish to lookup by typing set type=## where ## is the record type, then hit Enter. You may use ANY, A, AAAA, A+AAAA, CNAME, MX, NS, PTR, SOA, or SRV as the record type.

  4. Now enter the domain name you wish to query then hit Enter.. In this example, we will use Managed.com.

  5. NSLOOKUP will now return the record entries for the domain you entered.

  6. You can also change the Name Servers which you are querying. This is useful if you are checking the records before DNS has fully propagated. To change the Name Server type server [name server]. Replace [name server] with the Name Servers you wish to use. In this example, we will set these as NSA.managed.com.

  7. Once changed, change the query type (Step 3) if needed then enter new a new domain (Step 4.)

For Linux:

1) Check DNS Records Using Dig Command Dig stands for domain information groper is a flexible tool for interrogating DNS name servers. It performs DNS lookups and displays the answers that are returned from the name server(s) that were queried. Most DNS administrators use dig to troubleshoot DNS problems because of its flexibility, ease of use and clarity of output. Other lookup tools tend to have less functionality than dig.

2) Check DNS Records Using NSlookup Command Nslookup is a program to query Internet domain name servers. Nslookup has two modes interactive and non-interactive.

Interactive mode allows the user to query name servers for information about various hosts and domains or to print a list of hosts in a domain.

Non-interactive mode is used to print just the name and requested information for a host or domain. It’s network administration tool which will help them to check and troubleshoot DNS related issues.

3) Check DNS Records Using Host Command host is a simple utility for performing DNS lookups. It is normally used to convert names to IP addresses and vice versa. When no arguments or options are given, host prints a short summary of its command line arguments and options.

Create a global variable in TypeScript

This is how I have fixed it:

Steps:

  1. Declared a global namespace, for e.g. custom.d.ts as below :
declare global {
    namespace NodeJS {
        interface Global {
            Config: {}
        }
    }
}
export default global;
  1. Map the above created a file into "tsconfig.json" as below:
"typeRoots": ["src/types/custom.d.ts" ]
  1. Get the above created global variable in any of the files as below:
console.log(global.config)

Note:

  1. typescript version: "3.0.1".

  2. In my case, the requirement was to set the global variable before boots up the application and the variable should access throughout the dependent objects so that we can get the required config properties.

Hope this helps!

Thank you

Format date and time in a Windows batch script

The following may not be a direct answer but a close one?

set hour=%time:~0,2%
if "%hour:~0,1%" == " " set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__0%time:~1,2%_%time:~3,2%_%time:~6,2%
else set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%

At least it may be inspiring.

How to generate a simple popup using jQuery

I think this is a great tutorial on writing a simple jquery popup. Plus it looks very beautiful

How to add a set path only for that batch file executing?

Just like any other environment variable, with SET:

SET PATH=%PATH%;c:\whatever\else

If you want to have a little safety check built in first, check to see if the new path exists first:

IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else

If you want that to be local to that batch file, use setlocal:

setlocal
set PATH=...
set OTHERTHING=...

@REM Rest of your script

Read the docs carefully for setlocal/endlocal , and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.

The Syntax page should get you started with the basics.

Why does visual studio 2012 not find my tests?

After googling "visual studio can't see tests" it brought me here, so I thought I'd share my problem. I could build my solution, and the tests existed, but I could not see them! It turns our it was a quirk of the IDE, that caused the problem. See image below for an explanation and fix:

enter image description here

Populating a ListView using an ArrayList?

public class Example extends Activity
{
    private ListView lv;
    ArrayList<String> arrlist=new ArrayList<String>();
    //let me assume that you are putting the values in this arraylist
    //Now convert your arraylist to array

    //You will get an exmaple here

    //http://www.java-tips.org/java-se-tips/java.lang/how-to-convert-an-arraylist-into-an-array.html 

    private String arr[]=convert(arrlist);
    @Override
    public void onCreate(Bundle bun)
    {
        super.onCreate(bun);
        setContentView(R.layout.main);
        lv=(ListView)findViewById(R.id.lv);
        lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
        }
    }

Smooth scroll to specific div on click

There are many examples of smooth scrolling using JS libraries like jQuery, Mootools, Prototype, etc.

The following example is on pure JavaScript. If you have no jQuery/Mootools/Prototype on page or you don't want to overload page with heavy JS libraries the example will be of help.

http://jsfiddle.net/rjSfP/

HTML Part:

<div class="first"><button type="button" onclick="smoothScroll(document.getElementById('second'))">Click Me!</button></div>
<div class="second" id="second">Hi</div>

CSS Part:

.first {
    width: 100%;
    height: 1000px;
    background: #ccc;
}

.second {
    width: 100%;
    height: 1000px;
    background: #999;
}

JS Part:

window.smoothScroll = function(target) {
    var scrollContainer = target;
    do { //find scroll container
        scrollContainer = scrollContainer.parentNode;
        if (!scrollContainer) return;
        scrollContainer.scrollTop += 1;
    } while (scrollContainer.scrollTop == 0);

    var targetY = 0;
    do { //find the top of target relatively to the container
        if (target == scrollContainer) break;
        targetY += target.offsetTop;
    } while (target = target.offsetParent);

    scroll = function(c, a, b, i) {
        i++; if (i > 30) return;
        c.scrollTop = a + (b - a) / 30 * i;
        setTimeout(function(){ scroll(c, a, b, i); }, 20);
    }
    // start scrolling
    scroll(scrollContainer, scrollContainer.scrollTop, targetY, 0);
}

React: Expected an assignment or function call and instead saw an expression

You use a function component:

const def = (props) => {
<div>
<div className=" ..some classes..">{abc}</div>
<div className=" ..some classes..">{t('translation/something')}</div>

<div ...>
<someComponent 
 do something
/>

if (some condition) {
do this
} else {
do that
}

 </div>

};

In the function component, you have to write a return or just add parentheses. After the added return or parentheses your code should look like this:

const def = (props) => ({
<div>
<div className=" ..some classes..">{abc}</div>
<div className=" ..some classes..">{t('translation/something')}</div>

<div ...>
<someComponent 
 do something
/>

if (some condition) {
do this
} else {
do that
}

 </div>
});

How to get longitude and latitude of any address?

There is no forumula, as street names and cities are essentially handed out randomly. The address needs to be looked up in a database. Alternatively, you can look up a zip code in a database for the region that the zip code is for.

You didn't mention a country, so I'm going to assume you just want addresses in the USA. There are numerous databases you can use, some free, some not.

You can also use the Google Maps API to have them look up an address in their database for you. That is probably the easiest solution, but requires your application to have a working internet connection at all times.

Connect to sqlplus in a shell script and run SQL scripts

Wouldn't something akin to this be better, security-wise?:

sqlplus -s /nolog << EOF
CONNECT admin/password;

whenever sqlerror exit sql.sqlcode;
set echo off 
set heading off

@pl_script_1.sql
@pl_script_2.sql

exit;
EOF 

How can I check whether a variable is defined in Node.js?

It sounds like you're doing property checking on an object! If you want to check a property exists (but can be values such as null or 0 in addition to truthy values), the in operator can make for some nice syntax.

var foo = { bar: 1234, baz: null };
console.log("bar in foo:", "bar" in foo); // true
console.log("baz in foo:", "baz" in foo); // true
console.log("otherProp in foo:", "otherProp" in foo) // false
console.log("__proto__ in foo:", "__proto__" in foo) // true

As you can see, the __proto__ property is going to be thrown here. This is true for all inherited properties. For further reading, I'd recommend the MDN page:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

Probably is the use of the "on" event that Bootstrap use a lot and was inserted at jQuery 1.7 http://api.jquery.com/on/

Android: adb pull file on desktop

Note need root than:

  • adb root
  • adb pull /data/data/com.google.android.apps.nexuslauncher/databases/launcher.db launcher.db

how to measure running time of algorithms in python

Using a decorator for measuring execution time for functions can be handy. There is an example at http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods.

Below I've shamelessly pasted the code from the site mentioned above so that the example exists at SO in case the site is wiped off the net.

import time                                                

def timeit(method):

    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()

        print '%r (%r, %r) %2.2f sec' % \
              (method.__name__, args, kw, te-ts)
        return result

    return timed

class Foo(object):

    @timeit
    def foo(self, a=2, b=3):
        time.sleep(0.2)

@timeit
def f1():
    time.sleep(1)
    print 'f1'

@timeit
def f2(a):
    time.sleep(2)
    print 'f2',a

@timeit
def f3(a, *args, **kw):
    time.sleep(0.3)
    print 'f3', args, kw

f1()
f2(42)
f3(42, 43, foo=2)
Foo().foo()

// John

Search a string in a file and delete it from this file by Shell Script

This should do it:

sed -e s/deletethis//g -i *
sed -e "s/deletethis//g" -i.backup *
sed -e "s/deletethis//g" -i .backup *

it will replace all occurrences of "deletethis" with "" (nothing) in all files (*), editing them in place.

In the second form the pattern can be edited a little safer, and it makes backups of any modified files, by suffixing them with ".backup".

The third form is the way some versions of sed like it. (e.g. Mac OS X)

man sed for more information.

What is the difference between a token and a lexeme?

When a source program is fed into the lexical analyzer, it begins by breaking up the characters into sequences of lexemes. The lexemes are then used in the construction of tokens, in which the lexemes are mapped into tokens. A variable called myVar would be mapped into a token stating <id, "num">, where "num" should point to the variable's location in the symbol table.

Shortly put:

  • Lexemes are the words derived from the character input stream.
  • Tokens are lexemes mapped into a token-name and an attribute-value.


An example includes:
x = a + b * 2
Which yields the lexemes: {x, =, a, +, b, *, 2}
With corresponding tokens: {<id, 0>, <=>, <id, 1>, <+>, <id, 2>, <*>, <id, 3>}

Inserting string at position x of another string

_x000D_
_x000D_
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
var output = [a.slice(0, position), b, a.slice(position)].join('');_x000D_
console.log(output);
_x000D_
_x000D_
_x000D_


Optional: As a prototype method of String

The following can be used to splice text within another string at a desired index, with an optional removeCount parameter.

_x000D_
_x000D_
if (String.prototype.splice === undefined) {_x000D_
  /**_x000D_
   * Splices text within a string._x000D_
   * @param {int} offset The position to insert the text at (before)_x000D_
   * @param {string} text The text to insert_x000D_
   * @param {int} [removeCount=0] An optional number of characters to overwrite_x000D_
   * @returns {string} A modified string containing the spliced text._x000D_
   */_x000D_
  String.prototype.splice = function(offset, text, removeCount=0) {_x000D_
    let calculatedOffset = offset < 0 ? this.length + offset : offset;_x000D_
    return this.substring(0, calculatedOffset) +_x000D_
      text + this.substring(calculatedOffset + removeCount);_x000D_
  };_x000D_
}_x000D_
_x000D_
let originalText = "I want apple";_x000D_
_x000D_
// Positive offset_x000D_
console.log(originalText.splice(6, " an"));_x000D_
// Negative index_x000D_
console.log(originalText.splice(-5, "an "));_x000D_
// Chaining_x000D_
console.log(originalText.splice(6, " an").splice(2, "need", 4).splice(0, "You", 1));
_x000D_
.as-console-wrapper { top: 0; max-height: 100% !important; }
_x000D_
_x000D_
_x000D_

How to use GROUP BY to concatenate strings in SQL Server?

SQL Server 2005 and later allow you to create your own custom aggregate functions, including for things like concatenation- see the sample at the bottom of the linked article.

How to stop INFO messages displaying on spark console?

If you don't have the ability to edit the java code to insert the .setLogLevel() statements and you don't want yet more external files to deploy, you can use a brute force way to solve this. Just filter out the INFO lines using grep.

spark-submit --deploy-mode client --master local <rest-of-cmd> | grep -v -F "INFO"

JavaFX and OpenJDK

JavaFX is part of OpenJDK

The JavaFX project itself is open source and is part of the OpenJDK project.

Update Dec 2019

For current information on how to use Open Source JavaFX, visit https://openjfx.io. This includes instructions on using JavaFX as a modular library accessed from an existing JDK (such as an Open JDK installation).

The open source code repository for JavaFX is at https://github.com/openjdk/jfx.

At the source location linked, you can find license files for open JavaFX (currently this license matches the license for OpenJDK: GPL+classpath exception).

The wiki for the project is located at: https://wiki.openjdk.java.net/display/OpenJFX/Main

If you want a quick start to using open JavaFX, the Belsoft Liberica JDK distributions provide pre-built binaries of OpenJDK that (currently) include open JavaFX for a variety of platforms.

For distribution as self-contained applications, Java 14, is scheduled to implement JEP 343: Packaging Tool, which "Supports native packaging formats to give end users a natural installation experience. These formats include msi and exe on Windows, pkg and dmg on macOS, and deb and rpm on Linux.", for deployment of OpenJFX based applications with native installers and no additional platform dependencies (such as a pre-installed JDK).


Older information which may become outdated over time

Building JavaFX from the OpenJDK repository

You can build an open version of OpenJDK (including JavaFX) completely from source which has no dependencies on the Oracle JDK or closed source code.

Update: Using a JavaFX distribution pre-built from OpenJDK sources

As noted in comments to this question and in another answer, the Debian Linux distributions offer a JavaFX binary distibution based upon OpenJDK:

(currently this only works for Java 8 as far as I know).

Differences between Open JDK and Oracle JDK with respect to JavaFX

The following information was provided for Java 8. As of Java 9, VP6 encoding is deprecated for JavaFX and the Oracle WebStart/Browser embedded application deployment technology is also deprecated. So future versions of JavaFX, even if they are distributed by Oracle, will likely not include any technology which is not open source.

Oracle JDK includes some software which is not usable from the OpenJDK. There are two main components which relate to JavaFX.

  1. The ON2 VP6 video codec, which is owned by Google and Google has not open sourced.
  2. The Oracle WebStart/Browser Embedded application deployment technology.

This means that an open version of JavaFX cannot play VP6 FLV files. This is not a big loss as it is difficult to find VP6 encoders or media encoded in VP6.

Other more common video formats, such as H.264 will playback fine with an open version of JavaFX (as long as you have the appropriate codecs pre-installed on the target machine).

The lack of WebStart/Browser Embedded deployment technology is really something to do with OpenJDK itself rather than JavaFX specifically. This technology can be used to deploy non-JavaFX applications.

It would be great if the OpenSource community developed a deployment technology for Java (and other software) which completely replaced WebStart and Browser Embedded deployment methods, allowing a nice light-weight, low impact user experience for application distribution. I believe there have been some projects started to serve such a goal, but they have not yet reached a high maturity and adoption level.

Personally, I feel that WebStart/Browser Embedded deployments are legacy technology and there are currently better ways to deploy many JavaFX applications (such as self-contained applications).

Update Dec, 2019:

An open source version of WebStart for JDK 11+ has been developed and is available at https://openwebstart.com.

Who needs to create Linux OpenJDK Distributions which include JavaFX

It is up to the people which create packages for Linux distributions based upon OpenJDK (e.g. Redhat, Ubuntu etc) to create RPMs for the JDK and JRE that include JavaFX. Those software distributors, then need to place the generated packages in their standard distribution code repositories (e.g. fedora/red hat network yum repositories). Currently this is not being done, but I would be quite surprised if Java 8 Linux packages did not include JavaFX when Java 8 is released in March 2014.

Update, Dec 2019:

Now that JavaFX has been separated from most binary JDK and JRE distributions (including Oracle's distribution) and is, instead, available as either a stand-alone SDK, set of jmods or as a library dependencies available from the central Maven repository (as outlined as https://openjfx.io), there is less of a need for standard Linux OpenJDK distributions to include JavaFX.

If you want a pre-built JDK which includes JavaFX, consider the Liberica JDK distributions, which are provided for a variety of platforms.

Advice on Deployment for Substantial Applications

I advise using Java's self-contained application deployment mode.

A description of this deployment mode is:

Application is installed on the local drive and runs as a standalone program using a private copy of Java and JavaFX runtimes. The application can be launched in the same way as other native applications for that operating system, for example using a desktop shortcut or menu entry.

You can build a self-contained application either from the Oracle JDK distribution or from an OpenJDK build which includes JavaFX. It currently easier to do so with an Oracle JDK.

As a version of Java is bundled with your application, you don't have to care about what version of Java may have been pre-installed on the machine, what capabilities it has and whether or not it is compatible with your program. Instead, you can test your application against an exact Java runtime version, and distribute that with your application. The user experience for deploying your application will be the same as installing a native application on their machine (e.g. a windows .exe or .msi installed, an OS X .dmg, a linux .rpm or .deb).

Note: The self-contained application feature was only available for Java 8 and 9, and not for Java 10-13. Java 14, via JEP 343: Packaging Tool, is scheduled to again provide support for this feature from OpenJDK distributions.

Update, April 2018: Information on Oracle's current policy towards future developments

How do I prevent 'git diff' from using a pager?

This worked for me with Git version 2.1.4 on Linux:

git config --global --replace-all core.pager cat

This makes Git use cat instead of less. cat just dumps the output of diff to the screen without any paging.

Link and execute external JavaScript file hosted on GitHub

https://raw.githack.com/

found this site supply a CDN for

  • remove nosniff http header
  • fix mime type by ext name

and this site:

https://rawgit.com/

NOTE: RawGit has reached the end of its useful life

How do I vertically align text in a div?

According to Adam Tomat's answer there was prepared a JSFiddle example to align the text in div:

<div class="cells-block">    
    text<br/>in the block   
</div>

by using display:flex in CSS:

.cells-block {
    display: flex;
    flex-flow: column;
    align-items: center;       /* Vertically   */
    justify-content: flex-end; /* Horisontally */
    text-align: right;         /* Addition: for text's lines */
}

with another example and a few explanations in a blog post.

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){
    this.context=context;
}

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

Equivalent of typedef in C#

Jon really gave a nice solution, I didn't know you could do that!

At times what I resorted to was inheriting from the class and creating its constructors. E.g.

public class FooList : List<Foo> { ... }

Not the best solution (unless your assembly gets used by other people), but it works.

How to upload a file in Django?

Demo

See the github repo, works with Django 3

A minimal Django file upload example

1. Create a django project

Run startproject::

$ django-admin.py startproject sample

now a folder(sample) is created.

2. create an app

Create an app::

$ cd sample
$ python manage.py startapp uploader

Now a folder(uploader) with these files are created::

uploader/
  __init__.py
  admin.py
  app.py
  models.py
  tests.py
  views.py
  migrations/
    __init__.py

3. Update settings.py

On sample/settings.py add 'uploader' to INSTALLED_APPS and add MEDIA_ROOT and MEDIA_URL, ie::

INSTALLED_APPS = [
    'uploader',
    ...<other apps>...      
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

4. Update urls.py

in sample/urls.py add::

...<other imports>...
from django.conf import settings
from django.conf.urls.static import static
from uploader import views as uploader_views

urlpatterns = [
    ...<other url patterns>...
    path('', uploader_views.UploadView.as_view(), name='fileupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

5. Update models.py

update uploader/models.py::

from django.db import models
class Upload(models.Model):
    upload_file = models.FileField()    
    upload_date = models.DateTimeField(auto_now_add =True)

6. Update views.py

update uploader/views.py::

from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Upload
class UploadView(CreateView):
    model = Upload
    fields = ['upload_file', ]
    success_url = reverse_lazy('fileupload')
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['documents'] = Upload.objects.all()
        return context

7. create templates

Create a folder sample/uploader/templates/uploader

Create a file upload_form.html ie sample/uploader/templates/uploader/upload_form.html::

<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <h1>Django File Upload</h1>
    <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form.as_p }}
      <button type="submit">Submit</button>
    </form><hr>
    <ul>
    {% for document in documents %}
        <li>
            <a href="{{ document.upload_file.url }}">{{ document.upload_file.name }}</a>
            <small>({{ document.upload_file.size|filesizeformat }}) - {{document.upload_date}}</small>
        </li>
    {% endfor %}
    </ul>
</div>

8. Syncronize database

Syncronize database and runserver::

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver

visit http://localhost:8000/

inline conditionals in angular.js

Angular 1.1.5 added support for ternary operators:

{{myVar === "two" ? "it's true" : "it's false"}}

Jquery mouseenter() vs mouseover()

Old question, but still no good up-to-date answer with insight imo.

As jQuery uses Javascript wording for events and handlers, but does its own undocumented, but different interpretation of those, let me first shed light on the difference from the pure Javascript viewpoint:

  • both event pairs
    • the mouse can “jump” from outside/outer elements to inner/innermost elements when moved faster than the browser samples its position
    • any enter/over gets a corresponding leave/out (possibly late/jumpy)
    • events go to the visible element below the pointer (invisible elements can’t be target)
  • mouseenter/mouseleave
    • does not bubble (event not useful for delegate handlers)
    • the event registration itself defines the area of observation and abstraction
    • works on the target area, like a park with a pond: the pond is considered part of the park
    • the event is emitted on the target/area whenever the element itself or any descendant directly is entered/left the first time
    • entering a descendant, moving from one descendant to another or moving back into the target does not finish/restart the mouseenter/mouseleave cycle (i.e. no events fire)
    • if you want to observe multiple areas with one handler, register it on each area/element or use the other event pair discussed next
    • descendants of registered areas/elements can have their own handlers, creating an independent observation area with its independent mouseenter/mouseleave event cycles
    • if you think about how a bubbling version of mouseenter/mouseleave could look like, you end up with with something like mouseover/mouseout
  • mouseover/mouseout
    • events bubble
    • events fire whenever the element below the pointer changes
      • mouseout on the previously sampled element
      • followed by mouseover on the new element
      • the events don’t “nest”: before e.g. a child is “overed” the parent will be “out”
    • target/relatedTarget indicate new and previous element
    • if you want to watch different areas
      • register one handler on a common parent (or multiple parents, which together cover all elements you want to watch)
      • look for the element you are interested in between the handler element and the target element; maybe $(event.target).closest(...) suits your needs

Not-so-trivial mouseover/mouseout example:

$('.side-menu, .top-widget')
  .on('mouseover mouseout', event => {
    const target = event.type === 'mouseover' ? event.target : event.relatedTarget;
    const thing = $(target).closest('[data-thing]').attr('data-thing') || 'default';
    // do something with `thing`
  });

These days, all browsers support mouseover/mouseout and mouseenter/mouseleave natively. Nevertheless, jQuery does not register your handler to mouseenter/mouseleave, but silently puts them on a wrappers around mouseover/mouseout as the code below exposes.

The emulation is unnecessary, imperfect and a waste of CPU cycles: it filters out mouseover/mouseout events that a mouseenter/mouseleave would not get, but the target is messed. The real mouseenter/mouseleave would give the handler element as target, the emulation might indicate children of that element, i.e. whatever the mouseover/mouseout carried.

For that reason I do not use jQuery for those events, but e.g.:

$el[0].addEventListener('mouseover', e => ...);

_x000D_
_x000D_
const list = document.getElementById('log');
const outer = document.getElementById('outer');
const $outer = $(outer);

function log(tag, event) {
  const li = list.insertBefore(document.createElement('li'), list.firstChild);
  // only jQuery handlers have originalEvent
  const e = event.originalEvent || event;
  li.append(`${tag} got ${e.type} on ${e.target.id}`);
}

outer.addEventListener('mouseenter', log.bind(null, 'JSmouseenter'));
$outer.on('mouseenter', log.bind(null, '$mouseenter'));
_x000D_
div {
  margin: 20px;
  border: solid black 2px;
}

#inner {
  min-height: 80px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div id=outer>
    <ul id=log>
    </ul>
  </div>
</body>
_x000D_
_x000D_
_x000D_


Note: For delegate handlers never use jQuery’s “delegate handlers with selector registration”. (Reason in another answer.) Use this (or similar):

$(parent).on("mouseover", e => {
  if ($(e.target).closest('.gold').length) {...};
});

instead of

$(parent).on("mouseover", '.gold', e => {...});

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

You have to load jdbc driver. Consider below Code.

try {
           Class.forName("com.mysql.jdbc.Driver");

            // connect way #1
            String url1 = "jdbc:mysql://localhost:3306/aavikme";
            String user = "root";
            String password = "aa";

            conn1 = DriverManager.getConnection(url1, user, password);
            if (conn1 != null) {
                System.out.println("Connected to the database test1");
            }

            // connect way #2
            String url2 = "jdbc:mysql://localhost:3306/aavikme?user=root&password=aa";
            conn2 = DriverManager.getConnection(url2);
            if (conn2 != null) {
                System.out.println("Connected to the database test2");
            }

            // connect way #3
            String url3 = "jdbc:mysql://localhost:3306/aavikme";
            Properties info = new Properties();
            info.put("user", "root");
            info.put("password", "aa");

            conn3 = DriverManager.getConnection(url3, info);
            if (conn3 != null) {
                System.out.println("Connected to the database test3");
            }
   } catch (SQLException ex) {
            System.out.println("An error occurred. Maybe user/password is invalid");
            ex.printStackTrace();
   } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

cannot redeclare block scoped variable (typescript)

Use IIFE(Immediately Invoked Function Expression), IIFE

(function () {
    all your code is here...

 })();

JQuery - Call the jquery button click event based on name property

You have to use the jquery attribute selector. You can read more here:

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

In your case it should be:

$('input[name="btnName"]')

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

Note: This answer is somewhat intended to be a joke, but it actually does work...

#!/bin/bash
outfile="/tmp/$RANDOM"
cfile="$outfile.c"
echo '#include <stdio.h>
int main(void){int e=1;char c;while((c=getc(stdin))!=-1){if(c==10)e=1;if(c==32)e=0;if(e)putc(c,stdout);}}' >> "$cfile"
gcc -o "$outfile" "$cfile"
rm "$cfile"
cat somedata.txt | "$outfile"
rm "$outfile"

You can replace cat somedata.txt with a different command.

Dictionary returning a default value if the key does not exist

No, nothing like that exists. The extension method is the way to go, and your name for it (GetValueOrDefault) is a pretty good choice.

Example of Named Pipes

For someone who is new to IPC and Named Pipes, I found the following NuGet package to be a great help.

GitHub: Named Pipe Wrapper for .NET 4.0

To use first install the package:

PS> Install-Package NamedPipeWrapper

Then an example server (copied from the link):

var server = new NamedPipeServer<SomeClass>("MyServerPipe");
server.ClientConnected += delegate(NamedPipeConnection<SomeClass> conn)
    {
        Console.WriteLine("Client {0} is now connected!", conn.Id);
        conn.PushMessage(new SomeClass { Text: "Welcome!" });
    };

server.ClientMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
    {
        Console.WriteLine("Client {0} says: {1}", conn.Id, message.Text);
    };

server.Start();

Example client:

var client = new NamedPipeClient<SomeClass>("MyServerPipe");
client.ServerMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
    {
        Console.WriteLine("Server says: {0}", message.Text);
    };

client.Start();

Best thing about it for me is that unlike the accepted answer here it supports multiple clients talking to a single server.

How to use Google Translate API in my Java application?

You can use google script which has FREE translate API. All you need is a common google account and do these THREE EASY STEPS.
1) Create new script with such code on google script:

var mock = {
  parameter:{
    q:'hello',
    source:'en',
    target:'fr'
  }
};


function doGet(e) {
  e = e || mock;

  var sourceText = ''
  if (e.parameter.q){
    sourceText = e.parameter.q;
  }

  var sourceLang = '';
  if (e.parameter.source){
    sourceLang = e.parameter.source;
  }

  var targetLang = 'en';
  if (e.parameter.target){
    targetLang = e.parameter.target;
  }

  var translatedText = LanguageApp.translate(sourceText, sourceLang, targetLang, {contentType: 'html'});

  return ContentService.createTextOutput(translatedText).setMimeType(ContentService.MimeType.JSON);
}

2) Click Publish -> Deploy as webapp -> Who has access to the app: Anyone even anonymous -> Deploy. And then copy your web app url, you will need it for calling translate API.
google script deploy

3) Use this java code for testing your API:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Translator {

    public static void main(String[] args) throws IOException {
        String text = "Hello world!";
        //Translated text: Hallo Welt!
        System.out.println("Translated text: " + translate("en", "de", text));
    }

    private static String translate(String langFrom, String langTo, String text) throws IOException {
        // INSERT YOU URL HERE
        String urlStr = "https://your.google.script.url" +
                "?q=" + URLEncoder.encode(text, "UTF-8") +
                "&target=" + langTo +
                "&source=" + langFrom;
        URL url = new URL(urlStr);
        StringBuilder response = new StringBuilder();
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    }

}

As it is free, there are QUATA LIMITS: https://docs.google.com/macros/dashboard

Opening new window in HTML for target="_blank"

You don't have that kind of control with a bare a tag. But you can hook up the tag's onclick handler to call window.open(...) with the right parameters. See here for examples: https://developer.mozilla.org/En/DOM/Window.open

I still don't think you can force window over tab directly though-- that depends on the browser and the user's settings.

Validating with an XML schema in Python

An example of a simple validator in Python3 using the popular library lxml

Installation lxml

pip install lxml

If you get an error like "Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?", try to do this first:

# Debian/Ubuntu
apt-get install python-dev python3-dev libxml2-dev libxslt-dev

# Fedora 23+
dnf install python-devel python3-devel libxml2-devel libxslt-devel

The simplest validator

Let's create simplest validator.py

from lxml import etree

def validate(xml_path: str, xsd_path: str) -> bool:

    xmlschema_doc = etree.parse(xsd_path)
    xmlschema = etree.XMLSchema(xmlschema_doc)

    xml_doc = etree.parse(xml_path)
    result = xmlschema.validate(xml_doc)

    return result

then write and run main.py

from validator import validate

if validate("path/to/file.xml", "path/to/scheme.xsd"):
    print('Valid! :)')
else:
    print('Not valid! :(')

A little bit of OOP

In order to validate more than one file, there is no need to create an XMLSchema object every time, therefore:

validator.py

from lxml import etree

class Validator:

    def __init__(self, xsd_path: str):
        xmlschema_doc = etree.parse(xsd_path)
        self.xmlschema = etree.XMLSchema(xmlschema_doc)

    def validate(self, xml_path: str) -> bool:
        xml_doc = etree.parse(xml_path)
        result = self.xmlschema.validate(xml_doc)

        return result

Now we can validate all files in the directory as follows:

main.py

import os
from validator import Validator

validator = Validator("path/to/scheme.xsd")

# The directory with XML files
XML_DIR = "path/to/directory"

for file_name in os.listdir(XML_DIR):
    print('{}: '.format(file_name), end='')

    file_path = '{}/{}'.format(XML_DIR, file_name)

    if validator.validate(file_path):
        print('Valid! :)')
    else:
        print('Not valid! :(')

For more options read here: Validation with lxml

This version of the application is not configured for billing through Google Play

If you're here from 2018, you need to download the APK directly from Play Store and install the "derived" APK. Maybe it is because of Google's Play Store has a feature "App Signing by Google Play".

Pandas every nth row

A solution I came up with when using the index was not viable ( possibly the multi-Gig .csv was too large, or I missed some technique that would allow me to reindex without crashing ).
Walk through one row at a time and add the nth row to a new dataframe.

import pandas as pd
from csv import DictReader

def make_downsampled_df(filename, interval):    
    with open(filename, 'r') as read_obj:
        csv_dict_reader = DictReader(read_obj)
        column_names = csv_dict_reader.fieldnames
        df = pd.DataFrame(columns=column_names)
    
        for index, row in enumerate(csv_dict_reader):
            if index % interval == 0:
               print(str(row))
               df = df.append(row, ignore_index=True)

    return df

How to pass multiple parameters from ajax to mvc controller?

Try this;

function X (id,parameter1,parameter2,...) {
    $.ajax({

            url: '@Url.Action("Actionre", "controller")',+ id,
            type: "Get",
            data: { parameter1: parameter1, parameter2: parameter2,...}

    }).done(function(result) {

        your code...
    });
}

So controller method would looks like :

public ActionResult ActionName(id,parameter1, parameter2,...)
{
   Your Code .......
}

Convert International String to \u Codes in java

Just some basic Methods for that (inspired from native2ascii tool):

/**
 * Encode a String like äöü to \u00e4\u00f6\u00fc
 * 
 * @param text
 * @return
 */
public String native2ascii(String text) {
    if (text == null)
        return text;
    StringBuilder sb = new StringBuilder();
    for (char ch : text.toCharArray()) {
        sb.append(native2ascii(ch));
    }
    return sb.toString();
}

/**
 * Encode a Character like ä to \u00e4
 * 
 * @param ch
 * @return
 */
public String native2ascii(char ch) {
    if (ch > '\u007f') {
        StringBuilder sb = new StringBuilder();
        // write \udddd
        sb.append("\\u");
        StringBuffer hex = new StringBuffer(Integer.toHexString(ch));
        hex.reverse();
        int length = 4 - hex.length();
        for (int j = 0; j < length; j++) {
            hex.append('0');
        }
        for (int j = 0; j < 4; j++) {
            sb.append(hex.charAt(3 - j));
        }
        return sb.toString();
    } else {
        return Character.toString(ch);
    }
}

How to concatenate string variables in Bash

Yet another approach...

> H="Hello "
> U="$H""universe."
> echo $U
Hello universe.

...and yet yet another one.

> H="Hello "
> U=$H"universe."
> echo $U
Hello universe.

Convert NVARCHAR to DATETIME in SQL Server 2008

As your data is nvarchar there is no guarantee it will convert to datetime (as it may hold invalid date/time information) - so a way to handle this is to use ISDATE which I would use within a cross apply. (Cross apply results are reusable hence making is easier for the output formats.)

|                     YOUR_DT |             SQL2008 |
|-----------------------------|---------------------|
|         2013-08-29 13:55:48 | 29-08-2013 13:55:48 |
|    2013-08-29 13:55:48 blah |              (null) |
| 2013-08-29 13:55:48 rubbish |              (null) |

SELECT
  [Your_Dt]
, convert(varchar, ca1.dt_converted ,105) + ' ' + convert(varchar, ca1.dt_converted ,8) AS sql2008
FROM your_table
CROSS apply ( SELECT CASE WHEN isdate([Your_Dt]) = 1
                        THEN convert(datetime,[Your_Dt])
                        ELSE NULL
                     END
            ) AS ca1 (dt_converted)
;

Notes:

You could also introduce left([Your_Dt],19) to only get a string like '2013-08-29 13:55:48' from '2013-08-29 13:55:48 rubbish'

For that specific output I think you will need 2 sql 2008 date styles (105 & 8) sql2012 added for comparison

declare @your_dt as datetime2
set @your_dt = '2013-08-29 13:55:48'

select
  FORMAT(@your_dt, 'dd-MM-yyyy H:m:s') as sql2012
, convert(varchar, @your_dt ,105) + ' ' + convert(varchar, @your_dt ,8) as sql2008

|             SQL2012 |             SQL2008 |
|---------------------|---------------------|
| 29-08-2013 13:55:48 | 29-08-2013 13:55:48 | 

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

What solves my problem: I am using 64 bit Windows 7, so I thought I could install 64 bit Wamp. After I Installed the 32-bit version the error does not appear. So something in the developing process at Wamp went wrong...

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

We had the same issue.

The parent pom file was available in our local repository, but maven still unsuccessfully tried to download it from the central repository, or from the relativePath (there were no files in the relative path).

Turns out, there was a file called "_remote.repositories" in the local repository, which was causing this behavior. After deleting all the files with this name from the complete local repository, we could build our modules.

Python os.path.join on Windows

to join a windows path, try

mypath=os.path.join('c:\\', 'sourcedir')

basically, you will need to escape the slash

How to convert java.sql.timestamp to LocalDate (java8) java.time?

You can do:

timeStamp.toLocalDateTime().toLocalDate();

Note that timestamp.toLocalDateTime() will use the Clock.systemDefaultZone() time zone to make the conversion. This may or may not be what you want.

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

Google Hosted jQuery

  • If you care about older browsers, primarily versions of IE prior to IE9, this is the most widely compatible jQuery version
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  • If you don’t care about oldIE, this one is smaller and faster:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

Backup/Fallback Plan!

  • Either way, you should use a fallback to local just in case the Google CDN fails (unlikely) or is blocked in a location that your users access your site from (slightly more likely), like Iran or sometimes China.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>if (!window.jQuery) { document.write('<script src="/path/to/your/jquery"><\/script>'); }
</script>

Reference: http://websitespeedoptimizations.com/ContentDeliveryNetworkPost.aspx

Send FormData with other field in AngularJS

Assume that we want to get a list of certain images from a PHP server using the POST method.

You have to provide two parameters in the form for the POST method. Here is how you are going to do.

app.controller('gallery-item', function ($scope, $http) {

    var url = 'service.php'; 

    var data = new FormData();

    data.append("function", 'getImageList');
    data.append('dir', 'all');

    $http.post(url, data, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
      }).then(function (response) {

          // This function handles success
        console.log('angular:', response);

    }, function (response) {

        // this function handles error

    });
});

I have tested it on my system and it works.

Unknown URL content://downloads/my_downloads

For those who are getting Error Unknown URI: content://downloads/public_downloads. I managed to solve this by getting a hint given by @Commonsware in this answer. I found out the class FileUtils on GitHub. Here InputStream methods are used to fetch file from Download directory.

 // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);

                if (id != null && id.startsWith("raw:")) {
                    return id.substring(4);
                }

                String[] contentUriPrefixesToTry = new String[]{
                        "content://downloads/public_downloads",
                        "content://downloads/my_downloads",
                        "content://downloads/all_downloads"
                };

                for (String contentUriPrefix : contentUriPrefixesToTry) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
                    try {
                        String path = getDataColumn(context, contentUri, null, null);
                        if (path != null) {
                            return path;
                        }
                    } catch (Exception e) {}
                }

                // path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
                String fileName = getFileName(context, uri);
                File cacheDir = getDocumentCacheDir(context);
                File file = generateFileName(fileName, cacheDir);
                String destinationPath = null;
                if (file != null) {
                    destinationPath = file.getAbsolutePath();
                    saveFileFromUri(context, uri, destinationPath);
                }

                return destinationPath;
            }

Spring 3 RequestMapping: Get path value

Here is how I did it. You can see how I convert the requestedURI to a filesystem path (what this SO question is about). Bonus: and also how to respond with the file.

@RequestMapping(value = "/file/{userId}/**", method = RequestMethod.GET)
public void serveFile(@PathVariable("userId") long userId, HttpServletRequest request, HttpServletResponse response) {
    assert request != null;
    assert response != null;

    // requestURL:  http://192.168.1.3:8080/file/54/documents/tutorial.pdf
    // requestURI:  /file/54/documents/tutorial.pdf
    // servletPath: /file/54/documents/tutorial.pdf
    // logger.debug("requestURL: " + request.getRequestURL());
    // logger.debug("requestURI: " + request.getRequestURI());
    // logger.debug("servletPath: " + request.getServletPath());

    String requestURI = request.getRequestURI();
    String relativePath = requestURI.replaceFirst("^/file/", "");

    Path path = Paths.get("/user_files").resolve(relativePath);
    try {
        InputStream is = new FileInputStream(path.toFile());  
        org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
        response.flushBuffer();
    } catch (IOException ex) {
        logger.error("Error writing file to output stream. Path: '" + path + "', requestURI: '" + requestURI + "'");
        throw new RuntimeException("IOError writing file to output stream");
    }
}

How to write multiple line string using Bash with variables?

I'm using Mac OS and to write multiple lines in a SH Script following code worked for me

#! /bin/bash
FILE_NAME="SomeRandomFile"

touch $FILE_NAME

echo """I wrote all
the  
stuff
here.
And to access a variable we can use
$FILE_NAME  

""" >> $FILE_NAME

cat $FILE_NAME

Please don't forget to assign chmod as required to the script file. I have used

chmod u+x myScriptFile.sh

Check if an array contains duplicate values

Late answer but can be helpful

function areThereDuplicates(args) {

    let count = {};
    for(let i = 0; i < args.length; i++){
         count[args[i]] = 1 + (count[args[i]] || 0);
    }
    let found = Object.keys(count).filter(function(key) {
        return count[key] > 1;
    });
    return found.length ? true : false; 
}

areThereDuplicates([1,2,5]);

How to enable cURL in PHP / XAMPP

For windows OS users (It worked for me) in XAMPP.

step 1: Go to C:\xampp\php\php.ini

edit this file php.ini

find curl- you will see a line ;extension=php_curl.dll.

remove semicolon (;)extension=php_curl.dll. so this line looks like

;extension=php_curl.dll

to

extension=php_curl.dll

step 2: copy ssleay32.dll, libeay32.dll from php folder. paste it in C:\Windows\System32\

step 3: Restart the system . Curl will run successfully.

Advantages of SQL Server 2008 over SQL Server 2005?

Someone with more reputation can copy this into the main answer:

  • Change Tracking. Allows you to get info on what changes happened to which rows since a specific version.
  • Change Data Capture. Allows all changes to be captured and queried. (Enterprise)

How to find the Vagrant IP?

Open a terminal, cd to the path of your Vagrantfile and write this

(Linux)

vagrant ssh -c "hostname -I | cut -d' ' -f2" 2>/dev/null

(OS X)

vagrant ssh -c "hostname -I | cut -d' ' -f2" 2>/dev/null | pbcopy

The command for Linux also works for windows. I have no way to test, sorry.

source: https://coderwall.com/p/etzdmq/get-vagrant-box-guest-ip-from-host

Handler vs AsyncTask vs Thread

It depends which one to chose is based on the requirement

Handler is mostly used to switch from other thread to main thread, Handler is attached to a looper on which it post its runnable task in queue. So If you are already in other thread and switch to main thread then you need handle instead of async task or other thread

If Handler created in other than main thread which is not a looper is will not give error as handle is created the thread, that thread need to be made a lopper

AsyncTask is used to execute code for few seconds which run on background thread and gives its result to main thread ** *AsyncTask Limitations 1. Async Task is not attached to life cycle of activity and it keeps run even if its activity destroyed whereas loader doesn't have this limitation 2. All Async Tasks share the same background thread for execution which also impact the app performance

Thread is used in app for background work also but it doesn't have any call back on main thread. If requirement suits some threads instead of one thread and which need to give task many times then thread pool executor is better option.Eg Requirement of Image loading from multiple url like glide.

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

Use these following commands, this will solve the error:

sudo apt-get install postgresql

then fire:

sudo apt-get install python-psycopg2

and last:

sudo apt-get install libpq-dev

When do I need a fb:app_id or fb:admins?

Including the fb:app_id tag in your HTML HEAD will allow the Facebook scraper to associate the Open Graph entity for that URL with an application. This will allow any admins of that app to view Insights about that URL and any social plugins connected with it.

The fb:admins tag is similar, but allows you to just specify each user ID that you would like to give the permission to do the above.

You can include either of these tags or both, depending on how many people you want to admin the Insights, etc. A single as fb:admins is pretty much a minimum requirement. The rest of the Open Graph tags will still be picked up when people share and like your URL, however it may cause problems in the future, so please include one of the above.

fb:admins is specified like this:
<meta property="fb:admins" content="USER_ID"/>
OR
<meta property="fb:admins" content="USER_ID,USER_ID2,USER_ID3"/>

and fb:app_id like this:
<meta property="fb:app_id" content="APPID"/>

How can I check if a scrollbar is visible?

(scrollWidth/Height - clientWidth/Height) is a good indicator for the presence of a scrollbar, but it will give you a "false positive" answer on many occasions. if you need to be accurate i would suggest using the following function. instead of trying to guess if the element is scrollable - you can scroll it...

_x000D_
_x000D_
function isScrollable( el ){_x000D_
  var y1 = el.scrollTop;_x000D_
  el.scrollTop  += 1;_x000D_
  var y2 = el.scrollTop;_x000D_
  el.scrollTop  -= 1;_x000D_
  var y3 = el.scrollTop;_x000D_
  el.scrollTop   = y1;_x000D_
  var x1 = el.scrollLeft;_x000D_
  el.scrollLeft += 1;_x000D_
  var x2 = el.scrollLeft;_x000D_
  el.scrollLeft -= 1;_x000D_
  var x3 = el.scrollLeft;_x000D_
  el.scrollLeft  = x1;_x000D_
  return {_x000D_
    horizontallyScrollable: x1 !== x2 || x2 !== x3,_x000D_
    verticallyScrollable: y1 !== y2 || y2 !== y3_x000D_
  }_x000D_
}_x000D_
function check( id ){_x000D_
  alert( JSON.stringify( isScrollable( document.getElementById( id ))));_x000D_
}
_x000D_
#outer1, #outer2, #outer3 {_x000D_
  background-color: pink;_x000D_
  overflow: auto;_x000D_
  float: left;_x000D_
}_x000D_
#inner {_x000D_
  width:  150px;_x000D_
  height: 150px;_x000D_
}_x000D_
button {  margin: 2em 0 0 1em; }
_x000D_
<div id="outer1" style="width: 100px; height: 100px;">_x000D_
  <div id="inner">_x000D_
    <button onclick="check('outer1')">check if<br>scrollable</button>_x000D_
  </div>_x000D_
</div>_x000D_
<div id="outer2" style="width: 200px; height: 100px;">_x000D_
  <div id="inner">_x000D_
    <button onclick="check('outer2')">check if<br>scrollable</button>_x000D_
  </div>_x000D_
</div>_x000D_
<div id="outer3" style="width: 100px; height: 180px;">_x000D_
  <div id="inner">_x000D_
    <button onclick="check('outer3')">check if<br>scrollable</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I split a string into segments of n characters?

Coming a little later to the discussion but here a variation that's a little faster than the substring + array push one.

// substring + array push + end precalc
var chunks = [];

for (var i = 0, e = 3, charsLength = str.length; i < charsLength; i += 3, e += 3) {
    chunks.push(str.substring(i, e));
}

Pre-calculating the end value as part of the for loop is faster than doing the inline math inside substring. I've tested it in both Firefox and Chrome and they both show speedup.

You can try it here

Passing arguments to require (when loading module)

Yes. In your login module, just export a single function that takes the db as its argument. For example:

module.exports = function(db) {
  ...
};

How to install Android app on LG smart TV?

Thanks for the research FIRESTICK is a solution for non Android based but there's another one Im using if you guys want to try it let me know...

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP, PHILCO and TOSHIBA.

How to get root access on Android emulator?

I used part of the method from the solutions above; however, they did not work completely. On the latest version of Andy, this worked for me:

On Andy (Root Shell) [To get, right click the HandyAndy icon and select Term Shell]

Inside the shell, run these commands:

mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
cd /system/bin
cat sh > su && chmod 4775 su

Then, install SuperSU and install SU binary. This will replace the SU binary we just created. (Optional) Remove SuperSU and install Superuser by CWM. Install the su binary again. Now, root works!

How to get the title of HTML page with JavaScript?

Put in the URL bar and then click enter:

javascript:alert(document.title);

You can select and copy the text from the alert depending on the website and the web browser you are using.

Random word generator- Python

Solution for Python 3

For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.

import urllib.request

word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()

Output:

>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
 'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
 'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]

And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:

import random
upper_words = [word for word in words if word[0].isupper()]
name_words  = [word for word in upper_words if not word.isupper()]
rand_name   = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])

And some random names:

>>> for n in range(10):
        ' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])

    'Semiramis Sicilian'
    'Julius Genevieve'
    'Rwanda Cohn'
    'Quito Sutherland'
    'Eocene Wheller'
    'Olav Jove'
    'Weldon Pappas'
    'Vienna Leyden'
    'Io Dave'
    'Schwartz Stromberg'

How to generate the "create table" sql statement for an existing table in postgreSQL

In pgadminIII database>>schemas>>tables>> right click on 'Your table'>>scripts>> 'Select any one (Create,Insert,Update,Delete..)'

How to exit a function in bash

Use return operator:

function FUNCT {
  if [ blah is false ]; then
    return 1 # or return 0, or even you can omit the argument.
  else
    keep running the function
  fi
}

Perl - If string contains text?

if ($string =~ m/something/) {
   # Do work
}

Where something is a regular expression.

Gradle to execute Java class (without modifying build.gradle)

Expanding on First Zero's answer, I'm guess you want something where you can also run gradle build without errors.

Both gradle build and gradle -PmainClass=foo runApp work with this:

task runApp(type:JavaExec) {
    classpath = sourceSets.main.runtimeClasspath

    main = project.hasProperty("mainClass") ? project.getProperty("mainClass") : "package.MyDefaultMain"
}

where you set your default main class.

Do C# Timers elapse on a separate thread?

For System.Timers.Timer:

See Brian Gideon's answer below

For System.Threading.Timer:

MSDN Documentation on Timers states:

The System.Threading.Timer class makes callbacks on a ThreadPool thread and does not use the event model at all.

So indeed the timer elapses on a different thread.

How to check if a map contains a key in Go?

As noted by other answers, the general solution is to use an index expression in an assignment of the special form:

v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]
var v, ok T = a[x]

This is nice and clean. It has some restrictions though: it must be an assignment of special form. Right-hand side expression must be the map index expression only, and the left-hand expression list must contain exactly 2 operands, first to which the value type is assignable, and a second to which a bool value is assignable. The first value of the result of this special form will be the value associated with the key, and the second value will tell if there is actually an entry in the map with the given key (if the key exists in the map). The left-hand side expression list may also contain the blank identifier if one of the results is not needed.

It's important to know that if the indexed map value is nil or does not contain the key, the index expression evaluates to the zero value of the value type of the map. So for example:

m := map[int]string{}
s := m[1] // s will be the empty string ""
var m2 map[int]float64 // m2 is nil!
f := m2[2] // f will be 0.0

fmt.Printf("%q %f", s, f) // Prints: "" 0.000000

Try it on the Go Playground.

So if we know that we don't use the zero value in our map, we can take advantage of this.

For example if the value type is string, and we know we never store entries in the map where the value is the empty string (zero value for the string type), we can also test if the key is in the map by comparing the non-special form of the (result of the) index expression to the zero value:

m := map[int]string{
    0: "zero",
    1: "one",
}

fmt.Printf("Key 0 exists: %t\nKey 1 exists: %t\nKey 2 exists: %t",
    m[0] != "", m[1] != "", m[2] != "")

Output (try it on the Go Playground):

Key 0 exists: true
Key 1 exists: true
Key 2 exists: false

In practice there are many cases where we don't store the zero-value value in the map, so this can be used quite often. For example interfaces and function types have a zero value nil, which we often don't store in maps. So testing if a key is in the map can be achieved by comparing it to nil.

Using this "technique" has another advantage too: you can check existence of multiple keys in a compact way (you can't do that with the special "comma ok" form). More about this: Check if key exists in multiple maps in one condition

Getting the zero value of the value type when indexing with a non-existing key also allows us to use maps with bool values conveniently as sets. For example:

set := map[string]bool{
    "one": true,
    "two": true,
}

fmt.Println("Contains 'one':", set["one"])

if set["two"] {
    fmt.Println("'two' is in the set")
}
if !set["three"] {
    fmt.Println("'three' is not in the set")
}

It outputs (try it on the Go Playground):

Contains 'one': true
'two' is in the set
'three' is not in the set

See related: How can I create an array that contains unique strings?

What is this weird colon-member (" : ") syntax in the constructor?

You are correct, this is indeed a way to initialize member variables. I'm not sure that there's much benefit to this, other than clearly expressing that it's an initialization. Having a "bar=num" inside the code could get moved around, deleted, or misinterpreted much more easily.

Artificially create a connection timeout error

Plug in your network cable into a switch which has no other connection/cables. That should work imho.

How can I use a reportviewer control in an asp.net mvc 3 razor view?

Here is the complete solution for directly integrating a report-viewer control (as well as any asp.net server side control) in an MVC .aspx view, which will also work on a report with multiple pages (unlike Adrian Toman's answer) and with AsyncRendering set to true, (based on "Pro ASP.NET MVC Framework" by Steve Sanderson).

What one needs to do is basically:

  1. Add a form with runat = "server"

  2. Add the control, (for report-viewer controls it can also sometimes work even with AsyncRendering="True" but not always, so check in your specific case)

  3. Add server side scripting by using script tags with runat = "server"

  4. Override the Page_Init event with the code shown below, to enable the use of PostBack and Viewstate

Here is a demonstration:

<form ID="form1" runat="server">
    <rsweb:ReportViewer ID="ReportViewer1" runat="server" />
</form>
<script runat="server">
    protected void Page_Init(object sender, EventArgs e)
    {
        Context.Handler = Page;
    }
    //Other code needed for the report viewer here        
</script>

It is of course recommended to fully utilize the MVC approach, by preparing all needed data in the controller, and then passing it to the view via the ViewModel.

This will allow reuse of the View!

However this is only said for data this is needed for every post back, or even if they are required only for initialization if it is not data intensive, and the data also has not to be dependent on the PostBack and ViewState values.

However even data intensive can sometimes be encapsulated into a lambda expression and then passed to the view to be called there.

A couple of notes though:

  • By doing this the view essentially turns into a web form with all it's drawbacks, (i.e. Postbacks, and the possibility of non Asp.NET controls getting overriden)
  • The hack of overriding Page_Init is undocumented, and it is subject to change at any time

Nginx not picking up site in sites-enabled?

Include sites-available/default in sites-enabled/default. It requires only one line.

In sites-enabled/default (new config version?):

It seems that the include path is relative to the file that included it

include sites-available/default;

See the include documentation.


I believe that certain versions of nginx allows including/linking to other files purely by having a single line with the relative path to the included file. (At least that's what it looked like in some "inherited" config files I've been using, until a new nginx version broke them.)

In sites-enabled/default (old config version?):

It seems that the include path is relative to the current file

../sites-available/default

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Also, if you can't change class B, you can fix the error by using multiple inheritance.

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

push multiple elements to array

If you want to add multiple items, you have to use the spread operator

a = [1,2]
b = [3,4,5,6]
a.push(...b)

The output will be

a = [1,2,3,4,5,6]

TypeError: 'bool' object is not callable

You do cls.isFilled = True. That overwrites the method called isFilled and replaces it with the value True. That method is now gone and you can't call it anymore. So when you try to call it again you get an error, since it's not there anymore.

The solution is use a different name for the variable than you do for the method.

How to get CSS to select ID that begins with a string (not in Javascript)?

[id^=product]

^= indicates "starts with". Conversely, $= indicates "ends with".

The symbols are actually borrowed from Regex syntax, where ^ and $ mean "start of string" and "end of string" respectively.

See the specs for full information.