Programs & Examples On #Oracleinternetdirectory

Change name of folder when cloning from GitHub?

Here is one more answer from @Marged in comments

  1. Create a folder with the name you want
  2. Run the command below from the folder you created

    git clone <path to your online repo> .
    

How can I get the count of line in a file in an efficient way?

Do You need exact number of lines or only its approximation? I happen to process large files in parallel and often I don't need to know exact count of lines - I then revert to sampling. Split the file into ten 1MB chunks and count lines in each chunk, then multiply it by 10 and You'll receive pretty good approximation of line count.

How to change value of object which is inside an array using JavaScript or jQuery?

Let you want to update value of array[2] = "data"

    for(i=0;i<array.length;i++){
      if(i == 2){
         array[i] = "data";
        }
    }

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

Seems like the only way to get decimal in a pretty (for me) form requires some ridiculous code.

The only solution I got so far:

CASE WHEN xy>0 and xy<1 then '0' || to_char(xy) else to_char(xy)

xy is a decimal.

xy             query result
0.8            0.8  --not sth like .80
10             10  --not sth like 10.00

How to check whether mod_rewrite is enable on server?

This works on CentOS:

$ sudo httpd -M |grep rewrite_module

Should output rewrite_module (shared)

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

I had a similar issue and solved after running these instructions!

npm install npm -g
npm install --save-dev @angular/cli@latest
npm install
npm start

Replace contents of factor column in R dataframe

You can use the function revalue from the package plyr to replace values in a factor vector.

In your example to replace the factor virginica by setosa:

 data(iris)
 library(plyr)
 revalue(iris$Species, c("virginica" = "setosa")) -> iris$Species

How to check if curl is enabled or disabled

Just return your existing check from a function.

function _isCurl(){
    return function_exists('curl_version');
}

Drop data frame columns by name

Here is a dplyr way to go about it:

#df[ -c(1,3:6, 12) ]  # original
df.cut <- df %>% select(-col.to.drop.1, -col.to.drop.2, ..., -col.to.drop.6)  # with dplyr::select()

I like this because it's intuitive to read & understand without annotation and robust to columns changing position within the data frame. It also follows the vectorized idiom using - to remove elements.

Why does the program give "illegal start of type" error?

You have a misplaced closing brace before the return statement.

Double % formatting question for printf in Java

Yes, %d means decimal, but it means decimal number system, not decimal point.

Further, as a complement to the former post, you can also control the number of decimal points to show. Try this,

System.out.printf("%.2f %.1f",d,f); // prints 1.20 1.2

For more please refer to the API docs.

Getting list of parameter names inside python function

Well we don't actually need inspect here.

>>> func = lambda x, y: (x, y)
>>> 
>>> func.__code__.co_argcount
2
>>> func.__code__.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
...  print(func2.__code__.co_varnames)
...  pass # Other things
... 
>>> func2(3,3)
('x', 'y')
>>> 
>>> func2.__defaults__
(3,)

For Python 2.5 and older, use func_code instead of __code__, and func_defaults instead of __defaults__.

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

Increase the Windows process limit to 3gb. (via boot.ini or Vista boot manager)

Cloning a private Github repo

In case you have two-factor authentication enabled, make sure that you create a new access token and not regenerate an old one.

That didn't seem to work in my case.

Search for string within text column in MySQL

Using like might take longer time so use full_text_search:

SELECT * FROM items WHERE MATCH(items.xml) AGAINST ('your_search_word')

Integer division: How do you produce a double?

I don't like casting primitives, who knows what may happen.

Why do you have an irrational fear of casting primitives? Nothing bad will happen when you cast an int to a double. If you're just not sure of how it works, look it up in the Java Language Specification. Casting an int to double is a widening primitive conversion.

You can get rid of the extra pair of parentheses by casting the denominator instead of the numerator:

double d = num / (double) denom;

Passing event and argument to v-on in Vue.js

You can also do something like this...

<input @input="myHandler('foo', 'bar', ...arguments)">

Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.

Store multiple values in single key in json

Use arrays:

{
    "number": ["1", "2", "3"],
    "alphabet": ["a", "b", "c"]
}

You can the access the different values from their position in the array. Counting starts at left of array at 0. myJsonObject["number"][0] == 1 or myJsonObject["alphabet"][2] == 'c'

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

The extend method for example in jQuery or PrototypeJS, copies all properties from the source to the destination object.

Now about the prototype property, it is a member of function objects, it is part of the language core.

Any function can be used as a constructor, to create new object instances. All functions have this prototype property.

When you use the new operator with on a function object, a new object will be created, and it will inherit from its constructor prototype.

For example:

function Foo () {
}
Foo.prototype.bar = true;

var foo = new Foo();

foo.bar; // true
foo instanceof Foo; // true
Foo.prototype.isPrototypeOf(foo); // true

How to restart a single container with docker-compose

Since some of the other answers include info on rebuilding, and my use case also required a rebuild, I had a better solution (compared to those).

There's still a way to easily target just the one single worker container that both rebuilds + restarts it in a single line, albeit it's not actually a single command. The best solution for me was simply rebuild and restart:

docker-compose build worker && docker-compose restart worker

This accomplishes both major goals at once for me:

  1. Targets the single worker container
  2. Rebuilds and restarts it in a single line

Hope this helps anyone else getting here.

How to Copy Text to Clip Board in Android?

With Jetpack Compose, it's really easy:

AmbientClipboardManager.current.setText(AnnotatedString("Copied Text"))

How to decode jwt token in javascript without using a library?

Simple NodeJS Solution for Decoding a JSON Web Token (JWT)

function decodeTokenComponent(value) {
    const buff = new Buffer(value, 'base64')
    const text = buff.toString('ascii')
    return JSON.parse(text)
}

const token = 'xxxxxxxxx.XXXXXXXX.xxxxxxxx'
const [headerEncoded, payloadEncoded, signature] = token.split('.')
const [header, payload] = [headerEncoded, payloadEncoded].map(decodeTokenComponent)

console.log(`header: ${header}`)
console.log(`payload: ${payload}`)
console.log(`signature: ${signature}`)

Error handling in AngularJS http get then construct

You need to add an additional parameter:

$http.get(url).then(
    function(response) {
        console.log('get',response)
    },
    function(data) {
        // Handle error here
    })

reStructuredText tool support

Salvaging (and extending) the list from an old version of the Wikipedia page:

Documentation

Implementations

Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.

Python - Docutils

The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:

  • rst2html - from reStructuredText to HTML
  • rst2xml - from reStructuredText to XML
  • rst2latex - from reStructuredText to LaTeX
  • rst2odt - from reStructuredText to ODF Text (word processor) document.
  • rst2s5 - from reStructuredText to S5, a Simple Standards-based Slide Show System
  • rst2man - from reStructuredText to Man page

Haskell - Pandoc

Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.

There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),

  • POT truncates input rather more shortly. The POT user must render input in chunks that could be rendered whole by the ROR.
  • POT output lacks the helpful error messages displayed by the ROR (and generated by docutils)

Java - JRst

JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.

Scala - Laika

Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.

Perl

PHP

C#/.NET

Nim/C

The Nim compiler features the commands rst2htmland rst2tex which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:

  • rst - implements a reStructuredText parser
  • rstast - implements an AST for the reStructuredText parser
  • rstgen - implements a generator of HTML/Latex from reStructuredText

Other 3rd party converters

Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.

From reStructuredText

  • restview - This pip-installable python package requires docutils, which does the actual rendering. restview's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
    1. starts a small web server
    2. calls docutils to render your document(s) to HTML
    3. calls your device's browser to display the output HTML.
  • rst2pdf - from reStructuredText to PDF
  • rst2odp - from reStructuredText to ODF Presentation
  • rst2beamer - from reStructuredText to LaTeX beamer Presentation class
  • Wikir - from reStructuredText to a Google (and possibly other) Wiki formats
  • rst2qhc - Convert a collection of reStructuredText files into a Qt (toolkit) Help file and (optional) a Qt Help Project file

To reStructuredText

  • xml2rst is an XSLT script to convert Docutils internal XML representation (back) to reStructuredText
  • Pandoc (see above) can also convert from Markdown, HTML and LaTeX to reStructuredText
  • db2rst is a simple and limited DocBook to reStructuredText translator
  • pod2rst - convert .pod files to reStructuredText files

Extensions

Some projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.

Sphinx

The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.

rest2web

rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.

Pygments

Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.

Free Editors

While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.

Emacs

The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el

Vim

The vim-common package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:

Jed

There is a rst mode for the Jed programmers editor.

gedit

gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.

Geany

Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).

Leo

Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).

It also provides a way to preview the resulting HTML, in a "viewrendered" pane.

FTE

The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.

PyK

PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.

Eclipse

The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.

NoTex

NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.

Notepad++

Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.

Visual Studio Code

Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.

Dedicated reStructuredText Editors

Proprietary editors

Sublime Text

Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.

BBEdit / TextWrangler

BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.

TextMate

TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.

Intype

Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.

E Text Editor

E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.

PyCharm

PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).instant preview)

Wiki

here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:

MediaWiki

MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst> and </rst>.

MoinMoin

MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.

There is a reStructuredText Parser for MoinMoin.

Trac

Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.

This Wiki

This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.

rstiki

rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.

ikiwiki

Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.

Web Services

Sandbox

An Online reStructuredText editor can be used to play with the markup and see the results immediately.

Blogging frameworks

WordPress

WordPreSt reStructuredText plugin for WordPress. (PHP)

Zine

reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)

pelican

Pelican is a static blog generator that supports writing articles in ReST. (Python)

hyde

Hyde is a static website generator that supports ReST. (Python)

Acrylamid

Acrylamid is a static blog generator that supports writing articles in ReST. (Python)

Nikola

Nikola is a Static Site and Blog Generator that supports ReST. (Python)

ipsum genera

Ipsum genera is a static blog generator written in Nim.

Yozuch

Yozuch is a static blog generator written in Python.

More

jQuery ajax request with json response, how to?

Try this code. You don't require the parse function because your data type is JSON so it is return JSON object.

$.ajax({
    url : base_url+"Login/submit",
    type: "POST",
    dataType: "json",
    data : {
        'username': username,
        'password': password
    },
    success: function(data)
    {
        alert(data.status);
    }
});

Change header background color of modal of twitter bootstrap

A little late to the party, but here's another solution.

Simply adjusting the class of the modal to something like alert-danger does work, however it removes the top rounded corners of the modal.

A workaround is to give the element with modal-header an additional class of panel-heading, e.g.

<div class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header panel-heading"> <!-- change here -->
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body&hellip;</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Then, to change the heading color you can do something like (assuming you're using jQUery)

jQuery('.modal-content').addClass('panel-danger')

How to write a caption under an image?

CSS

#images{
    text-align:center;
    margin:50px auto; 
}
#images a{
    margin:0px 20px;
    display:inline-block;
    text-decoration:none;
    color:black;
 }

HTML

<div id="images">
    <a href="http://xyz.com/hello">
        <img src="hello.png" width="100px" height="100px">
        <div class="caption">Caption 1</div>
    </a>
    <a href="http://xyz.com/hi">
        <img src="hi.png" width="100px" height="100px"> 
        <div class="caption">Caption 2</div>
    </a>
</div>?

?A fiddle is here.

GitHub: invalid username or password

Since you probably want to keep 2FA enabled for your account, you can set up a ssh key and that way you won't need to type your Github credentials every time you want to push work to Github.

You can find all the ssh setup steps in the documentation. First, make sure you don't currently have any ssh keys (id_rsa.pub, etc.) with $ ls -al ~/.ssh

Install apk without downloading

For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.

    Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);

If you want it to download and install from your own server then use the following code

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
    startActivity(intent);

Resizing an iframe based on content

When you want to zoom out a web page to fit it into the iframe size:

  1. You should resize the iframe to fit it with the content
  2. Then you should zoom out the whole iframe with the loaded web page content

Here is an example:

<div id="wrap">
   <IFRAME ID="frame" name="Main" src ="http://www.google.com" />
</div>

<style type="text/css">
    #wrap { width: 130px; height: 130px; padding: 0; overflow: hidden; }
    #frame { width: 900px; height: 600px; border: 1px solid black; }
    #frame { zoom:0.15; -moz-transform:scale(0.15);-moz-transform-origin: 0 0; }
</style>

Android SDK manager won't open

I'd encountered the same problem. When running the android.bat I found the solution (if Java is installed in the 'normal' Windows directory, ie 'program files') you need to put quotes surrounding "c:/program files/" etc etc. Otherwise it cannot find java on "C:/program". (me dislikes spaces)

Pandas DataFrame to List of Dictionaries

If you are interested in only selecting one column this will work.

df[["item1"]].to_dict("records")

The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.

df["item1"].to_dict("records")

I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.

Where can I get a list of Ansible pre-defined variables?

Argh! From the FAQ:

How do I see a list of all of the ansible_ variables? Ansible by default gathers “facts” about the machines under management, and these facts can be accessed in Playbooks and in templates. To see a list of all of the facts that are available about a machine, you can run the “setup” module as an ad-hoc action:

ansible -m setup hostname

This will print out a dictionary of all of the facts that are available for that particular host.

Here is the output for my vagrant virtual machine called scdev:

scdev | success >> {
    "ansible_facts": {                                                                                                 
        "ansible_all_ipv4_addresses": [                                                                                
            "10.0.2.15",                                                                                               
            "192.168.10.10"                                                                                            
        ],                                                                                                             
        "ansible_all_ipv6_addresses": [                                                                                
            "fe80::a00:27ff:fe12:9698",                                                                                
            "fe80::a00:27ff:fe74:1330"                                                                                 
        ],                                                                                                             
        "ansible_architecture": "i386",                                                                                
        "ansible_bios_date": "12/01/2006",                                                                             
        "ansible_bios_version": "VirtualBox",                                                                          
        "ansible_cmdline": {                                                                                           
            "BOOT_IMAGE": "/vmlinuz-3.2.0-23-generic-pae",                                                             
            "quiet": true,                                                                                             
            "ro": true,                                                                                                
            "root": "/dev/mapper/precise32-root"                                                                       
        },                                                                                                             
        "ansible_date_time": {                                                                                         
            "date": "2013-09-17",                                                                                      
            "day": "17",                                                                                               
            "epoch": "1379378304",                                                                                     
            "hour": "00",                                                                                              
            "iso8601": "2013-09-17T00:38:24Z",                                                                         
            "iso8601_micro": "2013-09-17T00:38:24.425092Z",                                                            
            "minute": "38",                                                                                            
            "month": "09",                                                                                             
            "second": "24",                                                                                            
            "time": "00:38:24",                                                                                        
            "tz": "UTC",                                                                                               
            "year": "2013"                                                                                             
        },                                                                                                             
        "ansible_default_ipv4": {                                                                                      
            "address": "10.0.2.15",                                                                                    
            "alias": "eth0",                                                                                           
            "gateway": "10.0.2.2",                                                                                     
            "interface": "eth0",                                                                                       
            "macaddress": "08:00:27:12:96:98",                                                                         
            "mtu": 1500,                                                                                               
            "netmask": "255.255.255.0",                                                                                
            "network": "10.0.2.0",                                                                                     
            "type": "ether"                                                                                            
        },                                                                                                             
        "ansible_default_ipv6": {},                                                                                    
        "ansible_devices": {                                                                                           
            "sda": {                                                                                                   
                "holders": [],                                                                                         
                "host": "SATA controller: Intel Corporation 82801HM/HEM (ICH8M/ICH8M-E) SATA Controller [AHCI mode] (rev 02)",                                                                                                                
                "model": "VBOX HARDDISK",                                                                              
                "partitions": {                                                                                        
                    "sda1": {                                                                                          
                        "sectors": "497664",                                                                           
                        "sectorsize": 512,                                                                             
                        "size": "243.00 MB",                                                                           
                        "start": "2048"                                                                                
                    },                                                                                                 
                    "sda2": {                                                                                          
                        "sectors": "2",                                                                                
                        "sectorsize": 512,                                                                             
                        "size": "1.00 KB",                                                                             
                        "start": "501758"                                                                              
                    },                                                                                                 
                },                                                                                                     
                "removable": "0",                                                                                      
                "rotational": "1",                                                                                     
                "scheduler_mode": "cfq",                                                                               
                "sectors": "167772160",                                                                                
                "sectorsize": "512",                                                                                   
                "size": "80.00 GB",                                                                                    
                "support_discard": "0",                                                                                
                "vendor": "ATA"                                                                                        
            },                                                                                                         
            "sr0": {                                                                                                   
                "holders": [],                                                                                         
                "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",                           
                "model": "CD-ROM",                                                                                     
                "partitions": {},                                                                                      
                "removable": "1",                                                                                      
                "rotational": "1",                                                                                     
                "scheduler_mode": "cfq",                                                                               
                "sectors": "2097151",                                                                                  
                "sectorsize": "512",                                                                                   
                "size": "1024.00 MB",                                                                                  
                "support_discard": "0",                                                                                
                "vendor": "VBOX"                                                                                       
            },                                                                                                         
            "sr1": {                                                                                                   
                "holders": [],                                                                                         
                "host": "IDE interface: Intel Corporation 82371AB/EB/MB PIIX4 IDE (rev 01)",                           
                "model": "CD-ROM",                                                                                     
                "partitions": {},                                                                                      
                "removable": "1",                                                                                      
                "rotational": "1",                                                                                     
                "scheduler_mode": "cfq",                                                                               
                "sectors": "2097151",                                                                                  
                "sectorsize": "512",                                                                                   
                "size": "1024.00 MB",                                                                                  
                "support_discard": "0",                                                                                
                "vendor": "VBOX"                                                                                       
            }                                                                                                          
        },                                                                                                             
        "ansible_distribution": "Ubuntu",                                                                              
        "ansible_distribution_release": "precise",                                                                     
        "ansible_distribution_version": "12.04",                                                                       
        "ansible_domain": "",                                                                                          
        "ansible_eth0": {                                                                                              
            "active": true,                                                                                            
            "device": "eth0",                                                                                          
            "ipv4": {                                                                                                  
                "address": "10.0.2.15",                                                                                
                "netmask": "255.255.255.0",                                                                            
                "network": "10.0.2.0"                                                                                  
            },                                                                                                         
            "ipv6": [                                                                                                  
                {                                                                                                      
                    "address": "fe80::a00:27ff:fe12:9698",                                                             
                    "prefix": "64",                                                                                    
                    "scope": "link"                                                                                    
                }                                                                                                      
            ],                                                                                                         
            "macaddress": "08:00:27:12:96:98",                                                                         
            "module": "e1000",                                                                                         
            "mtu": 1500,                                                                                               
            "type": "ether"                                                                                            
        },                                                                                                             
        "ansible_eth1": {                                                                                              
            "active": true,                                                                                            
            "device": "eth1",                                                                                          
            "ipv4": {                                                                                                  
                "address": "192.168.10.10",                                                                            
                "netmask": "255.255.255.0",                                                                            
                "network": "192.168.10.0"                                                                              
            },                                                                                                         
            "ipv6": [                                                                                                  
                {                                                                                                      
                    "address": "fe80::a00:27ff:fe74:1330",                                                             
                    "prefix": "64",                                                                                    
                    "scope": "link"                                                                                    
                }                                                                                                      
            ],                                                                                                         
            "macaddress": "08:00:27:74:13:30",                                                                         
            "module": "e1000",                                                                                         
            "mtu": 1500,                                                                                               
            "type": "ether"                                                                                            
        },                                                                                                             
        "ansible_form_factor": "Other",                                                                                
        "ansible_fqdn": "scdev",                                                                                       
        "ansible_hostname": "scdev",                                                                                   
        "ansible_interfaces": [                                                                                        
            "lo",                                                                                                      
            "eth1",                                                                                                    
            "eth0"                                                                                                     
        ],                                                                                                             
        "ansible_kernel": "3.2.0-23-generic-pae",                                                                      
        "ansible_lo": {                                                                                                
            "active": true,                                                                                            
            "device": "lo",                                                                                            
            "ipv4": {                                                                                                  
                "address": "127.0.0.1",                                                                                
                "netmask": "255.0.0.0",                                                                                
                "network": "127.0.0.0"                                                                                 
            },                                                                                                         
            "ipv6": [                                                                                                  
                {                                                                                                      
                    "address": "::1",                                                                                  
                    "prefix": "128",                                                                                   
                    "scope": "host"                                                                                    
                }                                                                                                      
            ],                                                                                                         
            "mtu": 16436,                                                                                              
            "type": "loopback"                                                                                         
        },                                                                                                             
        "ansible_lsb": {                                                                                               
            "codename": "precise",                                                                                     
            "description": "Ubuntu 12.04 LTS",                                                                         
            "id": "Ubuntu",                                                                                            
            "major_release": "12",                                                                                     
            "release": "12.04"                                                                                         
        },                                                                                                             
        "ansible_machine": "i686",                                                                                     
        "ansible_memfree_mb": 23,                                                                                      
        "ansible_memtotal_mb": 369,                                                                                    
        "ansible_mounts": [                                                                                            
            {                                                                                                          
                "device": "/dev/mapper/precise32-root",                                                                
                "fstype": "ext4",                                                                                      
                "mount": "/",                                                                                          
                "options": "rw,errors=remount-ro",                                                                     
                "size_available": 77685088256,                                                                         
                "size_total": 84696281088                                                                              
            },                                                                                                         
            {                                                                                                          
                "device": "/dev/sda1",                                                                                 
                "fstype": "ext2",                                                                                      
                "mount": "/boot",                                                                                      
                "options": "rw",                                                                                       
                "size_available": 201044992,                                                                           
                "size_total": 238787584                                                                                
            },                                                                                                         
            {                                                                                                          
                "device": "/vagrant",                                                                                  
                "fstype": "vboxsf",                                                                                    
                "mount": "/vagrant",                                                                                   
                "options": "uid=1000,gid=1000,rw",                                                                     
                "size_available": 42013151232,                                                                         
                "size_total": 484145360896                                                                             
            }                                                                                                          
        ],                                                                                                             
        "ansible_os_family": "Debian",                                                                                 
        "ansible_pkg_mgr": "apt",                                                                                      
        "ansible_processor": [                                                                                         
            "Pentium(R) Dual-Core  CPU      E5300  @ 2.60GHz"                                                          
        ],                                                                                                             
        "ansible_processor_cores": "NA",                                                                               
        "ansible_processor_count": 1,                                                                                  
        "ansible_product_name": "VirtualBox",                                                                          
        "ansible_product_serial": "NA",                                                                                
        "ansible_product_uuid": "NA",                                                                                  
        "ansible_product_version": "1.2",                                                                              
        "ansible_python_version": "2.7.3", 
        "ansible_selinux": false, 
        "ansible_swapfree_mb": 766, 
        "ansible_swaptotal_mb": 767, 
        "ansible_system": "Linux", 
        "ansible_system_vendor": "innotek GmbH", 
        "ansible_user_id": "neves", 
        "ansible_userspace_architecture": "i386", 
        "ansible_userspace_bits": "32", 
        "ansible_virtualization_role": "guest", 
        "ansible_virtualization_type": "virtualbox"
    }, 
    "changed": false
}

The current documentation now has a complete chapter listing all Variables and Facts

How to explicitly obtain post data in Spring MVC?

If you are using one of the built-in controller instances, then one of the parameters to your controller method will be the Request object. You can call request.getParameter("value1") to get the POST (or PUT) data value.

If you are using Spring MVC annotations, you can add an annotated parameter to your method's parameters:

@RequestMapping(value = "/someUrl")
public String someMethod(@RequestParam("value1") String valueOne) {
 //do stuff with valueOne variable here
}

How do I set a program to launch at startup

    /// <summary>
    /// Add application to Startup of windows
    /// </summary>
    /// <param name="appName"></param>
    /// <param name="path"></param>
    public static void AddStartup(string appName, string path)
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.SetValue(appName, "\"" + path + "\"");
        }
    }

    /// <summary>
    /// Remove application from Startup of windows
    /// </summary>
    /// <param name="appName"></param>
    public static void RemoveStartup(string appName)
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
        {
            key.DeleteValue(appName, false);
        }
    }

Why is "cursor:pointer" effect in CSS not working

cursor:pointer doesn't work when you're using Chrome's mobile emulator.

enter image description here

Delete worksheet in Excel using VBA

Consider:

Sub SheetKiller()
    Dim s As Worksheet, t As String
    Dim i As Long, K As Long
    K = Sheets.Count

    For i = K To 1 Step -1
        t = Sheets(i).Name
        If t = "ID Sheet" Or t = "Summary" Then
            Application.DisplayAlerts = False
                Sheets(i).Delete
            Application.DisplayAlerts = True
        End If
    Next i
End Sub

NOTE:

Because we are deleting, we run the loop backwards.

How to know when a web page was last updated?

01. Open the page for which you want to get the information.

02. Clear the address bar [where you type the address of the sites]:

and type or copy/paste from below:

javascript:alert(document.lastModified)

03. Press Enter or Go button.

IOPub data rate exceeded in Jupyter notebook (when viewing image)

Some additional advice for Windows(10) users:

  1. If you are using Anaconda Prompt/PowerShell for the first time, type "Anaconda" in the search field of your Windows task bar and you will see the suggested software.
  2. Make sure to open the Anaconda prompt as administrator.
  3. Always navigate to your user directory or the directory with your Jupyter Notebook files first before running the command. Otherwise you might end up somewhere in your system files and be confused by an unfamiliar file tree.

The correct way to open Jupyter notebook with new data limit from the Anaconda Prompt on my own Windows 10 PC is:

(base) C:\Users\mobarget\Google Drive\Jupyter Notebook>jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10

Python 3.4.0 with MySQL database

sudo apt-get install python3-dev
sudo apt-get install libmysqlclient-dev
sudo apt-get install zlib1g-dev
sudo pip3 install mysqlclient

that worked for me!

What is the best way to repeatedly execute a function every x seconds?

If your program doesn't have a event loop already, use the sched module, which implements a general purpose event scheduler.

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc): 
    print("Doing stuff...")
    # do your stuff
    s.enter(60, 1, do_something, (sc,))

s.enter(60, 1, do_something, (s,))
s.run()

If you're already using an event loop library like asyncio, trio, tkinter, PyQt5, gobject, kivy, and many others - just schedule the task using your existing event loop library's methods, instead.

implement addClass and removeClass functionality in angular2

If you want to due this in component.ts

HTML:

<button class="class1 class2" (click)="clicked($event)">Click me</button>

Component:

clicked(event) {
  event.target.classList.add('class3'); // To ADD
  event.target.classList.remove('class1'); // To Remove
  event.target.classList.contains('class2'); // To check
  event.target.classList.toggle('class4'); // To toggle
}

For more options, examples and browser compatibility visit this link.

ERROR Android emulator gets killed

This worked for me:

Tools -> SDK Manager -> SDK Tools (tab) -> Deselect 'Android Emulator' -> OK

Now, when you try to run your app, or launch device from AVD Manager, it will give the 'Install Emulator' error -> Click Ok. This will automatically download the correct version.

Float to String format specifier

In C#, float is an alias for System.Single (a bit like intis an alias for System.Int32).

What's the C# equivalent to the With statement in VB?

Not really, you have to assign a variable. So

    var bar = Stuff.Elements.Foo;
    bar.Name = "Bob Dylan";
    bar.Age = 68;
    bar.Location = "On Tour";
    bar.IsCool = True;

Or in C# 3.0:

    var bar = Stuff.Elements.Foo
    {
        Name = "Bob Dylan",
        Age = 68,
        Location = "On Tour",
        IsCool = True
    };

How Do I Convert an Integer to a String in Excel VBA?

Try the CStr() function

Dim myVal as String;
Dim myNum as Integer;

myVal = "My number is:"
myVal = myVal & CStr(myNum);

How do you turn a Mongoose document into a plain object?

the fast way if the property is not in the model :

document.set( key,value, { strict: false });

How I add Headers to http.get or http.post in Typescript and angular 2?

Be sure to declare HttpHeaders without null values.

    this.http.get('url', {headers: new HttpHeaders({'a': a || '', 'b': b || ''}))

Otherwise, if you try to add a null value to HttpHeaders it will give you an error.

How to resize the jQuery DatePicker control

This code will work on Calender buttons. size of numbers will increase by using "line-height".

/* Change Size */
<style>
    .ui-datepicker{
        font-size:16px;
        line-height: 1.3;
    }
</style>

How do I check/uncheck all checkboxes with a button using jQuery?

This is the shortest way I've found (needs jQuery1.6+)

HTML:

<input type="checkbox" id="checkAll"/>

JS:

$("#checkAll").change(function () {
    $("input:checkbox").prop('checked', $(this).prop("checked"));
});

I'm using .prop as .attr doesn't work for checkboxes in jQuery 1.6+ unless you've explicitly added a checked attribute to your input tag.

Example-

_x000D_
_x000D_
$("#checkAll").change(function () {_x000D_
    $("input:checkbox").prop('checked', $(this).prop("checked"));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form action="#">_x000D_
    <p><label><input type="checkbox" id="checkAll"/> Check all</label></p>_x000D_
    _x000D_
    <fieldset>_x000D_
        <legend>Loads of checkboxes</legend>_x000D_
        <p><label><input type="checkbox" /> Option 1</label></p>_x000D_
        <p><label><input type="checkbox" /> Option 2</label></p>_x000D_
        <p><label><input type="checkbox" /> Option 3</label></p>_x000D_
        <p><label><input type="checkbox" /> Option 4</label></p>_x000D_
    </fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How do I update pip itself from inside my virtual environment?

In my case this worked from the terminal command line in Debian Stable

python3 -m pip install --upgrade pip

Easy way to concatenate two byte arrays

Most straightforward:

byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);

Why does python use 'else' after for and while loops?

To make it simple, you can think of it like that;

  • If it encounters the break command in the for loop, the else part will not be called.
  • If it does not encounter the break command in the for loop, the else part will be called.

In other words, if for loop iteration is not "broken" with break, the else part will be called.

Full-screen iframe with a height of 100%

<iframe src="" style="top:0;left: 0;width:100%;height: 100%; position: absolute; border: none"></iframe>

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

 Use the below code to solve the CertPathValidatorException issue.


 Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(YOUR_BASE_URL)
        .client(getUnsafeOkHttpClient().build())
        .build();


  public static OkHttpClient.Builder getUnsafeOkHttpClient() {

    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return new java.security.cert.X509Certificate[]{};
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return builder;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

For more details visit https://mobikul.com/android-retrofit-handling-sslhandshakeexception/

Change marker size in Google maps V3

This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.

The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(42, 68)
);  

As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.

Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:

what happens when you leave anchor null on an enlarged shadow

The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null. In other words, leaving the anchor null ensures the tip points where it is supposed to point.

However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.

By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.

var pinShadow = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
    null,
    null,
    /* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
    new google.maps.Point(40, 110), 
    new google.maps.Size(120, 110)); 

to give this:

offset the enlarged shadow anchor explicitly

anchor jumping by using javascript

You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.

Here is a lazier way to do that:

function jump(h){
    var url = location.href;               //Save down the URL without hash.
    location.href = "#"+h;                 //Go to the target element.
    history.replaceState(null,null,url);   //Don't like hashes. Changing it back.
}

This uses replaceState to manipulate the url. If you also want support for IE, then you will have to do it the complicated way:

function jump(h){
    var top = document.getElementById(h).offsetTop; //Getting Y of target element
    window.scrollTo(0, top);                        //Go there directly or some transition
}?

Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/

You can also use .scrollIntoView:

document.getElementById(h).scrollIntoView();   //Even IE6 supports this

(Well I lied. It's not complicated at all.)

Find length of 2D array Python

You can use numpy.shape.

import numpy as np
x = np.array([[1, 2],[3, 4],[5, 6]])

Result:

>>> x
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> np.shape(x)
(3, 2)

First value in the tuple is number rows = 3; second value in the tuple is number of columns = 2.

cartesian product in pandas

With method chaining:

product = (
    df1.assign(key=1)
    .merge(df2.assign(key=1), on="key")
    .drop("key", axis=1)
)

How to get a value from a cell of a dataframe?

It doesn't need to be complicated:

val = df.loc[df.wd==1, 'col_name'].values[0]

Python: find position of element in array

There is a built in method for doing this:

numpy.where()

You can find out more about it in the excellent detailed documentation.

Cannot find Microsoft.Office.Interop Visual Studio

You can find it at link:

C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Word\15.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Word.dll

Browse it then add references

Android WebView not loading an HTTPS URL

I followed the answers above but still it seems not to be working for me below code did a trick for me when integrating payment gatways which are usually https requests :

public class MainActivity extends Activity {

    WebView webView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView) findViewById(R.id.webView1);
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        webView.setWebViewClient(new MyWebViewClient());
        String postData = "amount=1000&firstname=mtetno&[email protected]&phone=2145635784&productinfo=android&surl=success.php"
                + "&furl=failure.php&lastname=qwerty&curl=dsdsd.com&address1=dsdsds&address2=dfdfd&city=dsdsds&state=dfdfdfd&"
                + "country=fdfdf&zipcode=123456&udf1=dsdsds&udf2=fsdfdsf&udf3=jhghjg&udf4=fdfd&udf5=fdfdf&pg=dfdf";
        webView.postUrl(
                "http://host/payment.php",
                EncodingUtils.getBytes(postData, "BASE64"));

    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            webView.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler,
                SslError error) {
            handler.proceed();
        }
    }
}

Above code is doing a post request in webview and redirecting to payment gateway.

Setting settings.setDomStorageEnabled(true); did a trick for me Hope this helps .

How can I make my custom objects Parcelable?

I have found simplest way to create Parcelable class

enter image description here

How do I get the total Json record count using JQuery?

Perhaps you might want to try JSON.parse your return result first then you can get the count by .length

This Activity already has an action bar supplied by the window decor

Simply put, you can do the following:-

if (android.os.Build.VERSION.SDK_INT >= 21) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));

    }

instantiate a class from a variable in PHP?

I would recommend the call_user_func() or call_user_func_arrayphp methods. You can check them out here (call_user_func_array , call_user_func).

example

class Foo {
static public function test() {
    print "Hello world!\n";
}
}

 call_user_func('Foo::test');//FOO is the class, test is the method both separated by ::
 //or
 call_user_func(array('Foo', 'test'));//alternatively you can pass the class and method as an array

If you have arguments you are passing to the method , then use the call_user_func_array() function.

example.

class foo {
function bar($arg, $arg2) {
    echo __METHOD__, " got $arg and $arg2\n";
}
}

// Call the $foo->bar() method with 2 arguments
call_user_func_array(array("foo", "bar"), array("three", "four"));
//or
//FOO is the class, bar is the method both separated by ::
call_user_func_array("foo::bar"), array("three", "four"));

C# Java HashMap equivalent

Dictionary is probably the closest. System.Collections.Generic.Dictionary implements the System.Collections.Generic.IDictionary interface (which is similar to Java's Map interface).

Some notable differences that you should be aware of:

  • Adding/Getting items
    • Java's HashMap has the put and get methods for setting/getting items
      • myMap.put(key, value)
      • MyObject value = myMap.get(key)
    • C#'s Dictionary uses [] indexing for setting/getting items
      • myDictionary[key] = value
      • MyObject value = myDictionary[key]
  • null keys
    • Java's HashMap allows null keys
    • .NET's Dictionary throws an ArgumentNullException if you try to add a null key
  • Adding a duplicate key
    • Java's HashMap will replace the existing value with the new one.
    • .NET's Dictionary will replace the existing value with the new one if you use [] indexing. If you use the Add method, it will instead throw an ArgumentException.
  • Attempting to get a non-existent key
    • Java's HashMap will return null.
    • .NET's Dictionary will throw a KeyNotFoundException. You can use the TryGetValue method instead of the [] indexing to avoid this:
      MyObject value = null; if (!myDictionary.TryGetValue(key, out value)) { /* key doesn't exist */ }

Dictionary's has a ContainsKey method that can help deal with the previous two problems.

For Restful API, can GET method use json data?

To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode). However, considering your reason for doing this is due to the length of the URI, using JSON will be self-defeating (introducing more characters than required).

I suggest you send your parameters in body of a POST request, either in regular CGI style (param1=val1&param2=val2) or JSON (parsed by your API upon receipt)

What is the return value of os.system() in Python?

os.system('command') returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.

00000000    00000000
exit code   signal num

Example 1 - command exit with code 1

os.system('command') #it returns 256
256 in 16 bits -  00000001 00000000
Exit code is 00000001 which means 1

Example 2 - command exit with code 3

os.system('command') # it returns 768
768 in 16 bits  - 00000011 00000000
Exit code is 00000011 which means 3

Now try with signal - Example 3 - Write a program which sleep for long time use it as command in os.system() and then kill it by kill -15 or kill -9

os.system('command') #it returns signal num by which it is killed
15 in bits - 00000000 00001111
Signal num is 00001111 which means 15

You can have a python program as command = 'python command.py'

import sys
sys.exit(n)  # here n would be exit code

In case of c or c++ program you can use return from main() or exit(n) from any function #

Note - This is applicable on unix

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

os.wait()

Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.

Availability: Unix

.

How do I parse JSON into an int?

The question is kind of old, but I get a good result creating a function to convert an object in a Json string from a string variable to an integer

function getInt(arr, prop) {
    var int;
    for (var i=0 ; i<arr.length ; i++) {
        int = parseInt(arr[i][prop])
            arr[i][prop] = int;
    }
    return arr;
  }

the function just go thru the array and return all elements of the object of your selection as an integer

Can anyone recommend a simple Java web-app framework?

A common property of Java Web-apps is that they usually use servlets which usually means the web server also runs Java. This contributes to the perceived complexity, IMHO. But you can build Java apps in the traditional Unix-style of "do one thing and do it well" without having performance suffer.

You can also use SCGI, it is a lot simpler than FastCGI. I'd try that first. But if it doesn't work out:

How to write a FastCGI application in Java

  1. Make an empty working directory and enter it
  2. Download the FastCGI devkit: wget --quiet --recursive --no-parent --accept=java --no-directories --no-host-directories "http://www.fastcgi.com/devkit/java/"
  3. mkdir -p com/fastcgi
  4. mv *.java com/fastcgi
  5. Now you need to apply a tiny patch to the devkit (replace operator == with <= on line 175 or use this script to do it):

    echo -e "175c\nif (count <= 0) {\n.\nw\nn\nq" | ed -s com/fastcgi/FCGIInputStream.java

  6. Create a test app, TinyFCGI.java (source below)
  7. Compile everything: javac **/*.java (** will probably only work in zsh)
  8. Start the FastCGI server: java -DFCGI_PORT=9884 TinyFCGI (leave it running in the background)
  9. Now set up e.g. Apache to use the server:

    • Using Apache 2.4, you can use mod_proxy_fcgi like this:
      1. Using Ubuntu, upgrade to Apache 2.4 using i.e. this PPA
      2. Enable the mod: sudo a2enmod proxy_fcgi
      3. Create /etc/apache2/conf-enabled/your_site.conf with the content below
      4. Restart Apache: sudo apache2ctl restart
  10. Now you can access the webapp at http://localhost/your_site

  11. Benchmark results below

TinyFCGI.java

import com.fastcgi.FCGIInterface;
import java.io.*;
import static java.lang.System.out;

class TinyFCGI {
    public static void main (String args[]) {
        int count = 0;
        FCGIInterface fcgiinterface = new FCGIInterface();
        while(fcgiinterface.FCGIaccept() >= 0) {
            count++;
            out.println("Content-type: text/html\n\n");
            out.println("<html>");
            out.println(
                "<head><TITLE>FastCGI-Hello Java stdio</TITLE></head>");
            out.println("<body>");
            out.println("<H3>FastCGI-HelloJava stdio</H3>");
            out.println("request number " + count +
                               " running on host "
                               + System.getProperty("SERVER_NAME"));
            out.println("</body>");
            out.println("</html>");
        }
    }
}

your_site.conf

<Location /your_site>
  ProxyPass fcgi://localhost:9884/
</Location>

Benchmark results

wrk

$ ./wrk -t1 -c100 -r10000 http://localhost/your_site 
Making 10000 requests to http://localhost/your_site
  1 threads and 100 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     3.58s    13.42s    1.06m    94.42%
    Req/Sec     0.00      0.00     0.00    100.00%
  10000 requests in 1.42m, 3.23MB read
  Socket errors: connect 0, read 861, write 0, timeout 2763
  Non-2xx or 3xx responses: 71
Requests/sec:    117.03
Transfer/sec:     38.70KB

ab

$ ab -n 10000 -c 100 localhost:8800/your_site
Concurrency Level:      100
Time taken for tests:   12.640 seconds
Complete requests:      10000
Failed requests:        0
Write errors:           0
Total transferred:      3180000 bytes
HTML transferred:       1640000 bytes
Requests per second:    791.11 [#/sec] (mean)
Time per request:       126.404 [ms] (mean)
Time per request:       1.264 [ms] (mean, across all concurrent requests)
Transfer rate:          245.68 [Kbytes/sec] received

siege

$ siege -r 10000 -c 100 "http://localhost:8800/your_site"
** SIEGE 2.70
** Preparing 100 concurrent users for battle.
The server is now under siege...^C
Lifting the server siege...      done.
Transactions:              89547 hits
Availability:             100.00 %
Elapsed time:             447.93 secs
Data transferred:          11.97 MB
Response time:              0.00 secs
Transaction rate:         199.91 trans/sec
Throughput:             0.03 MB/sec
Concurrency:                0.56
Successful transactions:       89547
Failed transactions:               0
Longest transaction:            0.08
Shortest transaction:           0.00

SQLAlchemy default DateTime

DateTime doesn't have a default key as an input. The default key should be an input to the Column function. Try this:

import datetime
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Test(Base):
    __tablename__ = 'test'

    id = Column(Integer, primary_key=True)
    created_date = Column(DateTime, default=datetime.datetime.utcnow)

Hide the browse button on a input type=file

Below code is very useful to hide default browse button and use custom instead:

_x000D_
_x000D_
(function($) {_x000D_
  $('input[type="file"]').bind('change', function() {_x000D_
    $("#img_text").html($('input[type="file"]').val());_x000D_
  });_x000D_
})(jQuery)
_x000D_
.file-input-wrapper {_x000D_
  height: 30px;_x000D_
  margin: 2px;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  width: 118px;_x000D_
  background-color: #fff;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.file-input-wrapper>input[type="file"] {_x000D_
  font-size: 40px;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  opacity: 0;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.file-input-wrapper>.btn-file-input {_x000D_
  background-color: #494949;_x000D_
  border-radius: 4px;_x000D_
  color: #fff;_x000D_
  display: inline-block;_x000D_
  height: 34px;_x000D_
  margin: 0 0 0 -1px;_x000D_
  padding-left: 0;_x000D_
  width: 121px;_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.file-input-wrapper:hover>.btn-file-input {_x000D_
  //background-color: #494949;_x000D_
}_x000D_
_x000D_
#img_text {_x000D_
  float: right;_x000D_
  margin-right: -80px;_x000D_
  margin-top: -14px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
  <div class="file-input-wrapper">_x000D_
    <button class="btn-file-input">SELECT FILES</button>_x000D_
    <input type="file" name="image" id="image" value="" />_x000D_
  </div>_x000D_
  <span id="img_text"></span>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Reversing a String with Recursion in Java

run the following and you'll see what's going on:

public class RS {

    public static String reverse(String str) {
        System.out.println("--- reverse --- " + str);
        if ((null == str) || (str.length() <= 1)) {
            return str;
        }
        return add(reverse(str.substring(1)), charAt(str));
    }

    public static char charAt(String s) {
        System.out.println("--- charAt --- " + s);
        return s.charAt(0);
    }

    public static String add(String s, char c) {
        System.out.println("--- add --- " + s + " - " + c);
        return s + c;
    }

    public static void main(String[] args) {
        System.out.println("start");
        System.out.println("result: " + reverse("hello"));
        System.out.println("end");
    }

}

How can I change the language (to english) in Oracle SQL Developer?

You can also configure directly on the file ..sqldeveloper\ide\bin\ide.conf:

Just add the JVM Option:

AddVMOption -Duser.language=en

The file will be like this:

enter image description here

Multiline text in JLabel

You can also use a JXLabel from the SwingX library.

JXLabel multiline = new JXLabel("this is a \nMultiline Text");
multiline.setLineWrap(true);

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

How to split() a delimited string to a List<String>

Either use:

List<string> list = new List<string>(array);

or from LINQ:

List<string> list = array.ToList();

Or change your code to not rely on the specific implementation:

IList<string> list = array; // string[] implements IList<string>

How to check for file existence

Check out Pathname and in particular Pathname#exist?.

File and its FileTest module are perhaps simpler/more direct, but I find Pathname a nicer interface in general.

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

Your branch is ahead of 'origin/master' by 3 commits

$ git fetch

  - remote: Enumerating objects: 3, done.
  - remote: Counting objects: 100% (3/3), done.
  - remote: Compressing objects: 100% (3/3), done.
  - remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0


$ git pull 

   - Already up to date!
   - Merge made by the 'recursive' strategy.

finally:

$ git push origin

Adding 30 minutes to time formatted as H:i in PHP

In order for that to work $time has to be a timestamp. You cannot pass in "10:00" or something like $time = date('H:i', '10:00'); which is what you seem to do, because then I get 0:30 and 1:30 as results too.

Try

$time = strtotime('10:00');

As an alternative, consider using DateTime (the below requires PHP 5.3 though):

$dt = DateTime::createFromFormat('H:i', '10:00'); // create today 10 o'clock
$dt->sub(new DateInterval('PT30M'));              // substract 30 minutes
echo $dt->format('H:i');                          // echo modified time
$dt->add(new DateInterval('PT1H'));               // add 1 hour
echo $dt->format('H:i');                          // echo modified time

or procedural if you don't like OOP

$dateTime = date_create_from_format('H:i', '10:00');
date_sub($dateTime, date_interval_create_from_date_string('30 minutes'));
echo date_format($dateTime, 'H:i');
date_add($dateTime, date_interval_create_from_date_string('1 hour'));
echo date_format($dateTime, 'H:i');

How can I embed a YouTube video on GitHub wiki pages?

Complete Example

Expanding on @MGA's Answer

While it's not possible to embed a video in Markdown you can "fake it" by including a valid linked image in your markup file, using this format:

[![IMAGE ALT TEXT](http://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg)](http://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE "Video Title")

Explanation of the Markdown

If this markup snippet looks complicated, break it down into two parts:

an image
![image alt text](https://example.com/link-to-image)
wrapped in a link
[link text](https://example.com/my-link "link title")

Example using Valid Markdown and YouTube Thumbnail:

Everything Is AWESOME

We are sourcing the thumbnail image directly from YouTube and linking to the actual video, so when the person clicks the image/thumbnail they will be taken to the video.

Code:

[![Everything Is AWESOME](https://img.youtube.com/vi/StTqXEQ2l-Y/0.jpg)](https://www.youtube.com/watch?v=StTqXEQ2l-Y "Everything Is AWESOME")

OR If you want to give readers a visual cue that the image/thumbnail is actually a playable video, take your own screenshot of the video in YouTube and use that as the thumbnail instead.

Example using Screenshot with Video Controls as Visual Cue:

Everything Is AWESOME

Code:

[![Everything Is AWESOME](http://i.imgur.com/Ot5DWAW.png)](https://youtu.be/StTqXEQ2l-Y?t=35s "Everything Is AWESOME")

 Clear Advantages

While this requires a couple of extra steps (a) taking the screenshot of the video and (b) uploading it so you can use the image as your thumbnail it does have 3 clear advantages:

  1. The person reading your markdown (or resulting html page) has a visual cue telling them they can watch the video (video controls encourage clicking)
  2. You can chose a specific frame in the video to use as the thumbnail (thus making your content more engaging)
  3. You can link to a specific time in the video from which play will start when the linked-image is clicked. (in our case from 35 seconds)

Taking and uploading a screenshot takes a few seconds but has a big payoff.

Works Everywhere!

Since this is standard markdown, it works everywhere. try it on GitHub, Reddit, Ghost, and here on Stack Overflow.

Vimeo

This approach also works with Vimeo videos

Example

Little red riding hood

Code

[![Little red riding hood](http://i.imgur.com/7YTMFQp.png)](https://vimeo.com/3514904 "Little red riding hood - Click to Watch!")

Notes:

Postgres: INSERT if does not exist already

Here is a generic python function that given a tablename, columns and values, generates the upsert equivalent for postgresql.

import json

def upsert(table_name, id_column, other_columns, values_hash):

    template = """
    WITH new_values ($$ALL_COLUMNS$$) as (
      values
         ($$VALUES_LIST$$)
    ),
    upsert as
    (
        update $$TABLE_NAME$$ m
            set
                $$SET_MAPPINGS$$
        FROM new_values nv
        WHERE m.$$ID_COLUMN$$ = nv.$$ID_COLUMN$$
        RETURNING m.*
    )
    INSERT INTO $$TABLE_NAME$$ ($$ALL_COLUMNS$$)
    SELECT $$ALL_COLUMNS$$
    FROM new_values
    WHERE NOT EXISTS (SELECT 1
                      FROM upsert up
                      WHERE up.$$ID_COLUMN$$ = new_values.$$ID_COLUMN$$)
    """

    all_columns = [id_column] + other_columns
    all_columns_csv = ",".join(all_columns)
    all_values_csv = ','.join([query_value(values_hash[column_name]) for column_name in all_columns])
    set_mappings = ",".join([ c+ " = nv." +c for c in other_columns])

    q = template
    q = q.replace("$$TABLE_NAME$$", table_name)
    q = q.replace("$$ID_COLUMN$$", id_column)
    q = q.replace("$$ALL_COLUMNS$$", all_columns_csv)
    q = q.replace("$$VALUES_LIST$$", all_values_csv)
    q = q.replace("$$SET_MAPPINGS$$", set_mappings)

    return q


def query_value(value):
    if value is None:
        return "NULL"
    if type(value) in [str, unicode]:
        return "'%s'" % value.replace("'", "''")
    if type(value) == dict:
        return "'%s'" % json.dumps(value).replace("'", "''")
    if type(value) == bool:
        return "%s" % value
    if type(value) == int:
        return "%s" % value
    return value


if __name__ == "__main__":

    my_table_name = 'mytable'
    my_id_column = 'id'
    my_other_columns = ['field1', 'field2']
    my_values_hash = {
        'id': 123,
        'field1': "john",
        'field2': "doe"
    }
    print upsert(my_table_name, my_id_column, my_other_columns, my_values_hash)

How to make use of SQL (Oracle) to count the size of a string?

Regardless to Your example

select length('Burger') from dual;

I hope this will help :)

remove None value from a list without removing the 0 value

>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]

Just for fun, here's how you can adapt filter to do this without using a lambda, (I wouldn't recommend this code - it's just for scientific purposes)

>>> from operator import is_not
>>> from functools import partial
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> filter(partial(is_not, None), L)
[0, 23, 234, 89, 0, 35, 9]

WiX tricks and tips

Add a checkbox to the exit dialog to launch the app, or the helpfile.

...

<!-- CA to launch the exe after install -->
<CustomAction Id          ="CA.StartAppOnExit"
              FileKey     ="YourAppExeId"
              ExeCommand  =""
              Execute     ="immediate"
              Impersonate ="yes"
              Return      ="asyncNoWait" />

<!-- CA to launch the help file -->
<CustomAction Id         ="CA.LaunchHelp"
              Directory  ="INSTALLDIR"
              ExeCommand ='[WindowsFolder]hh.exe IirfGuide.chm'
              Execute    ="immediate"
              Return     ="asyncNoWait" />

<Property Id="WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT"
          Value="Launch MyApp when setup exits." />

<UI>
  <Publish Dialog  ="ExitDialog"
           Control ="Finish"
           Order   ="1"
           Event   ="DoAction"
           Value   ="CA.StartAppOnExit">WIXUI_EXITDIALOGOPTIONALCHECKBOXTEXT</Publish>
</UI>

If you do it this way, the "standard" appearance isn't quite right. The checkbox is always a gray background, while the dialog is white:

alt text http://www.dizzymonkeydesign.com/blog/misc/adding-and-customizing-dlgs-in-wix-3/images/exit_dlg_1.gif

One way around this is to specify your own custom ExitDialog, with a differently-located checkbox. This works, but seems like a lot of work just to change the color of one control. Another way to solve the same thing is to post-process the generated MSI to change the X,Y fields in the Control table for that particular CheckBox control. The javascript code looks like this:

var msiOpenDatabaseModeTransact = 1;
var filespec = WScript.Arguments(0);
var installer = new ActiveXObject("WindowsInstaller.Installer");
var database = installer.OpenDatabase(filespec, msiOpenDatabaseModeTransact);
var sql = "UPDATE `Control` SET `Control`.`Height` = '18', `Control`.`Width` = '170'," +
          " `Control`.`Y`='243', `Control`.`X`='10' " +
          "WHERE `Control`.`Dialog_`='ExitDialog' AND " + 
          "  `Control`.`Control`='OptionalCheckBox'";
var view = database.OpenView(sql);
view.Execute();
view.Close();
database.Commit();

Running this code as a command-line script (using cscript.exe) after the MSI is generated (from light.exe) will produce an ExitDialog that looks more professional:

alt text http://www.dizzymonkeydesign.com/blog/misc/adding-and-customizing-dlgs-in-wix-3/images/exit_dlg_2.gif

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

To discover any constraints used, use the code below:

-- Set the long data type for display purposes to 500000.

SET LONG 500000

-- Define a session scope variable.

VARIABLE output CLOB

-- Query the table definition through the <code>DBMS_METADATA</code> package.

SELECT dbms_metadata.get_ddl('TABLE','[Table Described]') INTO :output FROM dual;

This essentially shows a create statement for how the referenced table is made. By knowing how the table is created, you can see all of the table constraints.

Answer taken from Michael McLaughlin's blog: http://michaelmclaughlin.info/db1/lesson-5-querying-data/lab-5-querying-data/ From his Database Design I class.

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

How to enter a multi-line command

Just add a corner case here. It might save you 5 minutes. If you use a chain of actions, you need to put "." at the end of line, leave a space followed by the "`" (backtick). I found this out the hard way.

$yourString = "HELLO world! POWERSHELL!". `
                  Replace("HELLO", "Hello"). `
                  Replace("POWERSHELL", "Powershell")

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

Should I call Close() or Dispose() for stream objects?

On many classes which support both Close() and Dispose() methods, the two calls would be equivalent. On some classes, however, it is possible to re-open an object which has been closed. Some such classes may keep some resources alive after a Close, in order to permit reopening; others may not keep any resources alive on Close(), but might set a flag on Dispose() to explicitly forbid re-opening.

The contract for IDisposable.Dispose explicitly requires that calling it on an object which will never be used again will be at worst harmless, so I would recommend calling either IDisposable.Dispose or a method called Dispose() on every IDisposable object, whether or not one also calls Close().

How to loop through a JSON object with typescript (Angular2)

Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?

Check if an element is present in a Bash array

FWIW, here's what I used:

expr "${arr[*]}" : ".*\<$item\>"

This works where there are no delimiters in any of the array items or in the search target. I didn't need to solve the general case for my applicaiton.

Trigger an action after selection select2

See the documentation events section

Depending on the version, one of the snippets below should give you the event you want, alternatively just replace "select2-selecting" with "change".

Version 4.0 +

Events are now in format: select2:selecting (instead of select2-selecting)

Thanks to snakey for the notification that this has changed as of 4.0

$('#yourselect').on("select2:selecting", function(e) { 
   // what you would like to happen
});

Version Before 4.0

$('#yourselect').on("select2-selecting", function(e) { 
   // what you would like to happen
});

Just to clarify, the documentation for select2-selecting reads:

select2-selecting Fired when a choice is being selected in the dropdown, but before any modification has been made to the selection. This event is used to allow the user to reject selection by calling event.preventDefault()

whereas change has:

change Fired when selection is changed.

So change may be more appropriate for your needs, depending on whether you want the selection to complete and then do your event, or potentially block the change.

java: use StringBuilder to insert at the beginning

This thread is quite old, but you could also think about a recursive solution passing the StringBuilder to fill. This allows to prevent any reverse processing etc. Just need to design your iteration with a recursion and carefully decide for an exit condition.

public class Test {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        doRecursive(sb, 100, 0);
        System.out.println(sb.toString());
    }

    public static void doRecursive(StringBuilder sb, int limit, int index) {
        if (index < limit) {
            doRecursive(sb, limit, index + 1);
            sb.append(Integer.toString(index));
        }
    }
}

How to make a JSONP request from Javascript without JQuery?

I wrote a library to handle this, as simply as possible. No need to make it external, its just one function. Unlike some other options, this script cleans up after itself, and is generalized for making further requests at runtime.

https://github.com/Fresheyeball/micro-jsonp

function jsonp(url, key, callback) {

    var appendParam = function(url, key, param){
            return url
                + (url.indexOf("?") > 0 ? "&" : "?")
                + key + "=" + param;
        },

        createScript = function(url, callback){
            var doc = document,
                head = doc.head,
                script = doc.createElement("script");

            script
            .setAttribute("src", url);

            head
            .appendChild(script);

            callback(function(){
                setTimeout(function(){
                    head
                    .removeChild(script);
                }, 0);
            });
        },

        q =
            "q" + Math.round(Math.random() * Date.now());

    createScript(
        appendParam(url, key, q), function(remove){
            window[q] =
                function(json){
                    window[q] = undefined;
                    remove();
                    callback(json);
                };
        });
}

Sending XML data using HTTP POST with PHP

Another option would be file_get_contents():

// $xml_str = your xml
// $url = target url

$post_data = array('xml' => $xml_str);
$stream_options = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
        'content' =>  http_build_query($post_data)));

$context  = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);

How to launch an Activity from another Application in Android

// check for the app if it exist in the phone it will lunch it otherwise, it will search for the app in google play app in the phone and to avoid any crash, if no google play app installed in the phone, it will search for the app in the google play store using the browser : 

 public void onLunchAnotherApp() {

        final String appPackageName = getApplicationContext().getPackageName();

        Intent intent = getPackageManager().getLaunchIntentForPackage(appPackageName);
        if (intent != null) {

            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);

        } else {

            onGoToAnotherInAppStore(intent, appPackageName);

        }

    }

    public void onGoToAnotherInAppStore(Intent intent, String appPackageName) {

        try {

            intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(Uri.parse("market://details?id=" + appPackageName));
            startActivity(intent);

        } catch (android.content.ActivityNotFoundException anfe) {

            intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName));
            startActivity(intent);

        }

    }

Java Array, Finding Duplicates

Print all the duplicate elements. Output -1 when no repeating elements are found.

import java.util.*;

public class PrintDuplicate {

    public static void main(String args[]){
        HashMap<Integer,Integer> h = new HashMap<Integer,Integer>();


        Scanner s=new Scanner(System.in);
        int ii=s.nextInt();
        int k=s.nextInt();
        int[] arr=new  int[k];
        int[] arr1=new  int[k];
        int l=0;
        for(int i=0; i<arr.length; i++)
            arr[i]=s.nextInt();
        for(int i=0; i<arr.length; i++){
            if(h.containsKey(arr[i])){
                h.put(arr[i], h.get(arr[i]) + 1);
                arr1[l++]=arr[i];
            } else {
                h.put(arr[i], 1);
            }
        }
        if(l>0)
        { 
            for(int i=0;i<l;i++)
                System.out.println(arr1[i]);
        }
        else
            System.out.println(-1);
    }
}

Where does the .gitignore file belong?

In the simple case, a repository might have a single .gitignore file in its root directory, which applies recursively to the entire repository. However, it is also possible to have additional .gitignore files in subdirectories. The rules in these nested .gitignore files apply only to the files under the directory where they are located. The Linux kernel source repository has 206 .gitignore files.

-- this is what i read from progit.pdf(version 2), P32

converting numbers in to words C#

When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:

{1, "one"}
{2, "two"}
{30, "thirty"}

You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.

After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.

How to shrink/purge ibdata1 file in MySQL

In a new version of mysql-server recipes above will crush "mysql" database. In old version it works. In new some tables switches to table type INNODB, and by doing so you will damage them. The easiest way is to:

  • dump all you databases
  • uninstall mysql-server,
  • add in remained my.cnf:
    [mysqld]
    innodb_file_per_table=1
  • erase all in /var/lib/mysql
  • install mysql-server
  • restore users and databases

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

Had the same problem and the solution was to reauthorize the user. Check it here:

<?php

 require_once("src/facebook.php");

  $config = array(
      'appId' => '1424980371051918',
      'secret' => '2ed5c1260daa4c44673ba6fbc348c67d',
      'fileUpload' => false // optional
  );

  $facebook = new Facebook($config);

//Authorizing app:

?>
<a href="<?php echo $facebook->getLoginUrl(); ?>">Login con fb</a>

Saved project and opened on my test enviroment and it worked again. As I did, you can comment your previous code and try.

Is it possible to opt-out of dark mode on iOS 13?

Objective-c version

 if (@available(iOS 13.0, *)) {
        _window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }

fill an array in C#

Write yourself an extension method

public static class ArrayExtensions {
    public static void Fill<T>(this T[] originalArray, T with) {
        for(int i = 0; i < originalArray.Length; i++){
            originalArray[i] = with;
        }
    }  
}

and use it like

int foo[] = new int[]{0,0,0,0,0};
foo.Fill(13);

will fill all the elements with 13

What is dynamic programming?

Dynamic programming is when you use past knowledge to make solving a future problem easier.

A good example is solving the Fibonacci sequence for n=1,000,002.

This will be a very long process, but what if I give you the results for n=1,000,000 and n=1,000,001? Suddenly the problem just became more manageable.

Dynamic programming is used a lot in string problems, such as the string edit problem. You solve a subset(s) of the problem and then use that information to solve the more difficult original problem.

With dynamic programming, you store your results in some sort of table generally. When you need the answer to a problem, you reference the table and see if you already know what it is. If not, you use the data in your table to give yourself a stepping stone towards the answer.

The Cormen Algorithms book has a great chapter about dynamic programming. AND it's free on Google Books! Check it out here.

jQuery deferreds and promises - .then() vs .done()

There is actually a pretty critical difference, insofar as jQuery's Deferreds are meant to be an implementations of Promises (and jQuery3.0 actually tries to bring them into spec).

The key difference between done/then is that

  • .done() ALWAYS returns the same Promise/wrapped values it started with, regardless of what you do or what you return.
  • .then() always returns a NEW Promise, and you are in charge of controlling what that Promise is based on what the function you passed it returned.

Translated from jQuery into native ES2015 Promises, .done() is sort of like implementing a "tap" structure around a function in a Promise chain, in that it will, if the chain is in the "resolve" state, pass a value to a function... but the result of that function will NOT affect the chain itself.

const doneWrap = fn => x => { fn(x); return x };

Promise.resolve(5)
       .then(doneWrap( x => x + 1))
       .then(doneWrap(console.log.bind(console)));

$.Deferred().resolve(5)
            .done(x => x + 1)
            .done(console.log.bind(console));

Those will both log 5, not 6.

Note that I used done and doneWrap to do logging, not .then. That's because console.log functions don't actually return anything. And what happens if you pass .then a function that doesn't return anything?

Promise.resolve(5)
       .then(doneWrap( x => x + 1))
       .then(console.log.bind(console))
       .then(console.log.bind(console));

That will log:

5

undefined

What happened? When I used .then and passed it a function that didn't return anything, it's implicit result was "undefined"... which of course returned a Promise[undefined] to the next then method, which logged undefined. So the original value we started with was basically lost.

.then() is, at heart, a form of function composition: the result of each step is used as the argument for the function in the next step. That's why .done is best thought of as a "tap"-> it's not actually part of the composition, just something that sneaks a look at the value at a certain step and runs a function at that value, but doesn't actually alter the composition in any way.

This is a pretty fundamental difference, and there's a probably a good reason why native Promises don't have a .done method implemented themselves. We don't eve have to get into why there's no .fail method, because that's even more complicated (namely, .fail/.catch are NOT mirrors of .done/.then -> functions in .catch that return bare values do not "stay" rejected like those passed to .then, they resolve!)

How do I save a String to a text file using Java?

If you only care about pushing one block of text to file, this will overwrite it each time.

JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
    FileOutputStream stream = null;
    PrintStream out = null;
    try {
        File file = chooser.getSelectedFile();
        stream = new FileOutputStream(file); 
        String text = "Your String goes here";
        out = new PrintStream(stream);
        out.print(text);                  //This will overwrite existing contents

    } catch (Exception ex) {
        //do something
    } finally {
        try {
            if(stream!=null) stream.close();
            if(out!=null) out.close();
        } catch (Exception ex) {
            //do something
        }
    }
}

This example allows the user to select a file using a file chooser.

Install windows service without InstallUtil.exe

This is a base service class (ServiceBase subclass) that can be subclassed to build a windows service that can be easily installed from the command line, without installutil.exe. This solution is derived from How to make a .NET Windows Service start right after the installation?, adding some code to get the service Type using the calling StackFrame

public abstract class InstallableServiceBase:ServiceBase
{

    /// <summary>
    /// returns Type of the calling service (subclass of InstallableServiceBase)
    /// </summary>
    /// <returns></returns>
    protected static Type getMyType()
    {
        Type t = typeof(InstallableServiceBase);
        MethodBase ret = MethodBase.GetCurrentMethod();
        Type retType = null;
        try
        {
            StackFrame[] frames = new StackTrace().GetFrames();
            foreach (StackFrame x in frames)
            {
                ret = x.GetMethod();

                Type t1 = ret.DeclaringType;

                if (t1 != null && !t1.Equals(t) &&   !t1.IsSubclassOf(t))
                {


                    break;
                }
                retType = t1;
            }
        }
        catch
        {

        }
        return retType;
    }
    /// <summary>
    /// returns AssemblyInstaller for the calling service (subclass of InstallableServiceBase)
    /// </summary>
    /// <returns></returns>
    protected static AssemblyInstaller GetInstaller()
    {
        Type t = getMyType();
        AssemblyInstaller installer = new AssemblyInstaller(
            t.Assembly, null);
        installer.UseNewContext = true;
        return installer;
    }

    private bool IsInstalled()
    {
        using (ServiceController controller =
            new ServiceController(this.ServiceName))
        {
            try
            {
                ServiceControllerStatus status = controller.Status;
            }
            catch
            {
                return false;
            }
            return true;
        }
    }

    private bool IsRunning()
    {
        using (ServiceController controller =
            new ServiceController(this.ServiceName))
        {
            if (!this.IsInstalled()) return false;
            return (controller.Status == ServiceControllerStatus.Running);
        }
    }
    /// <summary>
    /// protected method to be called by a public method within the real service
    /// ie: in the real service
    ///    new internal  void InstallService()
    ///    {
    ///        base.InstallService();
    ///    }
    /// </summary>
    protected void InstallService()
    {
        if (this.IsInstalled()) return;

        try
        {
            using (AssemblyInstaller installer = GetInstaller())
            {

                IDictionary state = new Hashtable();
                try
                {
                    installer.Install(state);
                    installer.Commit(state);
                }
                catch
                {
                    try
                    {
                        installer.Rollback(state);
                    }
                    catch { }
                    throw;
                }
            }
        }
        catch
        {
            throw;
        }
    }
    /// <summary>
    /// protected method to be called by a public method within the real service
    /// ie: in the real service
    ///    new internal  void UninstallService()
    ///    {
    ///        base.UninstallService();
    ///    }
    /// </summary>
    protected void UninstallService()
    {
        if (!this.IsInstalled()) return;

        if (this.IsRunning()) {
            this.StopService();
        }
        try
        {
            using (AssemblyInstaller installer = GetInstaller())
            {
                IDictionary state = new Hashtable();
                try
                {
                    installer.Uninstall(state);
                }
                catch
                {
                    throw;
                }
            }
        }
        catch
        {
            throw;
        }
    }

    private void StartService()
    {
        if (!this.IsInstalled()) return;

        using (ServiceController controller =
            new ServiceController(this.ServiceName))
        {
            try
            {
                if (controller.Status != ServiceControllerStatus.Running)
                {
                    controller.Start();
                    controller.WaitForStatus(ServiceControllerStatus.Running,
                        TimeSpan.FromSeconds(10));
                }
            }
            catch
            {
                throw;
            }
        }
    }

    private void StopService()
    {
        if (!this.IsInstalled()) return;
        using (ServiceController controller =
            new ServiceController(this.ServiceName))
        {
            try
            {
                if (controller.Status != ServiceControllerStatus.Stopped)
                {
                    controller.Stop();
                    controller.WaitForStatus(ServiceControllerStatus.Stopped,
                         TimeSpan.FromSeconds(10));
                }
            }
            catch
            {
                throw;
            }
        }
    }
}

All you have to do is to implement two public/internal methods in your real service:

    new internal  void InstallService()
    {
        base.InstallService();
    }
    new internal void UninstallService()
    {
        base.UninstallService();
    }

and then call them when you want to install the service:

    static void Main(string[] args)
    {
        if (Environment.UserInteractive)
        {
            MyService s1 = new MyService();
            if (args.Length == 1)
            {
                switch (args[0])
                {
                    case "-install":
                        s1.InstallService();

                        break;
                    case "-uninstall":

                        s1.UninstallService();
                        break;
                    default:
                        throw new NotImplementedException();
                }
            }


        }
        else {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new MyService() 
            };
            ServiceBase.Run(MyService);            
        }

    }

Convert string to Boolean in javascript

you can also use JSON.parse() function

JSON.parse("true") returns true (Boolean)

JSON.parse("false") return false (Boolean)

"Active Directory Users and Computers" MMC snap-in for Windows 7?

You have to enable the features in Add/Remove Programs section of your Control Panel. Select "Turn Windows features on or off"

How to get the last five characters of a string using Substring() in C#?

static void Main()
    {
        string input = "OneTwoThree";

            //Get last 5 characters
        string sub = input.Substring(6);
        Console.WriteLine("Substring: {0}", sub); // Output Three. 
    }
  • Substring(0, 3) - Returns substring of first 3 chars. //One

  • Substring(3, 3) - Returns substring of second 3 chars. //Two

  • Substring(6) - Returns substring of all chars after first 6. //Three

How to display Woocommerce Category image?

This solution with few code. I think is better.

<?php echo wp_get_attachment_image( get_term_meta( get_queried_object_id(), 'thumbnail_id', 1 ), 'thumbnail' ); ?>

Java Date cut off time information

Just a quick update in light of the java.time classes now built into Java 8 and later.

LocalDateTime has a truncatedTo method that effectively addresses what you are talking about here:

LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES)

This will express the current time down to minutes only:

2015-03-05T11:47

You may use a ChronoUnit (or a TemporalUnit) smaller than DAYS to execute the truncation (as the truncation is applied only to the time part of LocalDateTime, not to the date part).

How to save a BufferedImage as a File

File outputfile = new File("image.jpg");
ImageIO.write(bufferedImage, "jpg", outputfile);

Make virtualenv inherit specific packages from your global site-packages

Create the environment with virtualenv --system-site-packages . Then, activate the virtualenv and when you want things installed in the virtualenv rather than the system python, use pip install --ignore-installed or pip install -I . That way pip will install what you've requested locally even though a system-wide version exists. Your python interpreter will look first in the virtualenv's package directory, so those packages should shadow the global ones.

Remove a JSON attribute

Simple:

delete myObj.test.key1;

Finding even or odd ID values

For finding the even number we should use

select num from table where ( num % 2 ) = 0

Lumen: get URL parameter in a Blade view

Given your URL:

http://locahost:8000/example?a=10

The best way that I have found to get the value for 'a' and display it on the page is to use the following:

{{ request()->get('a') }}

However, if you want to use it within an if statement, you could use:

@if( request()->get('a') )
    <script>console.log('hello')</script>
@endif

Hope that helps someone! :)

How to set a session variable when clicking a <a> link

I had the same problem - i wanted to pass a parameter to another page by clicking a hyperlink and get the value to go to the next page (without using GET because the parameter is stored in the URL).

to those who don't understand why you would want to do this the answer is you dont want the user to see sensitive information or you dont want someone editing the GET.

well after scouring the internet it seemed it wasnt possible to make a normal hyperlink using the POST method.

And then i had a eureka moment!!!! why not just use CSS to make the submit button look like a normal hyperlink??? ...and put the value i want to pass in a hidden field

i tried it and it works. you can see an exaple here http://paulyouthed.com/test/css-button-that-looks-like-hyperlink.php

the basic code for the form is:

    <form enctype="multipart/form-data" action="page-to-pass-to.php" method="post">
                        <input type="hidden" name="post-variable-name" value="value-you-want-pass"/>
                        <input type="submit" name="whatever" value="text-to-display" id="hyperlink-style-button"/>
                </form>

the basic css is:

    #hyperlink-style-button{
      background:none;
      border:0;
      color:#666;
      text-decoration:underline;
    }

    #hyperlink-style-button:hover{
      background:none;
      border:0;
      color:#666;
      text-decoration:none;
      cursor:pointer;
      cursor:hand;
    }

Convert String XML fragment to Document Node in Java

/**
*
* Convert a string to a Document Object
*
* @param xml The xml to convert
* @return A document Object
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static Document string2Document(String xml) throws IOException, SAXException, ParserConfigurationException {

    if (xml == null)
    return null;

    return inputStream2Document(new ByteArrayInputStream(xml.getBytes()));

}


/**
* Convert an inputStream to a Document Object
* @param inputStream The inputstream to convert
* @return a Document Object
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static Document inputStream2Document(InputStream inputStream) throws IOException, SAXException, ParserConfigurationException {
    DocumentBuilderFactory newInstance = DocumentBuilderFactory.newInstance();
    newInstance.setNamespaceAware(true);
    Document parse = newInstance.newDocumentBuilder().parse(inputStream);
    return parse;
}

Fixing Sublime Text 2 line endings?

The simplest way to modify all files of a project at once (batch) is through Line Endings Unify package:

  1. Ctrl+Shift+P type inst + choose Install Package.
  2. Type line end + choose Line Endings Unify.
  3. Once installed, Ctrl+Shift+P + type end + choose Line Endings Unify.
  4. OR (instead of 3.) copy:

    {
     "keys": ["ctrl+alt+l"],
     "command": "line_endings_unify"
    },
    

    to the User array (right pane, after the opening [) in Preferences -> KeyBindings + press Ctrl+Alt+L.

As mentioned in another answer:

  • The Carriage Return (CR) character (0x0D, \r) [...] Early Macintosh operating systems (OS-9 and earlier).

  • The Line Feed (LF) character (0x0A, \n) [...] UNIX based systems (Linux, Mac OSX)

  • The End of Line (EOL) sequence (0x0D 0x0A, \r\n) [...] (non-Unix: Windows, Symbian OS).

If you have node_modules, build or other auto-generated folders, delete them before running the package.

When you run the package:

  1. you are asked at the bottom to choose which file extensions to search through a comma separated list (type the only ones you need to speed up the replacements, e.g. js,jsx).
  2. then you are asked which Input line ending to use, e.g. if you need LF type \n.
  3. press ENTER and wait until you see an alert window with LineEndingsUnify Complete.

Run a Docker image as a container

Since you have created an image from the Dockerfile, the image currently is not in active state. In order to work you need to run this image inside a container.

The $ docker images command describes how many images are currently available in the local repository. and

docker ps -a

shows how many containers are currently available, i.e. the list of active and exited containers.

There are two ways to run the image in the container:

$ docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]

In detached mode:

-d=false: Detached mode: Run container in the background, print new container id

In interactive mode:

-i :Keep STDIN open even if not attached

Here is the Docker run command

$ docker run image_name:tag_name

For more clarification on Docker run, you can visit Docker run reference.

It's the best material to understand Docker.

How can I get the console logs from the iOS Simulator?

[iOS Logger]

You can use the Console application(select your device in Devices) on your Mac to see a log message that were sent using NSLog, os_log, Logger (you will not see logs from print function).

Also please check (Action -> Include <Info/Debug> Messages)

enter image description here

Please note that if you want to see a log from WebView(UIWebView or WKWebView) you should use Safary -> Develop -> device

[Find crash log]

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

Could not find a declaration file for module 'busboy'. 'f:/firebase-cloud- 
functions/functions/node_modules/busboy/lib/main.js' implicitly has an ‘any’ 
type.

Try `npm install @types/busboy` if it exists or add a new declaration (.d.ts) 
the file containing `declare module 'busboy';`

In my case it's solved: All you have to do is edit your TypeScript Config file (tsconfig.json) and add a new key-value pair as:

"noImplicitAny": false

How to apply an XSLT Stylesheet in C#

I found a possible answer here: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63

From the article:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;

Edit:

But my trusty compiler says, XslTransform is obsolete: Use XslCompiledTransform instead:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);

What is the default font of Sublime Text?

On my system (Windows 8.1), Sublime 2 shows default font "Consolas". You can find yours by following this procedure:

  1. go to View menu and select Show Console
  2. Then enter this command: view.settings().get('font_face')

You will find your default font.

How to convert Java String to JSON Object

Converting the String to JsonNode using ObjectMapper object :

ObjectMapper mapper = new ObjectMapper();

// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)

// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)

// For Json String 
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);

Change key pair for ec2 instance

My issue was , I tried with IP rather than public DNS. Then i tried with public DNS and its resolved

Why Is `Export Default Const` invalid?

If the component name is explained in the file name MyComponent.js, just don't name the component, keeps code slim.

import React from 'react'

export default (props) =>
    <div id='static-page-template'>
        {props.children}
    </div>

Update: Since this labels it as unknown in stack tracing, it isn't recommended

Does SVG support embedding of bitmap images?

You could use a Data URI to supply the image data, for example:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">

<image width="20" height="20" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>

</svg>

The image will go through all normal svg transformations.

But this technique has disadvantages, for example the image will not be cached by the browser

Oracle: If Table Exists

Another method is to define an exception and then only catch that exception letting all others propagate.

Declare
   eTableDoesNotExist Exception;
   PRAGMA EXCEPTION_INIT(eTableDoesNotExist, -942);
Begin
   EXECUTE IMMEDIATE ('DROP TABLE myschema.mytable');
Exception
   When eTableDoesNotExist Then
      DBMS_Output.Put_Line('Table already does not exist.');
End;

Invoke native date picker from web-app on iOS/Android

Give Mobiscroll a try. The scroller style date and time picker was especially created for interaction on touch devices. It is pretty flexible, and easily customizable. It comes with iOS/Android themes.

how to configuring a xampp web server for different root directory

You can also put in a new virtual Host entry in the

c:\xampp\apache\conf\httpd-vhosts.conf

like:

<VirtualHost *:80>
  ServerAdmin [email protected]
  DocumentRoot "C:/xampp/htdocs/myproject/web"
  ServerName localhost
  ErrorLog "logs/dummy-host2.example.com-error.log"
  CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

How to remove last n characters from a string in Bash?

First, it's usually better to be explicit about your intent. So if you know the string ends in .rtf, and you want to remove that .rtf, you can just use var2=${var%.rtf}. One potentially-useful aspect of this approach is that if the string doesn't end in .rtf, it is not changed at all; var2 will contain an unmodified copy of var.

If you want to remove a filename suffix but don't know or care exactly what it is, you can use var2=${var%.*} to remove everything starting with the last .. Or, if you only want to keep everything up to but not including the first ., you can use var2=${var%%.*}. Those options have the same result if there's only one ., but if there might be more than one, you get to pick which end of the string to work from. On the other hand, if there's no . in the string at all, var2 will again be an unchanged copy of var.

If you really want to always remove a specific number of characters, here are some options.

You tagged this bash specifically, so we'll start with bash builtins. The one which has worked the longest is the same suffix-removal syntax I used above: to remove four characters, use var2=${var%????}. Or to remove four characters only if the first one is a dot, use var2=${var%.???}, which is like var2=${var%.*} but only removes the suffix if the part after the dot is exactly three characters. As you can see, to count characters this way, you need one question mark per unknown character removed, so this approach gets unwieldy for larger substring lengths.

An option in newer shell versions is substring extraction: var2=${var:0:${#var}-4}. Here you can put any number in place of the 4 to remove a different number of characters. The ${#var} is replaced by the length of the string, so this is actually asking to extract and keep (length - 4) characters starting with the first one (at index 0). With this approach, you lose the option to make the change only if the string matches a pattern; no matter what the actual value of the string is, the copy will include all but its last four characters.

Bash lets you leave the start index out; it defaults to 0, so you can shorten that to just var2=${var::${#var}-4}. In fact, newer versions of bash (specifically 4+, which means the one that ships with MacOS won't work) recognize negative lengths as end indexes counting back from the end of the string, so you can get rid of the string-length expression, too: var2=${var::-4}.

If you're not actually using bash but some other POSIX-type shell, the pattern-based suffix removal with % will still work – even in plain old dash, where the index-based substring extraction won't. Ksh and zsh do both support substring extraction, but require the explicit 0 start index; zsh also supports the negative end index, while ksh requires the length expression. Note that zsh, which indexes arrays starting at 1, nonetheless indexes strings starting at 0 if you use this bash-compatible syntax; but you can also treat parameters as arrays of characters, in which case it uses a 1-based count and expects a start and inclusive end position in brackets: var2=$var[1,-5].

Instead of using built-in shell parameter expansion, you can of course run some utility program to modify the string and capture its output with command substitution. There are several commands that will work; one is var2=$(sed 's/.\{4\}$//' <<<"$var").

git stash blunder: git stash pop and ended up with merge conflicts

Note that Git 2.5 (Q2 2015) a future Git might try to make that scenario impossible.

See commit ed178ef by Jeff King (peff), 22 Apr 2015.
(Merged by Junio C Hamano -- gitster -- in commit 05c3967, 19 May 2015)

Note: This has been reverted. See below.

stash: require a clean index to apply/pop

Problem

If you have staged contents in your index and run "stash apply/pop", we may hit a conflict and put new entries into the index.
Recovering to your original state is difficult at that point, because tools like "git reset --keep" will blow away anything staged.

In other words:

"git stash pop/apply" forgot to make sure that not just the working tree is clean but also the index is clean.
The latter is important as a stash application can conflict and the index will be used for conflict resolution.

Solution

We can make this safer by refusing to apply when there are staged changes.

That means if there were merges before because of applying a stash on modified files (added but not committed), now they would not be any merges because the stash apply/pop would stop immediately with:

Cannot apply stash: Your index contains uncommitted changes.

Forcing you to commit the changes means that, in case of merges, you can easily restore the initial state( before git stash apply/pop) with a git reset --hard.


See commit 1937610 (15 Jun 2015), and commit ed178ef (22 Apr 2015) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit bfb539b, 24 Jun 2015)

That commit was an attempt to improve the safety of applying a stash, because the application process may create conflicted index entries, after which it is hard to restore the original index state.

Unfortunately, this hurts some common workflows around "git stash -k", like:

git add -p       ;# (1) stage set of proposed changes
git stash -k     ;# (2) get rid of everything else
make test        ;# (3) make sure proposal is reasonable
git stash apply  ;# (4) restore original working tree

If you "git commit" between steps (3) and (4), then this just works. However, if these steps are part of a pre-commit hook, you don't have that opportunity (you have to restore the original state regardless of whether the tests passed or failed).

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

Mockito - difference between doReturn() and when()

The latter alternative is used for methods on mocks that return void.

Please have a look, for example, here: How to make mock to void methods with mockito

Git undo local branch delete

Follow these Steps:

1: Enter:

git reflog show 

This will display all the Commit history, you need to select the sha-1 that has the last commit that you want to get back

2: create a branch name with the Sha-1 ID you selected eg: 8c87714

git branch your-branch-name 8c87714

Is there an Eclipse plugin to run system shell in the Console?

Eclipse TCF team has just release terminal (SSH, Telnet, local)

originally named TCF Terminal, then renamed to TM Terminal

http://marketplace.eclipse.org/content/tcf-terminals

Finally Windows and Linux all supported

Support for Git Bash on Windows is resolved Bug 435014.

This plugin is included into Enide Studio 2014 and Enide 2015.

To access the terminal go to Window -> Show View -> Terminal or Ctrl+Alt+T

Is there a Java equivalent or methodology for the typedef keyword in C++?

Really, the only use of typedef that carries over to Javaland is aliasing- that is, giving the same class multiple names. That is, you've got a class "A" and you want "B" to refer to the same thing. In C++, you'd be doing "typedef B A;"

Unfortunately, they just don't support it. However, if you control all the types involved you CAN pull a nasty hack at the library level- you either extend B from A or have B implement A.

Setting Curl's Timeout in PHP

Your code sets the timeout to 1000 seconds. For milliseconds, use CURLOPT_TIMEOUT_MS.

How to use BOOLEAN type in SELECT statement

The answer to this question simply put is: Don't use BOOLEAN with Oracle-- PL/SQL is dumb and it doesn't work. Use another data type to run your process.

A note to SSRS report developers with Oracle datasource: You can use BOOLEAN parameters, but be careful how you implement. Oracle PL/SQL does not play nicely with BOOLEAN, but you can use the BOOLEAN value in the Tablix Filter if the data resides in your dataset. This really tripped me up, because I have used BOOLEAN parameter with Oracle data source. But in that instance I was filtering against Tablix data, not SQL query.

If the data is NOT in your SSRS Dataset Fields, you can rewrite the SQL something like this using an INTEGER parameter:

__

<ReportParameter Name="paramPickupOrders">
  <DataType>Integer</DataType>
  <DefaultValue>
    <Values>
      <Value>0</Value>
    </Values>
  </DefaultValue>
  <Prompt>Pickup orders?</Prompt>
  <ValidValues>
    <ParameterValues>
      <ParameterValue>
        <Value>0</Value>
        <Label>NO</Label>
      </ParameterValue>
      <ParameterValue>
        <Value>1</Value>
        <Label>YES</Label>
      </ParameterValue>
    </ParameterValues>
  </ValidValues>
</ReportParameter>

...

<Query>
<DataSourceName>Gmenu</DataSourceName>
<QueryParameters>
  <QueryParameter Name=":paramPickupOrders">
    <Value>=Parameters!paramPickupOrders.Value</Value>
  </QueryParameter>
<CommandText>
    where 
        (:paramPickupOrders = 0 AND ordh.PICKUP_FLAG = 'N'
        OR :paramPickupOrders = 1 AND ordh.PICKUP_FLAG = 'Y' )

If the data is in your SSRS Dataset Fields, you can use a tablix filter with a BOOLEAN parameter:

__

</ReportParameter>
<ReportParameter Name="paramFilterOrdersWithNoLoad">
  <DataType>Boolean</DataType>
  <DefaultValue>
    <Values>
      <Value>false</Value>
    </Values>
  </DefaultValue>
  <Prompt>Only orders with no load?</Prompt>
</ReportParameter>

...

<Tablix Name="tablix_dsMyData">
<Filters>
  <Filter>
    <FilterExpression>
        =(Parameters!paramFilterOrdersWithNoLoad.Value=false) 
        or (Parameters!paramFilterOrdersWithNoLoad.Value=true and Fields!LOADNUMBER.Value=0)
    </FilterExpression>
    <Operator>Equal</Operator>
    <FilterValues>
      <FilterValue DataType="Boolean">=true</FilterValue>
    </FilterValues>
  </Filter>
</Filters>

Call a "local" function within module.exports from another function in module.exports?

You could declare your functions outside of the module.exports block.

var foo = function (req, res, next) {
  return ('foo');
}

var bar = function (req, res, next) {
  return foo();
}

Then:

module.exports = {
  foo: foo,
  bar: bar
}

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

There are two main differences.

Accessing the association sides

The first one is related to how you will access the relationship. For a unidirectional association, you can navigate the association from one end only.

So, for a unidirectional @ManyToOne association, it means you can only access the relationship from the child side where the foreign key resides.

If you have a unidirectional @OneToMany association, it means you can only access the relationship from the parent side which manages the foreign key.

For the bidirectional @OneToMany association, you can navigate the association in both ways, either from the parent or from the child side.

You also need to use add/remove utility methods for bidirectional associations to make sure that both sides are properly synchronized.

Performance

The second aspect is related to performance.

  1. For @OneToMany, unidirectional associations don't perform as well as bidirectional ones.
  2. For @OneToOne, a bidirectional association will cause the parent to be fetched eagerly if Hibernate cannot tell whether the Proxy should be assigned or a null value.
  3. For @ManyToMany, the collection type makes quite a difference as Sets perform better than Lists.

java.io.IOException: Broken pipe

increase the response.getBufferSize() get the buffer size and compare with the bytes you want to transfer !

How to refresh or show immediately in datagridview after inserting?

Try below piece of code.

this.dataGridView1.RefreshEdit();

How might I extract the property values of a JavaScript object into an array?

Object.values() method is now supported. This will give you an array of values of an object.

Object.values(dataObject)

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

Understanding The Modulus Operator %

Two Steps Solution.

Some of the answers here are complicated for me to understand. I will try to add one more answer in an attempt to simplify the way how to look at this.


Short Answer:

Example 1:

7 % 5 = 2

Each person should get one pizza slice.

Divide 7 slices on 5 people and every one of the 5 people will get one pizza slice and we will end up with 2 slices (remaining). 7 % 5 equals 2 is because 7 is larger than 5.


Example 2:

5 % 7 = 5

Each person should get one pizza slice

It gives 5 because 5 is less than 7. So by definition, you cannot divide whole 5items on 7 people. So the division doesn't take place at all and you end up with the same amount you started with which is 5.


Programmatic Answer:

The process is basically to ask two questions:

Example A: (7 % 5)

(Q.1) What number to multiply 5 in order to get 7?

Two Conditions: Multiplier starts from `0`. Output result should not exceed `7`. 

Let's try:

Multiplier is zero 0 so, 0 x 5 = 0

Still, we are short so we add one (+1) to multiplier.

1 so, 1 x 5 = 5

We did not get 7 yet, so we add one (+1).

2 so, 2 x 5 = 10

Now we exceeded 7. So 2 is not the correct multiplier. Let's go back one step (where we used 1) and hold in mind the result which is5. Number 5 is the key here.

(Q.2) How much do we need to add to the 5 (the number we just got from step 1) to get 7?

We deduct the two numbers: 7-5 = 2.

So the answer for: 7 % 5 is 2;


Example B: (5 % 7)

1- What number we use to multiply 7 in order to get 5?

Two Conditions: Multiplier starts from `0`. Output result and should not exceed `5`. 

Let's try:

0 so, 0 x 7 = 0

We did not get 5 yet, let's try a higher number.

1 so, 1 x 7 = 7

Oh no, we exceeded 5, let's get back to the previous step where we used 0 and got the result 0.

2- How much we need to add to 0 (the number we just got from step 1) in order to reach the value of the number on the left 5?

It's clear that the number is 5. 5-0 = 5

   5 % 7 = 5

Hope that helps.

android pick images from gallery

Just to offer an update to the answer for people with API min 19, per the docs:

On Android 4.4 (API level 19) and higher, you have the additional option of using the ACTION_OPEN_DOCUMENT intent, which displays a system-controlled picker UI controlled that allows the user to browse all files that other apps have made available. From this single UI, the user can pick a file from any of the supported apps.

On Android 5.0 (API level 21) and higher, you can also use the ACTION_OPEN_DOCUMENT_TREE intent, which allows the user to choose a directory for a client app to access.

Open files using storage access framework - Android Docs

     val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
     intent.type = "image/*"
     startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE)

Java: Check if command line arguments are null

You should check for (args == null || args.length == 0). Although the null check isn't really needed, it is a good practice.

how to call url of any other website in php

If you meant .. to REDIRECT from that page to another, the function is really simple

header("Location:www.google.com");

What is MVC and what are the advantages of it?

One con I can think of is if you need really fast access to your data in your view (for example, game animation data like bone positions.) It is very inefficient to keep a layer of separation in this case.

Otherwise, for most other applications which are more data driven than graphics driven, it seems like a logical way to drive a UI.

GitLab git user password

On my Windows 10 machine it was because the SSH_GIT environment variable wasn't set to use the putty plink I had installed on my machine.

SVN Repository on Google Drive or DropBox

While possible, it's potentially very risky - if you attempt to commit changes to the repository from 2 different locations simultaneously, you'll get a giant mess due to the file conflicts. Get a free private SVN host somewhere, or set up a repository on a server you have access to.

Edit based on a recent experience: If you have files open that are managed by Dropbox and your computer crashes, your files may be truncated to 0 bytes. If this happens to the files which manage your repository, your repository will be corrupted. If you discover this soon enough, you can use Dropbox's "recover old version" feature but you're still taking a risk.

How do you change the character encoding of a postgres database?

Dumping a database with a specific encoding and try to restore it on another database with a different encoding could result in data corruption. Data encoding must be set BEFORE any data is inserted into the database.

Check this : When copying any other database, the encoding and locale settings cannot be changed from those of the source database, because that might result in corrupt data.

And this : Some locale categories must have their values fixed when the database is created. You can use different settings for different databases, but once a database is created, you cannot change them for that database anymore. LC_COLLATE and LC_CTYPE are these categories. They affect the sort order of indexes, so they must be kept fixed, or indexes on text columns would become corrupt. (But you can alleviate this restriction using collations, as discussed in Section 22.2.) The default values for these categories are determined when initdb is run, and those values are used when new databases are created, unless specified otherwise in the CREATE DATABASE command.


I would rather rebuild everything from the begining properly with a correct local encoding on your debian OS as explained here :

su root

Reconfigure your local settings :

dpkg-reconfigure locales

Choose your locale (like for instance for french in Switzerland : fr_CH.UTF8)

Uninstall and clean properly postgresql :

apt-get --purge remove postgresql\*
rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/
userdel -r postgres
groupdel postgres

Re-install postgresql :

aptitude install postgresql-9.1 postgresql-contrib-9.1 postgresql-doc-9.1

Now any new database will be automatically be created with correct encoding, LC_TYPE (character classification), and LC_COLLATE (string sort order).

How do I pass options to the Selenium Chrome driver using Python?

Code which disable chrome extensions for ones, who uses DesiredCapabilities to set browser flags :

desired_capabilities['chromeOptions'] = {
    "args": ["--disable-extensions"],
    "extensions": []
}
webdriver.Chrome(desired_capabilities=desired_capabilities)

How can I start and check my MySQL log?

Enable general query log by the following query in mysql command line

SET GLOBAL general_log = 'ON';

Now open C:/xampp/mysql/data/mysql.log and check query log

If it fails, open your my.cnf file. For windows its my.ini file and enable it there. Just make sure its in the [mysqld] section

[mysqld]
general_log             = 1

Note: In xampp my.ini file can be either found in xampp\mysql or in c:\windows directory

How do I style a <select> dropdown with only CSS?

label {
    position: relative;
    display: inline-block;
}
select {
    display: inline-block;
    padding: 4px 3px 5px 5px;
    width: 150px;
    outline: none;
    color: black;
    border: 1px solid #C8BFC4;
    border-radius: 4px;
    box-shadow: inset 1px 1px 2px #ddd8dc;
    background-color: lightblue;
}

This uses a background color for select elements and I removed the image..

TypeError: 'float' object is not subscriptable

PriceList[0] is a float. PriceList[0][1] is trying to access the first element of a float. Instead, do

PriceList[0] = PriceList[1] = ...code omitted... = PriceList[6] = PizzaChange

or

PriceList[0:7] = [PizzaChange]*7

"unmappable character for encoding" warning in Java

Gradle Steps

If you are using Gradle then you can find the line that applies the java plugin:

apply plugin: 'java'

Then set the encoding for the compile task to be UTF-8:

compileJava {options.encoding = "UTF-8"}   

If you have unit tests, then you probably want to compile those with UTF-8 too:

compileTestJava {options.encoding = "UTF-8"}

Overall Gradle Example

This means that the overall gradle code would look something like this:

apply plugin: 'java'
compileJava {options.encoding = "UTF-8"}
compileTestJava {options.encoding = "UTF-8"}

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

Windows batch: formatted date into variable

I really liked Joey's method, but I thought I'd expand upon it a bit.

In this approach, you can run the code multiple times and not worry about the old date value "sticking around" because it's already defined.

Each time you run this batch file, it will output an ISO 8601 compatible combined date and time representation.

FOR /F "skip=1" %%D IN ('WMIC OS GET LocalDateTime') DO (SET LIDATE=%%D & GOTO :GOT_LIDATE)
:GOT_LIDATE
SET DATETIME=%LIDATE:~0,4%-%LIDATE:~4,2%-%LIDATE:~6,2%T%LIDATE:~8,2%:%LIDATE:~10,2%:%LIDATE:~12,2%
ECHO %DATETIME%

In this version, you'll have to be careful not to copy/paste the same code to multiple places in the file because that would cause duplicate labels. You could either have a separate label for each copy, or just put this code into its own batch file and call it from your source file wherever necessary.

Generating random whole numbers in JavaScript in a specific range?

Ionu? G. Stan wrote a great answer but it was a bit too complex for me to grasp. So, I found an even simpler explanation of the same concepts at https://teamtreehouse.com/community/mathfloor-mathrandom-max-min-1-min-explanation by Jason Anello.

NOTE: The only important thing you should know before reading Jason's explanation is a definition of "truncate". He uses that term when describing Math.floor(). Oxford dictionary defines "truncate" as:

Shorten (something) by cutting off the top or end.

ADB.exe is obsolete and has serious performance problems

I had the same problem and solved it by updating the Android SDK Build-Tools. Open the SDK manager in Android studio (double shift and type SDK manager). Then on the second tab (SDK Tools) update the Android SDK Build-Tools and the error message should go away.

jquery how to empty input field

if you hit the "back" button it usually tends to stick, what you can do is when the form is submitted clear the element then before it goes to the next page but after doing with the element what you need to.

    $('#shares').keyup(function(){
                payment = 0;
                calcTotal();
                gtotal = ($('#shares').val() * 1) + payment;
                gtotal = gtotal.toFixed(2);
                $('#shares').val('');
                $("p.total").html("Total Payment: <strong>" + gtotal + "</strong>");
            });

What's the Use of '\r' escape sequence?

It is quite useful, when you are running on the unix platform, and need to create a text file which will be opened on the dos platform.

Unix uses '\n' as its line terminator, and dos uses '\r\n' as its line terminator, so you can use it to create a dos text file.

What does upstream mean in nginx?

upstream defines a cluster that you can proxy requests to. It's commonly used for defining either a web server cluster for load balancing, or an app server cluster for routing / load balancing.

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

I had a similar problem. Using size_t was not working. I tried the other one which worked for me. (as below)

for(int i = things.size()-1;i>=0;i--)
{
 //...
}

I have never set any passwords to my keystore and alias, so how are they created?

if you want to configure them in gradle it should look like

signingConfigs {
        debug {
            storeFile file('PATH_TO_HOME/.android/debug.keystore')
            storePassword 'android'                   
            keyAlias 'AndroidDebugKey'
            keyPassword 'android'                     
        }
        ...
}

Blurring an image via CSS?

img {
  filter: blur(var(--blur));
}

How to get english language word database?

You can find what you need on infochimps.org.

They have a list of 350,000 simple (ie non-compound) words available for free download.

Word List - 350,000+ Simple English Words

Regarding other languages, you might want to poke around on Wiktionary. Here is a link to all the database backups - the information isnt organized so likely but if they have a language, you can download the data in SQL format.

CSS display:table-row does not expand when width is set to 100%

You can nest table-cell directly within table. You muslt have a table. Starting eith table-row does not work. Try it with this HTML:

<html>
  <head>
    <style type="text/css">
.table {
  display: table;
  width: 100%;
}
.tr {
  display: table-row;
  width: 100%;
}
.td {
  display: table-cell;
}
    </style>
  </head>
  <body>

    <div class="table">
      <div class="tr">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
      </div>
    </div>

      <div class="tr">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
      </div>

    <div class="table">
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
        <div class="td">
          X
        </div>
    </div>

  </body>
</html>

Is there a jQuery unfocus method?

Based on your question, I believe the answer is how to trigger a blur, not just (or even) set the event:

 $('#textArea').trigger('blur');

smtp configuration for php mail

Since some of the answers give here relate to setting up SMTP in general (and not just for @shinod particular issue where it had been working and stopped), I thought it would be helpful if I updated the answer because this is a lot simpler to do now than it used to be :-)

In PHP 4 the PEAR Mail package is typically already installed, and this really simple tutorial shows you the few lines of code that you need to add to your php file http://email.about.com/od/emailprogrammingtips/qt/PHP_Email_SMTP_Authentication.htm

Most hosting companies list the SMTP settings that you'll need. I use JustHost, and they list theirs at https://my.justhost.com/cgi/help/26 (under Outgoing Mail Server)

Is SQL syntax case sensitive?

SQL keywords are case insensitive themselves.

Names of tables, columns etc, have a case sensitivity which is database dependent - you should probably assume that they are case sensitive unless you know otherwise (In many databases they aren't though; in MySQL table names are SOMETIMES case sensitive but most other names are not).

Comparing data using =, >, < etc, has a case awareness which is dependent on the collation settings which are in use on the individual database, table or even column in question. It's normal however, to keep collation fairly consistent within a database. We have a few columns which need to store case-sensitive values; they have a collation specifically set.

Remove rows with all or some NAs (missing values) in data.frame

This will return the rows that have at least ONE non-NA value.

final[rowSums(is.na(final))<length(final),]

This will return the rows that have at least TWO non-NA value.

final[rowSums(is.na(final))<(length(final)-1),]

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

To show vertical scroll bar in your div you need to add

height: 100px;   
overflow-y : scroll;

or

height: 100px; 
overflow-y : auto;

What are some resources for getting started in operating system development?

Movitz is a Lisp environment written in Common Lisp and running "on the metal". Unfortunately, some links on the Movitz main page deny access, but you can find instructions on how to download and compile the source code from the trac page. Also, a ready image can be found on the archive of this page.

IMHO this is utmost interesting, as it brings back the Lisp machine concept on the currently available hardware. It failed commercially, but this does not prove to me that the idea was bad.

The Unix haters handbook is a fun book that semi-seriously berates the concept of Unix and its derivatives. Many sections argument about how better the Lisp machine concept was.

Installing MySQL in Docker fails with error message "Can't connect to local MySQL server through socket"

If you don't have MySQL installed on your host, you have to execute it in the container (https://docs.docker.com/engine/reference/commandline/exec/#/examples gives explanation about docker run vs docker exec).

Considering your container is running, you might use docker exec yourcontainername mysql -u root -p to access to the client.

Also, if you are using Docker Compose, and you've declared a mysql db service named database, you can use : docker-compose exec database mysql -u root -p

Java 8 NullPointerException in Collectors.toMap

I have slightly modified Emmanuel Touzery's implementation.

This version;

  • Allows null keys
  • Allows null values
  • Detects duplicate keys (even if they are null) and throws IllegalStateException as in the original JDK implementation.
  • Detects duplicate keys also when the key already mapped to the null value. In other words, separates a mapping with null-value from no-mapping.
public static <T, K, U> Collector<T, ?, Map<K, U>> toMapOfNullables(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) {
    return Collectors.collectingAndThen(
        Collectors.toList(),
        list -> {
            Map<K, U> map = new LinkedHashMap<>();
            list.forEach(item -> {
                K key = keyMapper.apply(item);
                if (map.containsKey(key)) {
                    throw new IllegalStateException(String.format("Duplicate key %s", key));
                }
                map.put(key, valueMapper.apply(item));
            });
            return map;
        }
    );
}

Unit tests:

@Test
public void toMapOfNullables_WhenHasNullKey() {
    assertEquals(singletonMap(null, "value"),
        Stream.of("ignored").collect(Utils.toMapOfNullables(i -> null, i -> "value"))
    );
}

@Test
public void toMapOfNullables_WhenHasNullValue() {
    assertEquals(singletonMap("key", null),
        Stream.of("ignored").collect(Utils.toMapOfNullables(i -> "key", i -> null))
    );
}

@Test
public void toMapOfNullables_WhenHasDuplicateNullKeys() {
    assertThrows(new IllegalStateException("Duplicate key null"),
        () -> Stream.of(1, 2, 3).collect(Utils.toMapOfNullables(i -> null, i -> i))
    );
}

@Test
public void toMapOfNullables_WhenHasDuplicateKeys_NoneHasNullValue() {
    assertThrows(new IllegalStateException("Duplicate key duplicated-key"),
        () -> Stream.of(1, 2, 3).collect(Utils.toMapOfNullables(i -> "duplicated-key", i -> i))
    );
}

@Test
public void toMapOfNullables_WhenHasDuplicateKeys_OneHasNullValue() {
    assertThrows(new IllegalStateException("Duplicate key duplicated-key"),
        () -> Stream.of(1, null, 3).collect(Utils.toMapOfNullables(i -> "duplicated-key", i -> i))
    );
}

@Test
public void toMapOfNullables_WhenHasDuplicateKeys_AllHasNullValue() {
    assertThrows(new IllegalStateException("Duplicate key duplicated-key"),
        () -> Stream.of(null, null, null).collect(Utils.toMapOfNullables(i -> "duplicated-key", i -> i))
    );
}

Visual Studio Code: How to show line endings

AFAIK there is no way to visually see line endings in the editor space, but in the bottom-right corner of the window there is an indicator that says "CLRF" or "LF" which will let you set the line endings for a particular file. Clicking on the text will allow you to change the line endings as well.

enter image description here

What is the best way to search the Long datatype within an Oracle database?

First convert LONG type column to CLOB type then use LIKE condition, for example:

CREATE TABLE tbl_clob AS
   SELECT to_lob(long_col) lob_col FROM tbl_long;

SELECT * FROM tbl_clob WHERE lob_col LIKE '%form%';

Trying to get Laravel 5 email to work

I've had the same problem; my MAIL_ENCRYPTION was tls on mail.php but it was null on .env file.
So I changed null to tls and it worked!

How to select the last record of a table in SQL?

select ADU.itemid, ADU.startdate, internalcostprice 
from ADUITEMINTERNALCOSTPRICE ADU

right join

   (select max(STARTDATE) as Max_date, itemid 
   from ADUITEMINTERNALCOSTPRICE
   group by itemid) as A

on A.ITEMID = ADU.ITEMID
and startdate= Max_date

Custom HTTP Authorization Header

Put it in a separate, custom header.

Overloading the standard HTTP headers is probably going to cause more confusion than it's worth, and will violate the principle of least surprise. It might also lead to interoperability problems for your API client programmers who want to use off-the-shelf tool kits that can only deal with the standard form of typical HTTP headers (such as Authorization).

How to concatenate strings in twig

Quick Answer (TL;DR)

  • Twig string concatenation may also be done with the format() filter

Detailed Answer

Context

  • Twig 2.x
  • String building and concatenation

Problem

  • Scenario: DeveloperGailSim wishes to do string concatenation in Twig
    • Other answers in this thread already address the concat operator
    • This answer focuses on the format filter which is more expressive

Solution

  • Alternative approach is to use the format filter
  • The format filter works like the sprintf function in other programming languages
  • The format filter may be less cumbersome than the ~ operator for more complex strings

Example00

  • example00 string concat bare

    
    {{ "%s%s%s!"|format('alpha','bravo','charlie') }}
    
    --- result --
    
    alphabravocharlie!
    
    

Example01

  • example01 string concat with intervening text

    
    {{ "The %s in %s falls mainly on the %s!"|format('alpha','bravo','charlie') }}
    
    --- result --
    
    The alpha in bravo falls mainly on the charlie!
    
    

Example02

  • example02 string concat with numeric formatting
  • follows the same syntax as sprintf in other languages

    
    {{ "The %04d in %04d falls mainly on the %s!"|format(2,3,'tree') }}
    
    --- result --
    
    The 0002 in 0003 falls mainly on the tree!
    
    

See also

Assert that a WebElement is not present using Selenium WebDriver with java

With Selenium Webdriver would be something like this:

assertTrue(!isElementPresent(By.linkText("Empresas en Misión")));

What are the aspect ratios for all Android phone and tablet devices?

I researched the same thing several months ago looking at dozens of the most popular Android devices. I found that every Android device had one of the following aspect ratios (from most square to most rectangular):

  • 4:3
  • 3:2
  • 8:5
  • 5:3
  • 16:9

And if you consider portrait devices separate from landscape devices you'll also find the inverse of those ratios (3:4, 2:3, 5:8, 3:5, and 9:16)


More complete answer here: stackoverflow community spreadsheet of Android device resolutions and DPIs

How do I fix the indentation of selected lines in Visual Studio

I like Ctrl+K, Ctrl+D, which indents the whole document.

How to ignore certain files in Git

1) Create a .gitignore file. To do that, you just create a .txt file and change the extension as follows:

Enter image description here

Then you have to change the name, writing the following line in a cmd window:

 rename git.txt .gitignore

Where git.txt is the name of the file you've just created.

Then you can open the file and write all the files you don’t want to add on the repository. For example, mine looks like this:

#OS junk files
[Tt]humbs.db
*.DS_Store

#Visual Studio files
*.[Oo]bj
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.sdf
*.pyc
*.xml
ipch/
obj/
[Bb]in
[Dd]ebug*/
[Rr]elease*/
Ankh.NoLoad

#Tooling
_ReSharper*/
*.resharper
[Tt]est[Rr]esult*

#Project files
[Bb]uild/

#Subversion files
.svn

# Office Temp Files
~$*

Once you have this, you need to add it to your Git repository. You have to save the file where your repository is.

Then in Git Bash you have to write the following line:

git config --global core.excludesfile ~/.gitignore_global

If the repository already exists then you have to do the following:

  1. git rm -r --cached .
  2. git add .
  3. git commit -m ".gitignore is now working"

If the step 2 doesn’t work then you should write the whole route of the files that you would like to add.

Is it possible to display my iPhone on my computer monitor?

use screensplitr on jailbrocken iphone/ipod touch it works

How do I start/stop IIS Express Server?

Here is a static class implementing Start(), Stop(), and IsStarted() for IISExpress. It is parametrized by hard-coded static properties and passes invocation information via the command-line arguments to IISExpress. It uses the Nuget package, MissingLinq.Linq2Management, which surprisingly provides information missing from System.Diagnostics.Process, specifically, the command-line arguments that can then be used to help disambiguate possible multiple instances of IISExpress processes, since I don't preserve the process Ids. I presume there is a way to accomplish the same thing with just System.Diagnostics.Process, but life is short. Enjoy.

using System.Diagnostics;
using System.IO;
using System.Threading;
using MissingLinq.Linq2Management.Context;
using MissingLinq.Linq2Management.Model.CIMv2;

public static class IisExpress
{
  #region Parameters
  public static string SiteFolder = @"C:\temp\UE_Soln_7\Spc.Frm.Imp";
  public static uint Port = 3001;
  public static int ProcessStateChangeDelay = 10 * 1000;
  public static string IisExpressExe = @"C:\Program Files (x86)\IIS Express\iisexpress.exe";
  #endregion

  public static void Start()
  {
    Process.Start(InvocationInfo);
    Thread.Sleep(ProcessStateChangeDelay);
  }
  public static void Stop()
  {
    var p = GetWin32Process();
    if (p == null) return;

    var pp = Process.GetProcessById((int)p.ProcessId);
    if (pp == null) return;

    pp.Kill();
    Thread.Sleep(ProcessStateChangeDelay);
  }
  public static bool IsStarted()
  {
    var p = GetWin32Process();
    return p != null;
  }

  static readonly string ProcessName = Path.GetFileName(IisExpressExe);
  static string Quote(string value) { return "\"" + value.Trim() + "\""; }
  static string CmdLine =
    string.Format(
      @"/path:{0} /port:{1}",
      Quote(SiteFolder),
      Port
      );
  static readonly ProcessStartInfo InvocationInfo =
    new ProcessStartInfo()
      {
        FileName = IisExpressExe,
        Arguments = CmdLine,
        WorkingDirectory = SiteFolder,
        CreateNoWindow = false,
        UseShellExecute = true,
        WindowStyle = ProcessWindowStyle.Minimized
      };
  static Win32Process GetWin32Process()
  {
    //the linq over ManagementObjectContext implementation is simplistic so we do foreach instead
    using (var mo = new ManagementObjectContext())
      foreach (var p in mo.CIMv2.Win32Processes)
        if (p.Name == ProcessName && p.CommandLine.Contains(CmdLine))
          return p;
    return null;
  }
}

How do I install the ext-curl extension with PHP 7?

We can install any PHP7 Extensions which we are needed at the time of install Magento just use related command which you get error at the time of installin Magento

sudo apt-get install php7.0-curl
sudo apt-get install php7.0-dom
sudo apt-get install php7.0-mcrypt
sudo apt-get install php7.0-simplexml
sudo apt-get install php7.0-spl
sudo apt-get install php7.0-xsl
sudo apt-get install php7.0-intl
sudo apt-get install php7.0-mbstring
sudo apt-get install php7.0-ctype
sudo apt-get install php7.0-hash
sudo apt-get install php7.0-openssl
sudo apt-get install php7.0-zip
sudo apt-get install php7.0-xmlwriter
sudo apt-get install php7.0-gd
sudo apt-get install php7.0-iconv

Thanks! Hope this will help you